3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #use warnings; FIXME - Bug 2505
28 use C4::Dates qw/format_date format_date_in_iso/;
32 use List::MoreUtils qw/any/;
34 use DateTime::Format::MySQL;
35 use Data::Dumper; # used as part of logging item record changes, not just for
36 # debugging; so please don't remove this
37 use Koha::DateUtils qw/dt_from_string/;
39 use vars qw($VERSION @ISA @EXPORT);
42 $VERSION = 3.07.00.049;
45 @ISA = qw( Exporter );
68 GetItemsByBiblioitemnumber
72 GetItemnumbersForBiblio
74 get_hostitemnumbers_of
75 GetItemnumberFromBarcode
76 GetBarcodeFromItemnumber
90 PrepareItemrecordDisplay
97 C4::Items - item management functions
101 This module contains an API for manipulating item
102 records in Koha, and is used by cataloguing, circulation,
103 acquisitions, and serials management.
105 A Koha item record is stored in two places: the
106 items table and embedded in a MARC tag in the XML
107 version of the associated bib record in C<biblioitems.marcxml>.
108 This is done to allow the item information to be readily
109 indexed (e.g., by Zebra), but means that each item
110 modification transaction must keep the items table
111 and the MARC XML in sync at all times.
113 Consequently, all code that creates, modifies, or deletes
114 item records B<must> use an appropriate function from
115 C<C4::Items>. If no existing function is suitable, it is
116 better to add one to C<C4::Items> than to use add
117 one-off SQL statements to add or modify items.
119 The items table will be considered authoritative. In other
120 words, if there is ever a discrepancy between the items
121 table and the MARC XML, the items table should be considered
124 =head1 HISTORICAL NOTE
126 Most of the functions in C<C4::Items> were originally in
127 the C<C4::Biblio> module.
129 =head1 CORE EXPORTED FUNCTIONS
131 The following functions are meant for use by users
138 $item = GetItem($itemnumber,$barcode,$serial);
140 Return item information, for a given itemnumber or barcode.
141 The return value is a hashref mapping item column
142 names to values. If C<$serial> is true, include serial publication data.
147 my ($itemnumber,$barcode, $serial) = @_;
148 my $dbh = C4::Context->dbh;
152 my $sth = $dbh->prepare("
154 WHERE itemnumber = ?");
155 $sth->execute($itemnumber);
156 $data = $sth->fetchrow_hashref;
158 my $sth = $dbh->prepare("
162 $sth->execute($barcode);
163 $data = $sth->fetchrow_hashref;
166 return unless ( $data );
169 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
170 $ssth->execute($data->{'itemnumber'}) ;
171 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
173 #if we don't have an items.itype, use biblioitems.itemtype.
174 if( ! $data->{'itype'} ) {
175 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
176 $sth->execute($data->{'biblionumber'});
177 ($data->{'itype'}) = $sth->fetchrow_array;
184 CartToShelf($itemnumber);
186 Set the current shelving location of the item record
187 to its stored permanent shelving location. This is
188 primarily used to indicate when an item whose current
189 location is a special processing ('PROC') or shelving cart
190 ('CART') location is back in the stacks.
195 my ( $itemnumber ) = @_;
197 unless ( $itemnumber ) {
198 croak "FAILED CartToShelf() - no itemnumber supplied";
201 my $item = GetItem($itemnumber);
202 if ( $item->{location} eq 'CART' ) {
203 $item->{location} = $item->{permanent_location};
204 ModItem($item, undef, $itemnumber);
210 ShelfToCart($itemnumber);
212 Set the current shelving location of the item
213 to shelving cart ('CART').
218 my ( $itemnumber ) = @_;
220 unless ( $itemnumber ) {
221 croak "FAILED ShelfToCart() - no itemnumber supplied";
224 my $item = GetItem($itemnumber);
225 $item->{'location'} = 'CART';
226 ModItem($item, undef, $itemnumber);
229 =head2 AddItemFromMarc
231 my ($biblionumber, $biblioitemnumber, $itemnumber)
232 = AddItemFromMarc($source_item_marc, $biblionumber);
234 Given a MARC::Record object containing an embedded item
235 record and a biblionumber, create a new item record.
239 sub AddItemFromMarc {
240 my ( $source_item_marc, $biblionumber ) = @_;
241 my $dbh = C4::Context->dbh;
243 # parse item hash from MARC
244 my $frameworkcode = GetFrameworkCode( $biblionumber );
245 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
247 my $localitemmarc=MARC::Record->new;
248 $localitemmarc->append_fields($source_item_marc->field($itemtag));
249 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
250 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
251 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
256 my ($biblionumber, $biblioitemnumber, $itemnumber)
257 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
259 Given a hash containing item column names as keys,
260 create a new Koha item record.
262 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
263 do not need to be supplied for general use; they exist
264 simply to allow them to be picked up from AddItemFromMarc.
266 The final optional parameter, C<$unlinked_item_subfields>, contains
267 an arrayref containing subfields present in the original MARC
268 representation of the item (e.g., from the item editor) that are
269 not mapped to C<items> columns directly but should instead
270 be stored in C<items.more_subfields_xml> and included in
271 the biblio items tag for display and indexing.
277 my $biblionumber = shift;
279 my $dbh = @_ ? shift : C4::Context->dbh;
280 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
281 my $unlinked_item_subfields;
283 $unlinked_item_subfields = shift
286 # needs old biblionumber and biblioitemnumber
287 $item->{'biblionumber'} = $biblionumber;
288 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
289 $sth->execute( $item->{'biblionumber'} );
290 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
292 _set_defaults_for_add($item);
293 _set_derived_columns_for_add($item);
294 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
295 # FIXME - checks here
296 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
297 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
298 $itype_sth->execute( $item->{'biblionumber'} );
299 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
302 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
303 $item->{'itemnumber'} = $itemnumber;
305 ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
307 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
309 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
312 =head2 AddItemBatchFromMarc
314 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
315 $biblionumber, $biblioitemnumber, $frameworkcode);
317 Efficiently create item records from a MARC biblio record with
318 embedded item fields. This routine is suitable for batch jobs.
320 This API assumes that the bib record has already been
321 saved to the C<biblio> and C<biblioitems> tables. It does
322 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
323 are populated, but it will do so via a call to ModBibiloMarc.
325 The goal of this API is to have a similar effect to using AddBiblio
326 and AddItems in succession, but without inefficient repeated
327 parsing of the MARC XML bib record.
329 This function returns an arrayref of new itemsnumbers and an arrayref of item
330 errors encountered during the processing. Each entry in the errors
331 list is a hashref containing the following keys:
337 Sequence number of original item tag in the MARC record.
341 Item barcode, provide to assist in the construction of
342 useful error messages.
346 Code representing the error condition. Can be 'duplicate_barcode',
347 'invalid_homebranch', or 'invalid_holdingbranch'.
349 =item error_information
351 Additional information appropriate to the error condition.
357 sub AddItemBatchFromMarc {
358 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
360 my @itemnumbers = ();
362 my $dbh = C4::Context->dbh;
364 # We modify the record, so lets work on a clone so we don't change the
366 $record = $record->clone();
367 # loop through the item tags and start creating items
368 my @bad_item_fields = ();
369 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
370 my $item_sequence_num = 0;
371 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
372 $item_sequence_num++;
373 # we take the item field and stick it into a new
374 # MARC record -- this is required so far because (FIXME)
375 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
376 # and there is no TransformMarcFieldToKoha
377 my $temp_item_marc = MARC::Record->new();
378 $temp_item_marc->append_fields($item_field);
380 # add biblionumber and biblioitemnumber
381 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
382 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
383 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
384 $item->{'biblionumber'} = $biblionumber;
385 $item->{'biblioitemnumber'} = $biblioitemnumber;
387 # check for duplicate barcode
388 my %item_errors = CheckItemPreSave($item);
390 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
391 push @bad_item_fields, $item_field;
395 _set_defaults_for_add($item);
396 _set_derived_columns_for_add($item);
397 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
398 warn $error if $error;
399 push @itemnumbers, $itemnumber; # FIXME not checking error
400 $item->{'itemnumber'} = $itemnumber;
402 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
404 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
405 $item_field->replace_with($new_item_marc->field($itemtag));
408 # remove any MARC item fields for rejected items
409 foreach my $item_field (@bad_item_fields) {
410 $record->delete_field($item_field);
413 # update the MARC biblio
414 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
416 return (\@itemnumbers, \@errors);
419 =head2 ModItemFromMarc
421 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
423 This function updates an item record based on a supplied
424 C<MARC::Record> object containing an embedded item field.
425 This API is meant for the use of C<additem.pl>; for
426 other purposes, C<ModItem> should be used.
428 This function uses the hash %default_values_for_mod_from_marc,
429 which contains default values for item fields to
430 apply when modifying an item. This is needed beccause
431 if an item field's value is cleared, TransformMarcToKoha
432 does not include the column in the
433 hash that's passed to ModItem, which without
434 use of this hash makes it impossible to clear
435 an item field's value. See bug 2466.
437 Note that only columns that can be directly
438 changed from the cataloging and serials
439 item editors are included in this hash.
445 my %default_values_for_mod_from_marc = (
447 booksellerid => undef,
449 'items.cn_source' => undef,
450 coded_location_qualifier => undef,
453 # dateaccessioned => undef,
455 holdingbranch => undef,
457 itemcallnumber => undef,
462 permanent_location => undef,
467 replacementprice => undef,
468 replacementpricedate => undef,
471 stocknumber => undef,
476 sub ModItemFromMarc {
477 my $item_marc = shift;
478 my $biblionumber = shift;
479 my $itemnumber = shift;
481 my $dbh = C4::Context->dbh;
482 my $frameworkcode = GetFrameworkCode($biblionumber);
483 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
485 my $localitemmarc = MARC::Record->new;
486 $localitemmarc->append_fields( $item_marc->field($itemtag) );
487 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
488 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
489 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
491 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
493 ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
499 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
501 Change one or more columns in an item record and update
502 the MARC representation of the item.
504 The first argument is a hashref mapping from item column
505 names to the new values. The second and third arguments
506 are the biblionumber and itemnumber, respectively.
508 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
509 an arrayref containing subfields present in the original MARC
510 representation of the item (e.g., from the item editor) that are
511 not mapped to C<items> columns directly but should instead
512 be stored in C<items.more_subfields_xml> and included in
513 the biblio items tag for display and indexing.
515 If one of the changed columns is used to calculate
516 the derived value of a column such as C<items.cn_sort>,
517 this routine will perform the necessary calculation
524 my $biblionumber = shift;
525 my $itemnumber = shift;
527 # if $biblionumber is undefined, get it from the current item
528 unless (defined $biblionumber) {
529 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
532 my $dbh = @_ ? shift : C4::Context->dbh;
533 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
535 my $unlinked_item_subfields;
537 $unlinked_item_subfields = shift;
538 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
541 $item->{'itemnumber'} = $itemnumber or return;
543 $item->{onloan} = undef if $item->{itemlost};
545 my @fields = qw( itemlost withdrawn );
547 # Only call GetItem if we need to set an "on" date field
548 if ( $item->{itemlost} || $item->{withdrawn} ) {
549 my $pre_mod_item = GetItem( $item->{'itemnumber'} );
550 for my $field (@fields) {
551 if ( defined( $item->{$field} )
552 and not $pre_mod_item->{$field}
553 and $item->{$field} )
555 $item->{ $field . '_on' } =
556 DateTime::Format::MySQL->format_datetime( dt_from_string() );
561 # If the field is defined but empty, we are removing and,
562 # and thus need to clear out the 'on' field as well
563 for my $field (@fields) {
564 if ( defined( $item->{$field} ) && !$item->{$field} ) {
565 $item->{ $field . '_on' } = undef;
570 _set_derived_columns_for_mod($item);
571 _do_column_fixes_for_mod($item);
574 # attempt to change itemnumber
575 # attempt to change biblionumber (if we want
576 # an API to relink an item to a different bib,
577 # it should be a separate function)
580 _koha_modify_item($item);
582 # request that bib be reindexed so that searching on current
583 # item status is possible
584 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
586 logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
589 =head2 ModItemTransfer
591 ModItemTransfer($itenumber, $frombranch, $tobranch);
593 Marks an item as being transferred from one branch
598 sub ModItemTransfer {
599 my ( $itemnumber, $frombranch, $tobranch ) = @_;
601 my $dbh = C4::Context->dbh;
603 # Remove the 'shelving cart' location status if it is being used.
604 CartToShelf( $itemnumber ) if ( C4::Context->preference("ReturnToShelvingCart") );
606 #new entry in branchtransfers....
607 my $sth = $dbh->prepare(
608 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
609 VALUES (?, ?, NOW(), ?)");
610 $sth->execute($itemnumber, $frombranch, $tobranch);
612 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
613 ModDateLastSeen($itemnumber);
617 =head2 ModDateLastSeen
619 ModDateLastSeen($itemnum);
621 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
622 C<$itemnum> is the item number
626 sub ModDateLastSeen {
627 my ($itemnumber) = @_;
629 my $today = C4::Dates->new();
630 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
635 DelItem($dbh, $biblionumber, $itemnumber);
637 Exported function (core API) for deleting an item record in Koha.
642 my ( $dbh, $biblionumber, $itemnumber ) = @_;
644 # FIXME check the item has no current issues
646 _koha_delete_item( $dbh, $itemnumber );
648 # get the MARC record
649 my $record = GetMarcBiblio($biblionumber);
650 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
652 #search item field code
653 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
656 =head2 CheckItemPreSave
658 my $item_ref = TransformMarcToKoha($marc, 'items');
660 my %errors = CheckItemPreSave($item_ref);
661 if (exists $errors{'duplicate_barcode'}) {
662 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
663 } elsif (exists $errors{'invalid_homebranch'}) {
664 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
665 } elsif (exists $errors{'invalid_holdingbranch'}) {
666 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
671 Given a hashref containing item fields, determine if it can be
672 inserted or updated in the database. Specifically, checks for
673 database integrity issues, and returns a hash containing any
674 of the following keys, if applicable.
678 =item duplicate_barcode
680 Barcode, if it duplicates one already found in the database.
682 =item invalid_homebranch
684 Home branch, if not defined in branches table.
686 =item invalid_holdingbranch
688 Holding branch, if not defined in branches table.
692 This function does NOT implement any policy-related checks,
693 e.g., whether current operator is allowed to save an
694 item that has a given branch code.
698 sub CheckItemPreSave {
699 my $item_ref = shift;
704 # check for duplicate barcode
705 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
706 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
707 if ($existing_itemnumber) {
708 if (!exists $item_ref->{'itemnumber'} # new item
709 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
710 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
715 # check for valid home branch
716 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
717 my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
718 unless (defined $branch_name) {
719 # relies on fact that branches.branchname is a non-NULL column,
720 # so GetBranchName returns undef only if branch does not exist
721 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
725 # check for valid holding branch
726 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
727 my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
728 unless (defined $branch_name) {
729 # relies on fact that branches.branchname is a non-NULL column,
730 # so GetBranchName returns undef only if branch does not exist
731 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
739 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
741 The following functions provide various ways of
742 getting an item record, a set of item records, or
743 lists of authorized values for certain item fields.
745 Some of the functions in this group are candidates
746 for refactoring -- for example, some of the code
747 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
748 has copy-and-paste work.
754 $itemstatushash = GetItemStatus($fwkcode);
756 Returns a list of valid values for the
757 C<items.notforloan> field.
759 NOTE: does B<not> return an individual item's
762 Can be MARC dependant.
764 But basically could be can be loan or not
765 Create a status selector with the following code
767 =head3 in PERL SCRIPT
769 my $itemstatushash = getitemstatus;
771 foreach my $thisstatus (keys %$itemstatushash) {
772 my %row =(value => $thisstatus,
773 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
775 push @itemstatusloop, \%row;
777 $template->param(statusloop=>\@itemstatusloop);
781 <select name="statusloop" id="statusloop">
782 <option value="">Default</option>
783 [% FOREACH statusloo IN statusloop %]
784 [% IF ( statusloo.selected ) %]
785 <option value="[% statusloo.value %]" selected="selected">[% statusloo.statusname %]</option>
787 <option value="[% statusloo.value %]">[% statusloo.statusname %]</option>
796 # returns a reference to a hash of references to status...
799 my $dbh = C4::Context->dbh;
801 $fwk = '' unless ($fwk);
802 my ( $tag, $subfield ) =
803 GetMarcFromKohaField( "items.notforloan", $fwk );
804 if ( $tag and $subfield ) {
807 "SELECT authorised_value
808 FROM marc_subfield_structure
814 $sth->execute( $tag, $subfield, $fwk );
815 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
818 "SELECT authorised_value,lib
819 FROM authorised_values
824 $authvalsth->execute($authorisedvaluecat);
825 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
826 $itemstatus{$authorisedvalue} = $lib;
840 $itemstatus{"1"} = "Not For Loan";
844 =head2 GetItemLocation
846 $itemlochash = GetItemLocation($fwk);
848 Returns a list of valid values for the
849 C<items.location> field.
851 NOTE: does B<not> return an individual item's
854 where fwk stands for an optional framework code.
855 Create a location selector with the following code
857 =head3 in PERL SCRIPT
859 my $itemlochash = getitemlocation;
861 foreach my $thisloc (keys %$itemlochash) {
862 my $selected = 1 if $thisbranch eq $branch;
863 my %row =(locval => $thisloc,
864 selected => $selected,
865 locname => $itemlochash->{$thisloc},
867 push @itemlocloop, \%row;
869 $template->param(itemlocationloop => \@itemlocloop);
873 <select name="location">
874 <option value="">Default</option>
875 <!-- TMPL_LOOP name="itemlocationloop" -->
876 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
882 sub GetItemLocation {
884 # returns a reference to a hash of references to location...
887 my $dbh = C4::Context->dbh;
889 $fwk = '' unless ($fwk);
890 my ( $tag, $subfield ) =
891 GetMarcFromKohaField( "items.location", $fwk );
892 if ( $tag and $subfield ) {
895 "SELECT authorised_value
896 FROM marc_subfield_structure
901 $sth->execute( $tag, $subfield, $fwk );
902 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
905 "SELECT authorised_value,lib
906 FROM authorised_values
910 $authvalsth->execute($authorisedvaluecat);
911 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
912 $itemlocation{$authorisedvalue} = $lib;
914 return \%itemlocation;
926 $itemlocation{"1"} = "Not For Loan";
927 return \%itemlocation;
932 $items = GetLostItems( $where, $orderby );
934 This function gets a list of lost items.
940 C<$where> is a hashref. it containts a field of the items table as key
941 and the value to match as value. For example:
943 { barcode => 'abc123',
944 homebranch => 'CPL', }
946 C<$orderby> is a field of the items table by which the resultset
951 C<$items> is a reference to an array full of hashrefs with columns
952 from the "items" table as keys.
954 =item usage in the perl script:
956 my $where = { barcode => '0001548' };
957 my $items = GetLostItems( $where, "homebranch" );
958 $template->param( itemsloop => $items );
965 # Getting input args.
968 my $dbh = C4::Context->dbh;
971 SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
972 itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber
974 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
975 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
976 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
978 authorised_values.category = 'LOST'
979 AND itemlost IS NOT NULL
982 my @query_parameters;
983 foreach my $key (keys %$where) {
984 $query .= " AND $key LIKE ?";
985 push @query_parameters, "%$where->{$key}%";
987 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
989 if ( defined $orderby && grep($orderby, @ordervalues)) {
990 $query .= ' ORDER BY '.$orderby;
993 my $sth = $dbh->prepare($query);
994 $sth->execute( @query_parameters );
996 while ( my $row = $sth->fetchrow_hashref ){
1002 =head2 GetItemsForInventory
1004 ($itemlist, $iTotalRecords) = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $offset, $size, $statushash);
1006 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1008 The sub returns a reference to a list of hashes, each containing
1009 itemnumber, author, title, barcode, item callnumber, and date last
1010 seen. It is ordered by callnumber then title.
1012 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1013 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1014 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1015 $statushash requires a hashref that has the authorized values fieldname (intems.notforloan, etc...) as keys, and an arrayref of statuscodes we are searching for as values.
1017 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
1021 sub GetItemsForInventory {
1022 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
1023 my $dbh = C4::Context->dbh;
1024 my ( @bind_params, @where_strings );
1026 my $select_columns = q{
1027 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, stocknumber
1029 my $select_count = q{SELECT COUNT(*)};
1032 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1033 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1036 for my $authvfield (keys %$statushash){
1037 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1038 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1039 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1045 push @where_strings, 'itemcallnumber >= ?';
1046 push @bind_params, $minlocation;
1050 push @where_strings, 'itemcallnumber <= ?';
1051 push @bind_params, $maxlocation;
1054 if ($datelastseen) {
1055 $datelastseen = format_date_in_iso($datelastseen);
1056 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1057 push @bind_params, $datelastseen;
1061 push @where_strings, 'items.location = ?';
1062 push @bind_params, $location;
1065 if ( $branchcode ) {
1066 if($branch eq "homebranch"){
1067 push @where_strings, 'items.homebranch = ?';
1069 push @where_strings, 'items.holdingbranch = ?';
1071 push @bind_params, $branchcode;
1075 push @where_strings, 'biblioitems.itemtype = ?';
1076 push @bind_params, $itemtype;
1079 if ( $ignoreissued) {
1080 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1081 push @where_strings, 'issues.date_due IS NULL';
1084 if ( @where_strings ) {
1086 $query .= join ' AND ', @where_strings;
1088 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1089 my $count_query = $select_count . $query;
1090 $query .= " LIMIT $offset, $size" if ($offset and $size);
1091 $query = $select_columns . $query;
1092 my $sth = $dbh->prepare($query);
1093 $sth->execute( @bind_params );
1096 my $tmpresults = $sth->fetchall_arrayref({});
1097 $sth = $dbh->prepare( $count_query );
1098 $sth->execute( @bind_params );
1099 my ($iTotalRecords) = $sth->fetchrow_array();
1101 foreach my $row (@$tmpresults) {
1104 foreach (keys %$row) {
1105 # If the koha field is mapped to a marc field
1106 my ($f, $sf) = GetMarcFromKohaField("items.$_", $row->{'frameworkcode'});
1108 # We replace the code with it's description
1109 my $authvals = C4::Koha::GetKohaAuthorisedValuesFromField($f, $sf, $row->{'frameworkcode'});
1110 $row->{$_} = $authvals->{$row->{$_}} if defined $authvals->{$row->{$_}};
1113 push @results, $row;
1116 return (\@results, $iTotalRecords);
1119 =head2 GetItemsCount
1121 $count = &GetItemsCount( $biblionumber);
1123 This function return count of item with $biblionumber
1128 my ( $biblionumber ) = @_;
1129 my $dbh = C4::Context->dbh;
1130 my $query = "SELECT count(*)
1132 WHERE biblionumber=?";
1133 my $sth = $dbh->prepare($query);
1134 $sth->execute($biblionumber);
1135 my $count = $sth->fetchrow;
1139 =head2 GetItemInfosOf
1141 GetItemInfosOf(@itemnumbers);
1145 sub GetItemInfosOf {
1146 my @itemnumbers = @_;
1151 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1153 return get_infos_of( $query, 'itemnumber' );
1156 =head2 GetItemsByBiblioitemnumber
1158 GetItemsByBiblioitemnumber($biblioitemnumber);
1160 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1161 Called by C<C4::XISBN>
1165 sub GetItemsByBiblioitemnumber {
1166 my ( $bibitem ) = @_;
1167 my $dbh = C4::Context->dbh;
1168 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1169 # Get all items attached to a biblioitem
1172 $sth->execute($bibitem) || die $sth->errstr;
1173 while ( my $data = $sth->fetchrow_hashref ) {
1174 # Foreach item, get circulation information
1175 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1176 WHERE itemnumber = ?
1177 AND issues.borrowernumber = borrowers.borrowernumber"
1179 $sth2->execute( $data->{'itemnumber'} );
1180 if ( my $data2 = $sth2->fetchrow_hashref ) {
1181 # if item is out, set the due date and who it is out too
1182 $data->{'date_due'} = $data2->{'date_due'};
1183 $data->{'cardnumber'} = $data2->{'cardnumber'};
1184 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1187 # set date_due to blank, so in the template we check itemlost, and withdrawn
1188 $data->{'date_due'} = '';
1190 # Find the last 3 people who borrowed this item.
1191 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1192 AND old_issues.borrowernumber = borrowers.borrowernumber
1193 ORDER BY returndate desc,timestamp desc LIMIT 3";
1194 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1195 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1197 while ( my $data2 = $sth2->fetchrow_hashref ) {
1198 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1199 $data->{"card$i2"} = $data2->{'cardnumber'};
1200 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1203 push(@results,$data);
1210 @results = GetItemsInfo($biblionumber);
1212 Returns information about items with the given biblionumber.
1214 C<GetItemsInfo> returns a list of references-to-hash. Each element
1215 contains a number of keys. Most of them are attributes from the
1216 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1217 Koha database. Other keys include:
1221 =item C<$data-E<gt>{branchname}>
1223 The name (not the code) of the branch to which the book belongs.
1225 =item C<$data-E<gt>{datelastseen}>
1227 This is simply C<items.datelastseen>, except that while the date is
1228 stored in YYYY-MM-DD format in the database, here it is converted to
1229 DD/MM/YYYY format. A NULL date is returned as C<//>.
1231 =item C<$data-E<gt>{datedue}>
1233 =item C<$data-E<gt>{class}>
1235 This is the concatenation of C<biblioitems.classification>, the book's
1236 Dewey code, and C<biblioitems.subclass>.
1238 =item C<$data-E<gt>{ocount}>
1240 I think this is the number of copies of the book available.
1242 =item C<$data-E<gt>{order}>
1244 If this is set, it is set to C<One Order>.
1251 my ( $biblionumber ) = @_;
1252 my $dbh = C4::Context->dbh;
1253 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1259 biblioitems.itemtype,
1262 biblioitems.publicationyear,
1263 biblioitems.publishercode,
1264 biblioitems.volumedate,
1265 biblioitems.volumedesc,
1268 items.notforloan as itemnotforloan,
1269 itemtypes.description,
1270 itemtypes.notforloan as notforloan_per_itemtype,
1273 holding.opac_info as branch_opac_info
1275 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1276 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1277 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1278 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1279 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1280 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1281 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1282 my $sth = $dbh->prepare($query);
1283 $sth->execute($biblionumber);
1288 my $isth = $dbh->prepare(
1289 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1290 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1291 WHERE itemnumber = ?"
1293 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1294 while ( my $data = $sth->fetchrow_hashref ) {
1296 $isth->execute( $data->{'itemnumber'} );
1297 if ( my $idata = $isth->fetchrow_hashref ) {
1298 $data->{borrowernumber} = $idata->{borrowernumber};
1299 $data->{cardnumber} = $idata->{cardnumber};
1300 $data->{surname} = $idata->{surname};
1301 $data->{firstname} = $idata->{firstname};
1302 $data->{lastreneweddate} = $idata->{lastreneweddate};
1303 $datedue = $idata->{'date_due'};
1304 if (C4::Context->preference("IndependentBranches")){
1305 my $userenv = C4::Context->userenv;
1306 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1307 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1311 if ( $data->{'serial'}) {
1312 $ssth->execute($data->{'itemnumber'}) ;
1313 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1316 #get branch information.....
1317 my $bsth = $dbh->prepare(
1318 "SELECT * FROM branches WHERE branchcode = ?
1321 $bsth->execute( $data->{'holdingbranch'} );
1322 if ( my $bdata = $bsth->fetchrow_hashref ) {
1323 $data->{'branchname'} = $bdata->{'branchname'};
1325 $data->{'datedue'} = $datedue;
1327 # get notforloan complete status if applicable
1328 if ( my $code = C4::Koha::GetAuthValCode( 'items.notforloan', $data->{frameworkcode} ) ) {
1329 $data->{notforloanvalue} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan} );
1330 $data->{notforloanvalueopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan}, 1 );
1333 # get restricted status and description if applicable
1334 if ( my $code = C4::Koha::GetAuthValCode( 'items.restricted', $data->{frameworkcode} ) ) {
1335 $data->{restrictedopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted}, 1 );
1336 $data->{restricted} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
1339 # my stack procedures
1340 if ( my $code = C4::Koha::GetAuthValCode( 'items.stack', $data->{frameworkcode} ) ) {
1341 $data->{stack} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{stack} );
1343 # Find the last 3 people who borrowed this item.
1344 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1345 WHERE itemnumber = ?
1346 AND old_issues.borrowernumber = borrowers.borrowernumber
1347 ORDER BY returndate DESC
1349 $sth2->execute($data->{'itemnumber'});
1351 while (my $data2 = $sth2->fetchrow_hashref()) {
1352 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1353 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1354 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1358 $results[$i] = $data;
1362 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1368 =head2 GetItemsLocationInfo
1370 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1372 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1374 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1378 =item C<$data-E<gt>{homebranch}>
1380 Branch Name of the item's homebranch
1382 =item C<$data-E<gt>{holdingbranch}>
1384 Branch Name of the item's holdingbranch
1386 =item C<$data-E<gt>{location}>
1388 Item's shelving location code
1390 =item C<$data-E<gt>{location_intranet}>
1392 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1394 =item C<$data-E<gt>{location_opac}>
1396 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1399 =item C<$data-E<gt>{itemcallnumber}>
1401 Item's itemcallnumber
1403 =item C<$data-E<gt>{cn_sort}>
1405 Item's call number normalized for sorting
1411 sub GetItemsLocationInfo {
1412 my $biblionumber = shift;
1415 my $dbh = C4::Context->dbh;
1416 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1417 location, itemcallnumber, cn_sort
1418 FROM items, branches as a, branches as b
1419 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1420 AND biblionumber = ?
1421 ORDER BY cn_sort ASC";
1422 my $sth = $dbh->prepare($query);
1423 $sth->execute($biblionumber);
1425 while ( my $data = $sth->fetchrow_hashref ) {
1426 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1427 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1428 push @results, $data;
1433 =head2 GetHostItemsInfo
1435 $hostiteminfo = GetHostItemsInfo($hostfield);
1436 Returns the iteminfo for items linked to records via a host field
1440 sub GetHostItemsInfo {
1442 my @returnitemsInfo;
1444 if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1445 C4::Context->preference('marcflavour') eq 'NORMARC'){
1446 foreach my $hostfield ( $record->field('773') ) {
1447 my $hostbiblionumber = $hostfield->subfield("0");
1448 my $linkeditemnumber = $hostfield->subfield("9");
1449 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1450 foreach my $hostitemInfo (@hostitemInfos){
1451 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1452 push (@returnitemsInfo,$hostitemInfo);
1457 } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1458 foreach my $hostfield ( $record->field('461') ) {
1459 my $hostbiblionumber = $hostfield->subfield("0");
1460 my $linkeditemnumber = $hostfield->subfield("9");
1461 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1462 foreach my $hostitemInfo (@hostitemInfos){
1463 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1464 push (@returnitemsInfo,$hostitemInfo);
1470 return @returnitemsInfo;
1474 =head2 GetLastAcquisitions
1476 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1477 'itemtypes' => ('BK','BD')}, 10);
1481 sub GetLastAcquisitions {
1482 my ($data,$max) = @_;
1484 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1486 my $number_of_branches = @{$data->{branches}};
1487 my $number_of_itemtypes = @{$data->{itemtypes}};
1490 my @where = ('WHERE 1 ');
1491 $number_of_branches and push @where
1492 , 'AND holdingbranch IN ('
1493 , join(',', ('?') x $number_of_branches )
1497 $number_of_itemtypes and push @where
1498 , "AND $itemtype IN ("
1499 , join(',', ('?') x $number_of_itemtypes )
1503 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1504 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1505 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1507 GROUP BY biblio.biblionumber
1508 ORDER BY dateaccessioned DESC LIMIT $max";
1510 my $dbh = C4::Context->dbh;
1511 my $sth = $dbh->prepare($query);
1513 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1516 while( my $row = $sth->fetchrow_hashref){
1517 push @results, {date => $row->{dateaccessioned}
1518 , biblionumber => $row->{biblionumber}
1519 , title => $row->{title}};
1525 =head2 GetItemnumbersForBiblio
1527 my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1529 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1533 sub GetItemnumbersForBiblio {
1534 my $biblionumber = shift;
1536 my $dbh = C4::Context->dbh;
1537 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1538 $sth->execute($biblionumber);
1539 while (my $result = $sth->fetchrow_hashref) {
1540 push @items, $result->{'itemnumber'};
1545 =head2 get_itemnumbers_of
1547 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1549 Given a list of biblionumbers, return the list of corresponding itemnumbers
1550 for each biblionumber.
1552 Return a reference on a hash where keys are biblionumbers and values are
1553 references on array of itemnumbers.
1557 sub get_itemnumbers_of {
1558 my @biblionumbers = @_;
1560 my $dbh = C4::Context->dbh;
1566 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1568 my $sth = $dbh->prepare($query);
1569 $sth->execute(@biblionumbers);
1573 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1574 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1577 return \%itemnumbers_of;
1580 =head2 get_hostitemnumbers_of
1582 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1584 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1586 Return a reference on a hash where key is a biblionumber and values are
1587 references on array of itemnumbers.
1592 sub get_hostitemnumbers_of {
1593 my ($biblionumber) = @_;
1594 my $marcrecord = GetMarcBiblio($biblionumber);
1595 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1597 my $marcflavor = C4::Context->preference('marcflavour');
1598 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1602 } elsif ($marcflavor eq 'UNIMARC') {
1608 foreach my $hostfield ( $marcrecord->field($tag) ) {
1609 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1610 my $linkeditemnumber = $hostfield->subfield($item_s);
1612 if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1614 @itemnumbers = @$itemnumbers;
1616 foreach my $itemnumber (@itemnumbers){
1617 if ($itemnumber eq $linkeditemnumber){
1618 push (@returnhostitemnumbers,$itemnumber);
1623 return @returnhostitemnumbers;
1627 =head2 GetItemnumberFromBarcode
1629 $result = GetItemnumberFromBarcode($barcode);
1633 sub GetItemnumberFromBarcode {
1635 my $dbh = C4::Context->dbh;
1638 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1639 $rq->execute($barcode);
1640 my ($result) = $rq->fetchrow;
1644 =head2 GetBarcodeFromItemnumber
1646 $result = GetBarcodeFromItemnumber($itemnumber);
1650 sub GetBarcodeFromItemnumber {
1651 my ($itemnumber) = @_;
1652 my $dbh = C4::Context->dbh;
1655 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1656 $rq->execute($itemnumber);
1657 my ($result) = $rq->fetchrow;
1661 =head2 GetHiddenItemnumbers
1663 my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
1665 Given a list of items it checks which should be hidden from the OPAC given
1666 the current configuration. Returns a list of itemnumbers corresponding to
1667 those that should be hidden.
1671 sub GetHiddenItemnumbers {
1675 my $yaml = C4::Context->preference('OpacHiddenItems');
1676 return () if (! $yaml =~ /\S/ );
1677 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1680 $hidingrules = YAML::Load($yaml);
1683 warn "Unable to parse OpacHiddenItems syspref : $@";
1686 my $dbh = C4::Context->dbh;
1689 foreach my $item (@items) {
1691 # We check each rule
1692 foreach my $field (keys %$hidingrules) {
1694 if (exists $item->{$field}) {
1695 $val = $item->{$field};
1698 my $query = "SELECT $field from items where itemnumber = ?";
1699 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1701 $val = '' unless defined $val;
1703 # If the results matches the values in the yaml file
1704 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1706 # We add the itemnumber to the list
1707 push @resultitems, $item->{'itemnumber'};
1709 # If at least one rule matched for an item, no need to test the others
1714 return @resultitems;
1717 =head3 get_item_authorised_values
1719 find the types and values for all authorised values assigned to this item.
1721 parameters: itemnumber
1723 returns: a hashref malling the authorised value to the value set for this itemnumber
1725 $authorised_values = {
1731 'RESTRICTED' => undef,
1734 'branches' => 'CPL',
1735 'cn_source' => undef,
1736 'itemtypes' => 'SER',
1739 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1743 sub get_item_authorised_values {
1744 my $itemnumber = shift;
1746 # assume that these entries in the authorised_value table are item level.
1747 my $query = q(SELECT distinct authorised_value, kohafield
1748 FROM marc_subfield_structure
1749 WHERE kohafield like 'item%'
1750 AND authorised_value != '' );
1752 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1753 my $iteminfo = GetItem( $itemnumber );
1754 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1756 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1757 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1758 $field =~ s/^items\.//;
1759 if ( exists $iteminfo->{ $field } ) {
1760 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1763 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1767 =head3 get_authorised_value_images
1769 find a list of icons that are appropriate for display based on the
1770 authorised values for a biblio.
1772 parameters: listref of authorised values, such as comes from
1773 get_item_authorised_values or
1774 from C4::Biblio::get_biblio_authorised_values
1776 returns: listref of hashrefs for each image. Each hashref looks like this:
1778 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1783 Notes: Currently, I put on the full path to the images on the staff
1784 side. This should either be configurable or not done at all. Since I
1785 have to deal with 'intranet' or 'opac' in
1786 get_biblio_authorised_values, perhaps I should be passing it in.
1790 sub get_authorised_value_images {
1791 my $authorised_values = shift;
1795 my $authorised_value_list = GetAuthorisedValues();
1796 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1797 foreach my $this_authorised_value ( @$authorised_value_list ) {
1798 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1799 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1800 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1801 if ( defined $this_authorised_value->{'imageurl'} ) {
1802 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1803 label => $this_authorised_value->{'lib'},
1804 category => $this_authorised_value->{'category'},
1805 value => $this_authorised_value->{'authorised_value'}, };
1810 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1815 =head1 LIMITED USE FUNCTIONS
1817 The following functions, while part of the public API,
1818 are not exported. This is generally because they are
1819 meant to be used by only one script for a specific
1820 purpose, and should not be used in any other context
1821 without careful thought.
1827 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1829 Returns MARC::Record of the item passed in parameter.
1830 This function is meant for use only in C<cataloguing/additem.pl>,
1831 where it is needed to support that script's MARC-like
1837 my ( $biblionumber, $itemnumber ) = @_;
1839 # GetMarcItem has been revised so that it does the following:
1840 # 1. Gets the item information from the items table.
1841 # 2. Converts it to a MARC field for storage in the bib record.
1843 # The previous behavior was:
1844 # 1. Get the bib record.
1845 # 2. Return the MARC tag corresponding to the item record.
1847 # The difference is that one treats the items row as authoritative,
1848 # while the other treats the MARC representation as authoritative
1849 # under certain circumstances.
1851 my $itemrecord = GetItem($itemnumber);
1853 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1854 # Also, don't emit a subfield if the underlying field is blank.
1857 return Item2Marc($itemrecord,$biblionumber);
1861 my ($itemrecord,$biblionumber)=@_;
1864 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1865 } keys %{ $itemrecord }
1867 my $itemmarc = TransformKohaToMarc($mungeditem);
1868 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1870 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1871 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1872 foreach my $field ($itemmarc->field($itemtag)){
1873 $field->add_subfields(@$unlinked_item_subfields);
1879 =head1 PRIVATE FUNCTIONS AND VARIABLES
1881 The following functions are not meant to be called
1882 directly, but are documented in order to explain
1883 the inner workings of C<C4::Items>.
1887 =head2 %derived_columns
1889 This hash keeps track of item columns that
1890 are strictly derived from other columns in
1891 the item record and are not meant to be set
1894 Each key in the hash should be the name of a
1895 column (as named by TransformMarcToKoha). Each
1896 value should be hashref whose keys are the
1897 columns on which the derived column depends. The
1898 hashref should also contain a 'BUILDER' key
1899 that is a reference to a sub that calculates
1904 my %derived_columns = (
1905 'items.cn_sort' => {
1906 'itemcallnumber' => 1,
1907 'items.cn_source' => 1,
1908 'BUILDER' => \&_calc_items_cn_sort,
1912 =head2 _set_derived_columns_for_add
1914 _set_derived_column_for_add($item);
1916 Given an item hash representing a new item to be added,
1917 calculate any derived columns. Currently the only
1918 such column is C<items.cn_sort>.
1922 sub _set_derived_columns_for_add {
1925 foreach my $column (keys %derived_columns) {
1926 my $builder = $derived_columns{$column}->{'BUILDER'};
1927 my $source_values = {};
1928 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1929 next if $source_column eq 'BUILDER';
1930 $source_values->{$source_column} = $item->{$source_column};
1932 $builder->($item, $source_values);
1936 =head2 _set_derived_columns_for_mod
1938 _set_derived_column_for_mod($item);
1940 Given an item hash representing a new item to be modified.
1941 calculate any derived columns. Currently the only
1942 such column is C<items.cn_sort>.
1944 This routine differs from C<_set_derived_columns_for_add>
1945 in that it needs to handle partial item records. In other
1946 words, the caller of C<ModItem> may have supplied only one
1947 or two columns to be changed, so this function needs to
1948 determine whether any of the columns to be changed affect
1949 any of the derived columns. Also, if a derived column
1950 depends on more than one column, but the caller is not
1951 changing all of then, this routine retrieves the unchanged
1952 values from the database in order to ensure a correct
1957 sub _set_derived_columns_for_mod {
1960 foreach my $column (keys %derived_columns) {
1961 my $builder = $derived_columns{$column}->{'BUILDER'};
1962 my $source_values = {};
1963 my %missing_sources = ();
1964 my $must_recalc = 0;
1965 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1966 next if $source_column eq 'BUILDER';
1967 if (exists $item->{$source_column}) {
1969 $source_values->{$source_column} = $item->{$source_column};
1971 $missing_sources{$source_column} = 1;
1975 foreach my $source_column (keys %missing_sources) {
1976 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1978 $builder->($item, $source_values);
1983 =head2 _do_column_fixes_for_mod
1985 _do_column_fixes_for_mod($item);
1987 Given an item hashref containing one or more
1988 columns to modify, fix up certain values.
1989 Specifically, set to 0 any passed value
1990 of C<notforloan>, C<damaged>, C<itemlost>, or
1991 C<withdrawn> that is either undefined or
1992 contains the empty string.
1996 sub _do_column_fixes_for_mod {
1999 if (exists $item->{'notforloan'} and
2000 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
2001 $item->{'notforloan'} = 0;
2003 if (exists $item->{'damaged'} and
2004 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
2005 $item->{'damaged'} = 0;
2007 if (exists $item->{'itemlost'} and
2008 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
2009 $item->{'itemlost'} = 0;
2011 if (exists $item->{'withdrawn'} and
2012 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
2013 $item->{'withdrawn'} = 0;
2015 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
2016 $item->{'permanent_location'} = $item->{'location'};
2018 if (exists $item->{'timestamp'}) {
2019 delete $item->{'timestamp'};
2023 =head2 _get_single_item_column
2025 _get_single_item_column($column, $itemnumber);
2027 Retrieves the value of a single column from an C<items>
2028 row specified by C<$itemnumber>.
2032 sub _get_single_item_column {
2034 my $itemnumber = shift;
2036 my $dbh = C4::Context->dbh;
2037 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2038 $sth->execute($itemnumber);
2039 my ($value) = $sth->fetchrow();
2043 =head2 _calc_items_cn_sort
2045 _calc_items_cn_sort($item, $source_values);
2047 Helper routine to calculate C<items.cn_sort>.
2051 sub _calc_items_cn_sort {
2053 my $source_values = shift;
2055 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2058 =head2 _set_defaults_for_add
2060 _set_defaults_for_add($item_hash);
2062 Given an item hash representing an item to be added, set
2063 correct default values for columns whose default value
2064 is not handled by the DBMS. This includes the following
2071 C<items.dateaccessioned>
2093 sub _set_defaults_for_add {
2095 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2096 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
2099 =head2 _koha_new_item
2101 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2103 Perform the actual insert into the C<items> table.
2107 sub _koha_new_item {
2108 my ( $item, $barcode ) = @_;
2109 my $dbh=C4::Context->dbh;
2112 "INSERT INTO items SET
2114 biblioitemnumber = ?,
2116 dateaccessioned = ?,
2120 replacementprice = ?,
2121 replacementpricedate = ?,
2122 datelastborrowed = ?,
2130 coded_location_qualifier = ?,
2136 permanent_location = ?,
2148 more_subfields_xml = ?,
2152 my $sth = $dbh->prepare($query);
2153 my $today = C4::Dates->today('iso');
2155 $item->{'biblionumber'},
2156 $item->{'biblioitemnumber'},
2158 $item->{'dateaccessioned'},
2159 $item->{'booksellerid'},
2160 $item->{'homebranch'},
2162 $item->{'replacementprice'},
2163 $item->{'replacementpricedate'} || $today,
2164 $item->{datelastborrowed},
2165 $item->{datelastseen} || $today,
2167 $item->{'notforloan'},
2169 $item->{'itemlost'},
2170 $item->{'withdrawn'},
2171 $item->{'itemcallnumber'},
2172 $item->{'coded_location_qualifier'},
2173 $item->{'restricted'},
2174 $item->{'itemnotes'},
2175 $item->{'holdingbranch'},
2177 $item->{'location'},
2178 $item->{'permanent_location'},
2181 $item->{'renewals'},
2182 $item->{'reserves'},
2183 $item->{'items.cn_source'},
2184 $item->{'items.cn_sort'},
2187 $item->{'materials'},
2189 $item->{'enumchron'},
2190 $item->{'more_subfields_xml'},
2191 $item->{'copynumber'},
2192 $item->{'stocknumber'},
2196 if ( defined $sth->errstr ) {
2197 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2200 $itemnumber = $dbh->{'mysql_insertid'};
2203 return ( $itemnumber, $error );
2206 =head2 MoveItemFromBiblio
2208 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2210 Moves an item from a biblio to another
2212 Returns undef if the move failed or the biblionumber of the destination record otherwise
2216 sub MoveItemFromBiblio {
2217 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2218 my $dbh = C4::Context->dbh;
2219 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2220 $sth->execute( $tobiblio );
2221 my ( $tobiblioitem ) = $sth->fetchrow();
2222 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2223 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2225 ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
2226 ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
2227 # Checking if the item we want to move is in an order
2228 require C4::Acquisition;
2229 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2231 # Replacing the biblionumber within the order if necessary
2232 $order->{'biblionumber'} = $tobiblio;
2233 C4::Acquisition::ModOrder($order);
2242 DelItemCheck($dbh, $biblionumber, $itemnumber);
2244 Exported function (core API) for deleting an item record in Koha if there no current issue.
2249 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2252 my $countanalytics=GetAnalyticsCount($itemnumber);
2255 # check that there is no issue on this item before deletion.
2256 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2257 $sth->execute($itemnumber);
2259 my $item = GetItem($itemnumber);
2260 my $onloan=$sth->fetchrow;
2263 $error = "book_on_loan"
2265 elsif ( !( C4::Context->userenv->{flags} & 1 )
2266 and C4::Context->preference("IndependentBranches")
2267 and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
2269 $error = "not_same_branch";
2272 # check it doesnt have a waiting reserve
2273 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2274 $sth->execute($itemnumber);
2275 my $reserve=$sth->fetchrow;
2277 $error = "book_reserved";
2278 } elsif ($countanalytics > 0){
2279 $error = "linked_analytics";
2281 DelItem($dbh, $biblionumber, $itemnumber);
2288 =head2 _koha_modify_item
2290 my ($itemnumber,$error) =_koha_modify_item( $item );
2292 Perform the actual update of the C<items> row. Note that this
2293 routine accepts a hashref specifying the columns to update.
2297 sub _koha_modify_item {
2299 my $dbh=C4::Context->dbh;
2302 my $query = "UPDATE items SET ";
2304 for my $key ( keys %$item ) {
2305 next if ( $key eq 'itemnumber' );
2307 push @bind, $item->{$key};
2310 $query .= " WHERE itemnumber=?";
2311 push @bind, $item->{'itemnumber'};
2312 my $sth = C4::Context->dbh->prepare($query);
2313 $sth->execute(@bind);
2314 if ( C4::Context->dbh->errstr ) {
2315 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2318 return ($item->{'itemnumber'},$error);
2321 =head2 _koha_delete_item
2323 _koha_delete_item( $dbh, $itemnum );
2325 Internal function to delete an item record from the koha tables
2329 sub _koha_delete_item {
2330 my ( $dbh, $itemnum ) = @_;
2332 # save the deleted item to deleteditems table
2333 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2334 $sth->execute($itemnum);
2335 my $data = $sth->fetchrow_hashref();
2336 my $query = "INSERT INTO deleteditems SET ";
2338 foreach my $key ( keys %$data ) {
2339 $query .= "$key = ?,";
2340 push( @bind, $data->{$key} );
2343 $sth = $dbh->prepare($query);
2344 $sth->execute(@bind);
2346 # delete from items table
2347 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2348 $sth->execute($itemnum);
2352 =head2 _marc_from_item_hash
2354 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2356 Given an item hash representing a complete item record,
2357 create a C<MARC::Record> object containing an embedded
2358 tag representing that item.
2360 The third, optional parameter C<$unlinked_item_subfields> is
2361 an arrayref of subfields (not mapped to C<items> fields per the
2362 framework) to be added to the MARC representation
2367 sub _marc_from_item_hash {
2369 my $frameworkcode = shift;
2370 my $unlinked_item_subfields;
2372 $unlinked_item_subfields = shift;
2375 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2376 # Also, don't emit a subfield if the underlying field is blank.
2377 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2378 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2379 : () } keys %{ $item } };
2381 my $item_marc = MARC::Record->new();
2382 foreach my $item_field ( keys %{$mungeditem} ) {
2383 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2384 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2385 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2386 foreach my $value (@values){
2387 if ( my $field = $item_marc->field($tag) ) {
2388 $field->add_subfields( $subfield => $value );
2390 my $add_subfields = [];
2391 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2392 $add_subfields = $unlinked_item_subfields;
2394 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2402 =head2 _repack_item_errors
2404 Add an error message hash generated by C<CheckItemPreSave>
2405 to a list of errors.
2409 sub _repack_item_errors {
2410 my $item_sequence_num = shift;
2411 my $item_ref = shift;
2412 my $error_ref = shift;
2414 my @repacked_errors = ();
2416 foreach my $error_code (sort keys %{ $error_ref }) {
2417 my $repacked_error = {};
2418 $repacked_error->{'item_sequence'} = $item_sequence_num;
2419 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2420 $repacked_error->{'error_code'} = $error_code;
2421 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2422 push @repacked_errors, $repacked_error;
2425 return @repacked_errors;
2428 =head2 _get_unlinked_item_subfields
2430 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2434 sub _get_unlinked_item_subfields {
2435 my $original_item_marc = shift;
2436 my $frameworkcode = shift;
2438 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2440 # assume that this record has only one field, and that that
2441 # field contains only the item information
2443 my @fields = $original_item_marc->fields();
2444 if ($#fields > -1) {
2445 my $field = $fields[0];
2446 my $tag = $field->tag();
2447 foreach my $subfield ($field->subfields()) {
2448 if (defined $subfield->[1] and
2449 $subfield->[1] ne '' and
2450 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2451 push @$subfields, $subfield->[0] => $subfield->[1];
2458 =head2 _get_unlinked_subfields_xml
2460 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2464 sub _get_unlinked_subfields_xml {
2465 my $unlinked_item_subfields = shift;
2468 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2469 my $marc = MARC::Record->new();
2470 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2471 # used in the framework
2472 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2473 $marc->encoding("UTF-8");
2474 $xml = $marc->as_xml("USMARC");
2480 =head2 _parse_unlinked_item_subfields_from_xml
2482 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2486 sub _parse_unlinked_item_subfields_from_xml {
2488 require C4::Charset;
2489 return unless defined $xml and $xml ne "";
2490 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2491 my $unlinked_subfields = [];
2492 my @fields = $marc->fields();
2493 if ($#fields > -1) {
2494 foreach my $subfield ($fields[0]->subfields()) {
2495 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2498 return $unlinked_subfields;
2501 =head2 GetAnalyticsCount
2503 $count= &GetAnalyticsCount($itemnumber)
2505 counts Usage of itemnumber in Analytical bibliorecords.
2509 sub GetAnalyticsCount {
2510 my ($itemnumber) = @_;
2513 ### ZOOM search here
2515 $query= "hi=".$itemnumber;
2516 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2523 $holds = &GetItemHolds($biblionumber, $itemnumber);
2527 This function return the count of holds with $biblionumber and $itemnumber
2532 my ($biblionumber, $itemnumber) = @_;
2534 my $dbh = C4::Context->dbh;
2535 my $query = "SELECT count(*)
2537 WHERE biblionumber=? AND itemnumber=?";
2538 my $sth = $dbh->prepare($query);
2539 $sth->execute($biblionumber, $itemnumber);
2540 $holds = $sth->fetchrow;
2544 # Return the list of the column names of items table
2545 sub _get_items_columns {
2546 my $dbh = C4::Context->dbh;
2547 my $sth = $dbh->column_info(undef, undef, 'items', '%');
2549 my $results = $sth->fetchall_hashref('COLUMN_NAME');
2550 return keys %$results;
2555 my $items = SearchItems($field, $value);
2557 SearchItems will search for items on a specific given field.
2558 For instance you can search all items with a specific stocknumber like this:
2560 my $items = SearchItems('stocknumber', $stocknumber);
2565 my ($field, $value) = @_;
2567 my $dbh = C4::Context->dbh;
2568 my @columns = _get_items_columns;
2570 if(0 < grep /^$field$/, @columns) {
2571 my $query = "SELECT $field FROM items WHERE $field = ?";
2572 my $sth = $dbh->prepare( $query );
2573 $sth->execute( $value );
2574 $results = $sth->fetchall_arrayref({});
2580 =head1 OTHER FUNCTIONS
2584 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2586 Find the given $subfield in the given $tag in the given
2587 MARC::Record $record. If the subfield is found, returns
2588 the (indicators, value) pair; otherwise, (undef, undef) is
2592 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2593 I suggest we export it from this module.
2598 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2601 if ( $tagfield < 10 ) {
2602 if ( $record->field($tagfield) ) {
2603 push @result, $record->field($tagfield)->data();
2608 foreach my $field ( $record->field($tagfield) ) {
2609 my @subfields = $field->subfields();
2610 foreach my $subfield (@subfields) {
2611 if ( @$subfield[0] eq $insubfield ) {
2612 push @result, @$subfield[1];
2613 $indicator = $field->indicator(1) . $field->indicator(2);
2618 return ( $indicator, @result );
2622 =head2 PrepareItemrecordDisplay
2624 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2626 Returns a hash with all the fields for Display a given item data in a template
2628 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2632 sub PrepareItemrecordDisplay {
2634 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2636 my $dbh = C4::Context->dbh;
2637 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2638 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2639 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2641 # return nothing if we don't have found an existing framework.
2642 return q{} unless $tagslib;
2645 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2649 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2651 SELECT authorised_value,lib FROM authorised_values
2654 LEFT JOIN authorised_values_branches ON ( id = av_id )
2659 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2660 $query .= qq{ ORDER BY lib};
2661 my $authorised_values_sth = $dbh->prepare( $query );
2662 foreach my $tag ( sort keys %{$tagslib} ) {
2663 my $previous_tag = '';
2666 # loop through each subfield
2668 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2669 next if ( subfield_is_koha_internal_p($subfield) );
2670 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2672 $subfield_data{tag} = $tag;
2673 $subfield_data{subfield} = $subfield;
2674 $subfield_data{countsubfield} = $cntsubf++;
2675 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2676 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2678 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2679 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2680 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2681 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2682 $subfield_data{hidden} = "display:none"
2683 if $tagslib->{$tag}->{$subfield}->{hidden};
2684 my ( $x, $defaultvalue );
2686 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2688 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2689 if ( !defined $defaultvalue ) {
2690 $defaultvalue = q||;
2692 $defaultvalue =~ s/"/"/g;
2695 # search for itemcallnumber if applicable
2696 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2697 && C4::Context->preference('itemcallnumber') ) {
2698 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2699 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2700 if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2701 $defaultvalue = $field->subfield($CNsubfield);
2704 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2706 && $defaultvalues->{'callnumber'} ) {
2707 if( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ){
2708 # if the item record exists, only use default value if the item has no callnumber
2709 $defaultvalue = $defaultvalues->{callnumber};
2710 } elsif ( !$itemrecord and $defaultvalues ) {
2711 # if the item record *doesn't* exists, always use the default value
2712 $defaultvalue = $defaultvalues->{callnumber};
2715 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2717 && $defaultvalues->{'branchcode'} ) {
2718 if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2719 $defaultvalue = $defaultvalues->{branchcode};
2722 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2724 && $defaultvalues->{'location'} ) {
2726 if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2727 # if the item record exists, only use default value if the item has no locationr
2728 $defaultvalue = $defaultvalues->{location};
2729 } elsif ( !$itemrecord and $defaultvalues ) {
2730 # if the item record *doesn't* exists, always use the default value
2731 $defaultvalue = $defaultvalues->{location};
2734 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2735 my @authorised_values;
2738 # builds list, depending on authorised value...
2740 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2741 if ( ( C4::Context->preference("IndependentBranches") )
2742 && ( C4::Context->userenv && C4::Context->userenv->{flags} % 2 != 1 ) ) {
2743 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2744 $sth->execute( C4::Context->userenv->{branch} );
2745 push @authorised_values, ""
2746 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2747 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2748 push @authorised_values, $branchcode;
2749 $authorised_lib{$branchcode} = $branchname;
2752 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2754 push @authorised_values, ""
2755 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2756 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2757 push @authorised_values, $branchcode;
2758 $authorised_lib{$branchcode} = $branchname;
2762 $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2763 if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2764 $defaultvalue = $defaultvalues->{branchcode};
2768 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2769 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2771 push @authorised_values, ""
2772 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2773 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2774 push @authorised_values, $itemtype;
2775 $authorised_lib{$itemtype} = $description;
2778 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2779 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2781 my $class_sources = GetClassSources();
2782 my $default_source = C4::Context->preference("DefaultClassificationSource");
2784 foreach my $class_source (sort keys %$class_sources) {
2785 next unless $class_sources->{$class_source}->{'used'} or
2786 ($class_source eq $default_source);
2787 push @authorised_values, $class_source;
2788 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2791 $defaultvalue = $default_source;
2793 #---- "true" authorised value
2795 $authorised_values_sth->execute(
2796 $tagslib->{$tag}->{$subfield}->{authorised_value},
2797 $branch_limit ? $branch_limit : ()
2799 push @authorised_values, ""
2800 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2801 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2802 push @authorised_values, $value;
2803 $authorised_lib{$value} = $lib;
2806 $subfield_data{marc_value} = CGI::scrolling_list(
2807 -name => 'field_value',
2808 -values => \@authorised_values,
2809 -default => "$defaultvalue",
2810 -labels => \%authorised_lib,
2815 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2817 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2819 my $extended_param = plugin_parameters( $dbh, undef, $tagslib, $subfield_data{id}, undef );
2820 my ( $function_name, $javascript ) = plugin_javascript( $dbh, undef, $tagslib, $subfield_data{id}, undef );
2821 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2822 $subfield_data{marc_value} = qq[<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255"
2823 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2824 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2825 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2828 warn "Plugin Failed: $plugin";
2829 $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" />); # supply default input form
2832 elsif ( $tag eq '' ) { # it's an hidden field
2833 $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
2835 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2836 $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
2838 elsif ( length($defaultvalue) > 100
2839 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2840 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2841 or (C4::Context->preference("marcflavour") eq "MARC21" and
2842 500 <= $tag && $tag < 600 )
2844 # oversize field (textarea)
2845 $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255">$defaultvalue</textarea>\n");
2847 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2849 push( @loop_data, \%subfield_data );
2854 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2855 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2858 'itemtagfield' => $itemtagfield,
2859 'itemtagsubfield' => $itemtagsubfield,
2860 'itemnumber' => $itemnumber,
2861 'iteminformation' => \@loop_data