4 # Copyright 2000-2002 Katipo Communications
5 # Copyright 2004-2010 BibLibre
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #use warnings; FIXME - Bug 2505
30 use C4::Koha; # XXX subfield_is_koha_internal_p
31 use C4::Branch; # XXX subfield_is_koha_internal_p
34 use List::MoreUtils qw/any/;
38 my $dbh = C4::Context->dbh;
41 my ($tagfield,$insubfield,$record) = @_;
44 foreach my $field ($record->field($tagfield)) {
45 my @subfields = $field->subfields();
46 foreach my $subfield (@subfields) {
47 if (@$subfield[0] eq $insubfield) {
48 $result .= @$subfield[1];
49 $indicator = $field->indicator(1).$field->indicator(2);
53 return($indicator,$result);
56 sub get_item_from_barcode {
58 my $dbh=C4::Context->dbh;
60 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
61 $rq->execute($barcode);
62 ($result)=$rq->fetchrow;
66 sub set_item_default_location {
67 my $itemnumber = shift;
68 my $item = GetItem( $itemnumber );
69 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
70 $item->{'permanent_location'} = $item->{'location'};
71 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
72 ModItem( $item, undef, $itemnumber);
75 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
76 ModItem( $item, undef, $itemnumber);
80 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
81 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
82 sub _increment_barcode {
83 my ($record, $frameworkcode) = @_;
84 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
85 unless ($record->field($tagfield)->subfield($tagsubfield)) {
86 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
87 $sth_barcode->execute;
88 my ($newbarcode) = $sth_barcode->fetchrow;
90 # OK, we have the new barcode, now create the entry in MARC record
91 my $fieldItem = $record->field($tagfield);
92 $record->delete_field($fieldItem);
93 $fieldItem->add_subfields($tagsubfield => $newbarcode);
94 $record->insert_fields_ordered($fieldItem);
100 sub generate_subfield_form {
101 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i) = @_;
104 my $dbh = C4::Context->dbh;
105 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
107 my $index_subfield = int(rand(1000000));
108 if ($subfieldtag eq '@'){
109 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
111 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
114 $subfield_data{tag} = $tag;
115 $subfield_data{subfield} = $subfieldtag;
116 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
117 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
118 $subfield_data{mandatory} = $subfieldlib->{mandatory};
119 $subfield_data{repeatable} = $subfieldlib->{repeatable};
121 $value =~ s/"/"/g;
122 if ( ! defined( $value ) || $value eq '') {
123 $value = $subfieldlib->{defaultvalue};
124 # get today date & replace YYYY, MM, DD if provided in the default value
125 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
126 $value =~ s/YYYY/$year/g;
127 $value =~ s/MM/$month/g;
128 $value =~ s/DD/$day/g;
131 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
133 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
134 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
135 my $CNtag = substr($pref_itemcallnumber, 0, 3);
136 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
137 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
138 my $temp2 = $temp->field($CNtag);
140 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
141 #remove any trailing space incase one subfield is used
142 $value =~ s/^\s+|\s+$//g;
146 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
147 my $attributes = qq($attributes_no_value value="$value" );
149 if ( $subfieldlib->{authorised_value} ) {
150 my @authorised_values;
152 # builds list, depending on authorised value...
153 if ( $subfieldlib->{authorised_value} eq "branches" ) {
154 foreach my $thisbranch (@$branches) {
155 push @authorised_values, $thisbranch->{value};
156 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
157 $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
160 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
161 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
162 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
164 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
165 push @authorised_values, $itemtype;
166 $authorised_lib{$itemtype} = $description;
170 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
171 $itype_sth->execute( $biblionumber );
172 ( $value ) = $itype_sth->fetchrow_array;
177 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
178 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
180 my $class_sources = GetClassSources();
181 my $default_source = C4::Context->preference("DefaultClassificationSource");
183 foreach my $class_source (sort keys %$class_sources) {
184 next unless $class_sources->{$class_source}->{'used'} or
185 ($value and $class_source eq $value) or
186 ($class_source eq $default_source);
187 push @authorised_values, $class_source;
188 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
190 $value = $default_source unless ($value);
192 #---- "true" authorised value
195 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
196 $authorised_values_sth->execute( $subfieldlib->{authorised_value} );
197 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
198 push @authorised_values, $value;
199 $authorised_lib{$value} = $lib;
203 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
204 -name => "field_value",
205 -values => \@authorised_values,
207 -labels => \%authorised_lib,
212 -id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
213 -class => "input_marceditor",
216 # it's a thesaurus / authority field
218 elsif ( $subfieldlib->{authtypecode} ) {
219 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
220 <a href=\"#\" class=\"buttonDot\"
221 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>
223 # it's a plugin field
225 elsif ( $subfieldlib->{value_builder} ) {
227 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
229 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
230 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
231 my $change = index($javascript, 'function Change') > -1 ?
232 "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
234 $subfield_data{marc_value} = qq[<input $attributes
235 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
237 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
238 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
241 warn "Plugin Failed: $plugin";
242 $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
245 elsif ( $tag eq '' ) { # it's an hidden field
246 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
248 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
249 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
251 elsif ( length($value) > 100
252 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
253 300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
254 or (C4::Context->preference("marcflavour") eq "MARC21" and
255 500 <= $tag && $tag < 600 )
257 # oversize field (textarea)
258 $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
260 # it's a standard field
261 $subfield_data{marc_value} = "<input $attributes />";
264 return \%subfield_data;
269 my $error = $input->param('error');
270 my $biblionumber = $input->param('biblionumber');
271 my $itemnumber = $input->param('itemnumber');
272 my $op = $input->param('op');
274 my $frameworkcode = &GetFrameworkCode($biblionumber);
276 # Defining which userflag is needing according to the framework currently used
278 if (defined $input->param('frameworkcode')) {
279 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
282 if (not defined $userflags) {
283 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
286 my ($template, $loggedinuser, $cookie)
287 = get_template_and_user({template_name => "cataloguing/additem.tmpl",
290 authnotrequired => 0,
291 flagsrequired => {editcatalogue => $userflags},
296 my $today_iso = C4::Dates->today('iso');
297 $template->param(today_iso => $today_iso);
299 my $tagslib = &GetMarcStructure(1,$frameworkcode);
300 my $record = GetMarcBiblio($biblionumber);
301 my $oldrecord = TransformMarcToKoha($dbh,$record);
303 my $nextop="additem";
304 my @errors; # store errors found while checking data BEFORE saving item.
305 #-------------------------------------------------------------------------------
306 if ($op eq "additem") {
307 #-------------------------------------------------------------------------------
309 my @tags = $input->param('tag');
310 my @subfields = $input->param('subfield');
311 my @values = $input->param('field_value');
312 # build indicator hash.
313 my @ind_tag = $input->param('ind_tag');
314 my @indicator = $input->param('indicator');
315 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
316 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
319 my $add_submit = $input->param('add_submit');
320 my $add_duplicate_submit = $input->param('add_duplicate_submit');
321 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
322 my $number_of_copies = $input->param('number_of_copies');
324 if (C4::Context->preference('autoBarcode') eq 'incremental') {
325 $record = _increment_barcode($record, $frameworkcode);
328 my $addedolditem = TransformMarcToKoha($dbh,$record);
330 # If we have to add or add & duplicate, we add the item
331 if ($add_submit || $add_duplicate_submit) {
332 # check for item barcode # being unique
333 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
334 push @errors,"barcode_not_unique" if($exist_itemnumber);
335 # if barcode exists, don't create, but report The problem.
336 unless ($exist_itemnumber) {
337 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
338 set_item_default_location($oldbibitemnum);
341 if ($exist_itemnumber) {
342 $itemrecord = $record;
346 # If we have to add & duplicate
347 if ($add_duplicate_submit) {
348 $itemrecord = $record;
349 if (C4::Context->preference('autoBarcode') eq 'incremental') {
350 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
353 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
354 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
355 my $fieldItem = $itemrecord->field($tagfield);
356 $itemrecord->delete_field($fieldItem);
357 $fieldItem->delete_subfields($tagsubfield);
358 $itemrecord->insert_fields_ordered($fieldItem);
362 # If we have to add multiple copies
363 if ($add_multiple_copies_submit) {
366 my $barcodeobj = C4::Barcodes->new;
367 my $oldbarcode = $addedolditem->{'barcode'};
368 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
370 # If there is a barcode and we can't find him new values, we can't add multiple copies
371 my $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
372 if ($oldbarcode && !$testbarcode) {
374 push @errors, "no_next_barcode";
375 $itemrecord = $record;
380 # For the first iteration
381 my $barcodevalue = $oldbarcode;
382 my $exist_itemnumber;
385 for (my $i = 0; $i < $number_of_copies;) {
387 # If there is a barcode
390 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
391 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
393 # Putting it into the record
395 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
398 # Checking if the barcode already exists
399 $exist_itemnumber = get_item_from_barcode($barcodevalue);
403 if (!$exist_itemnumber) {
404 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
405 set_item_default_location($oldbibitemnum);
407 # We count the item only if it was really added
408 # That way, all items are added, even if there was some already existing barcodes
409 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
413 # Preparing the next iteration
414 $oldbarcode = $barcodevalue;
421 #-------------------------------------------------------------------------------
422 } elsif ($op eq "edititem") {
423 #-------------------------------------------------------------------------------
424 # retrieve item if exist => then, it's a modif
425 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
426 $nextop = "saveitem";
427 #-------------------------------------------------------------------------------
428 } elsif ($op eq "delitem") {
429 #-------------------------------------------------------------------------------
430 # check that there is no issue on this item before deletion.
431 $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
433 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
438 #-------------------------------------------------------------------------------
439 } elsif ($op eq "delallitems") {
440 #-------------------------------------------------------------------------------
441 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
444 foreach my $biblioitem (@biblioitems) {
445 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
447 foreach my $item (@$items) {
448 $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
462 print $input->redirect("/cgi-bin/koha/catalogue/moredetail.pl?biblionumber=$biblionumber");
466 #-------------------------------------------------------------------------------
467 } elsif ($op eq "saveitem") {
468 #-------------------------------------------------------------------------------
470 my @tags = $input->param('tag');
471 my @subfields = $input->param('subfield');
472 my @values = $input->param('field_value');
473 # build indicator hash.
474 my @ind_tag = $input->param('ind_tag');
475 my @indicator = $input->param('indicator');
476 # my $itemnumber = $input->param('itemnumber');
477 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
478 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
479 # MARC::Record builded => now, record in DB
480 # warn "R: ".$record->as_formatted;
481 # check that the barcode don't exist already
482 my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
483 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
484 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
485 push @errors,"barcode_not_unique";
487 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
494 #-------------------------------------------------------------------------------
495 # build screen with existing items. and "new" one
496 #-------------------------------------------------------------------------------
498 # now, build existiing item list
499 my $temp = GetMarcBiblio( $biblionumber );
500 #my @fields = $record->fields();
501 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
503 #---- finds where items.itemnumber is stored
504 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
505 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
506 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
507 my @fields = $temp->fields();
509 foreach my $field (@fields) {
510 next if ( $field->tag() < 10 );
512 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
514 # loop through each subfield
516 foreach my $subfield (@subf){
517 my $subfieldcode = $subfield->[0];
518 my $subfieldvalue= $subfield->[1];
520 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
521 && ($field->tag() ne $itemtagfield
522 && $subfieldcode ne $itemtagsubfield));
523 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
524 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
525 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
526 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
527 $subfieldcode, $subfieldvalue, '', $tagslib)
531 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
533 my $userenv = C4::Context->userenv();
534 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
535 $this_row{'nomod'} = 1;
538 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
541 push(@big_array, \%this_row);
545 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
546 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
548 # now, construct template !
549 # First, the existing items for display
551 my @header_value_loop;
552 for my $row ( @big_array ) {
554 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
555 $row_data{item_value} = [ @item_fields ];
556 $row_data{itemnumber} = $row->{itemnumber};
557 #reporting this_row values
558 $row_data{'nomod'} = $row->{'nomod'};
559 push(@item_value_loop,\%row_data);
561 foreach my $subfield_code (sort keys(%witness)) {
563 $header_value{header_value} = $witness{$subfield_code};
564 push(@header_value_loop, \%header_value);
567 # now, build the item form for entering a new item
571 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
573 my $onlymine = C4::Context->preference('IndependantBranches') &&
574 C4::Context->userenv &&
575 C4::Context->userenv->{flags}!=1 &&
576 C4::Context->userenv->{branch};
577 my $branches = GetBranchesLoop(C4::Context->userenv->{branch},$onlymine); # build once ahead of time, instead of multiple times later.
579 # We generate form, from actuel record
582 foreach my $field ($itemrecord->fields()){
583 my $tag = $field->{_tag};
584 foreach my $subfield ( $field->subfields() ){
586 my $subfieldtag = $subfield->[0];
587 my $value = $subfield->[1];
588 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
590 next if subfield_is_koha_internal_p($subfieldtag);
591 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
593 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
595 push @fields, "$tag$subfieldtag";
596 push (@loop_data, $subfield_data);
602 # and now we add fields that are empty
604 foreach my $tag ( keys %{$tagslib}){
605 foreach my $subtag (keys %{$tagslib->{$tag}}){
606 next if subfield_is_koha_internal_p($subtag);
607 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
608 next if any { /^$tag$subtag$/ } @fields;
610 my @values = (undef);
611 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)->subfield($subtag)));
612 for my $value (@values){
613 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
614 push (@loop_data, $subfield_data);
619 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
621 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
622 $template->param( title => $record->title() ) if ($record ne "-1");
624 biblionumber => $biblionumber,
625 title => $oldrecord->{title},
626 author => $oldrecord->{author},
627 item_loop => \@item_value_loop,
628 item_header_loop => \@header_value_loop,
630 itemnumber => $itemnumber,
631 itemtagfield => $itemtagfield,
632 itemtagsubfield => $itemtagsubfield,
634 opisadd => ($nextop eq "saveitem") ? 0 : 1,
635 C4::Search::enabled_staff_search_views,
637 foreach my $error (@errors) {
638 $template->param($error => 1);
640 output_html_with_http_headers $input, $cookie, $template->output;