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/;
33 use Data
::Dumper
; # used as part of logging item record changes, not just for
34 # debugging; so please don't remove this
36 use vars
qw($VERSION @ISA @EXPORT);
39 $VERSION = 3.07.00.049;
42 @ISA = qw( Exporter );
65 GetItemsByBiblioitemnumber
69 GetItemnumbersForBiblio
71 get_hostitemnumbers_of
72 GetItemnumberFromBarcode
73 GetBarcodeFromItemnumber
87 PrepareItemrecordDisplay
94 C4::Items - item management functions
98 This module contains an API for manipulating item
99 records in Koha, and is used by cataloguing, circulation,
100 acquisitions, and serials management.
102 A Koha item record is stored in two places: the
103 items table and embedded in a MARC tag in the XML
104 version of the associated bib record in C<biblioitems.marcxml>.
105 This is done to allow the item information to be readily
106 indexed (e.g., by Zebra), but means that each item
107 modification transaction must keep the items table
108 and the MARC XML in sync at all times.
110 Consequently, all code that creates, modifies, or deletes
111 item records B<must> use an appropriate function from
112 C<C4::Items>. If no existing function is suitable, it is
113 better to add one to C<C4::Items> than to use add
114 one-off SQL statements to add or modify items.
116 The items table will be considered authoritative. In other
117 words, if there is ever a discrepancy between the items
118 table and the MARC XML, the items table should be considered
121 =head1 HISTORICAL NOTE
123 Most of the functions in C<C4::Items> were originally in
124 the C<C4::Biblio> module.
126 =head1 CORE EXPORTED FUNCTIONS
128 The following functions are meant for use by users
135 $item = GetItem($itemnumber,$barcode,$serial);
137 Return item information, for a given itemnumber or barcode.
138 The return value is a hashref mapping item column
139 names to values. If C<$serial> is true, include serial publication data.
144 my ($itemnumber,$barcode, $serial) = @_;
145 my $dbh = C4
::Context
->dbh;
148 my $sth = $dbh->prepare("
150 WHERE itemnumber = ?");
151 $sth->execute($itemnumber);
152 $data = $sth->fetchrow_hashref;
154 my $sth = $dbh->prepare("
158 $sth->execute($barcode);
159 $data = $sth->fetchrow_hashref;
162 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
163 $ssth->execute($data->{'itemnumber'}) ;
164 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
166 #if we don't have an items.itype, use biblioitems.itemtype.
167 if( ! $data->{'itype'} ) {
168 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
169 $sth->execute($data->{'biblionumber'});
170 ($data->{'itype'}) = $sth->fetchrow_array;
177 CartToShelf($itemnumber);
179 Set the current shelving location of the item record
180 to its stored permanent shelving location. This is
181 primarily used to indicate when an item whose current
182 location is a special processing ('PROC') or shelving cart
183 ('CART') location is back in the stacks.
188 my ( $itemnumber ) = @_;
190 unless ( $itemnumber ) {
191 croak
"FAILED CartToShelf() - no itemnumber supplied";
194 my $item = GetItem
($itemnumber);
195 if ( $item->{location
} eq 'CART' ) {
196 $item->{location
} = $item->{permanent_location
};
197 ModItem
($item, undef, $itemnumber);
203 ShelfToCart($itemnumber);
205 Set the current shelving location of the item
206 to shelving cart ('CART').
211 my ( $itemnumber ) = @_;
213 unless ( $itemnumber ) {
214 croak
"FAILED ShelfToCart() - no itemnumber supplied";
217 my $item = GetItem
($itemnumber);
218 $item->{'location'} = 'CART';
219 ModItem
($item, undef, $itemnumber);
222 =head2 AddItemFromMarc
224 my ($biblionumber, $biblioitemnumber, $itemnumber)
225 = AddItemFromMarc($source_item_marc, $biblionumber);
227 Given a MARC::Record object containing an embedded item
228 record and a biblionumber, create a new item record.
232 sub AddItemFromMarc
{
233 my ( $source_item_marc, $biblionumber ) = @_;
234 my $dbh = C4
::Context
->dbh;
236 # parse item hash from MARC
237 my $frameworkcode = GetFrameworkCode
( $biblionumber );
238 my ($itemtag,$itemsubfield)=GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
240 my $localitemmarc=MARC
::Record
->new;
241 $localitemmarc->append_fields($source_item_marc->field($itemtag));
242 my $item = &TransformMarcToKoha
( $dbh, $localitemmarc, $frameworkcode ,'items');
243 my $unlinked_item_subfields = _get_unlinked_item_subfields
($localitemmarc, $frameworkcode);
244 return AddItem
($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
249 my ($biblionumber, $biblioitemnumber, $itemnumber)
250 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
252 Given a hash containing item column names as keys,
253 create a new Koha item record.
255 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
256 do not need to be supplied for general use; they exist
257 simply to allow them to be picked up from AddItemFromMarc.
259 The final optional parameter, C<$unlinked_item_subfields>, contains
260 an arrayref containing subfields present in the original MARC
261 representation of the item (e.g., from the item editor) that are
262 not mapped to C<items> columns directly but should instead
263 be stored in C<items.more_subfields_xml> and included in
264 the biblio items tag for display and indexing.
270 my $biblionumber = shift;
272 my $dbh = @_ ?
shift : C4
::Context
->dbh;
273 my $frameworkcode = @_ ?
shift : GetFrameworkCode
( $biblionumber );
274 my $unlinked_item_subfields;
276 $unlinked_item_subfields = shift
279 # needs old biblionumber and biblioitemnumber
280 $item->{'biblionumber'} = $biblionumber;
281 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
282 $sth->execute( $item->{'biblionumber'} );
283 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
285 _set_defaults_for_add
($item);
286 _set_derived_columns_for_add
($item);
287 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
288 # FIXME - checks here
289 unless ( $item->{itype
} ) { # default to biblioitem.itemtype if no itype
290 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
291 $itype_sth->execute( $item->{'biblionumber'} );
292 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
295 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
296 $item->{'itemnumber'} = $itemnumber;
298 ModZebra
( $item->{biblionumber
}, "specialUpdate", "biblioserver", undef, undef );
300 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
302 return ($item->{biblionumber
}, $item->{biblioitemnumber
}, $itemnumber);
305 =head2 AddItemBatchFromMarc
307 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
308 $biblionumber, $biblioitemnumber, $frameworkcode);
310 Efficiently create item records from a MARC biblio record with
311 embedded item fields. This routine is suitable for batch jobs.
313 This API assumes that the bib record has already been
314 saved to the C<biblio> and C<biblioitems> tables. It does
315 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
316 are populated, but it will do so via a call to ModBibiloMarc.
318 The goal of this API is to have a similar effect to using AddBiblio
319 and AddItems in succession, but without inefficient repeated
320 parsing of the MARC XML bib record.
322 This function returns an arrayref of new itemsnumbers and an arrayref of item
323 errors encountered during the processing. Each entry in the errors
324 list is a hashref containing the following keys:
330 Sequence number of original item tag in the MARC record.
334 Item barcode, provide to assist in the construction of
335 useful error messages.
339 Code representing the error condition. Can be 'duplicate_barcode',
340 'invalid_homebranch', or 'invalid_holdingbranch'.
342 =item error_information
344 Additional information appropriate to the error condition.
350 sub AddItemBatchFromMarc
{
351 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
353 my @itemnumbers = ();
355 my $dbh = C4
::Context
->dbh;
357 # We modify the record, so lets work on a clone so we don't change the
359 $record = $record->clone();
360 # loop through the item tags and start creating items
361 my @bad_item_fields = ();
362 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField
("items.itemnumber",'');
363 my $item_sequence_num = 0;
364 ITEMFIELD
: foreach my $item_field ($record->field($itemtag)) {
365 $item_sequence_num++;
366 # we take the item field and stick it into a new
367 # MARC record -- this is required so far because (FIXME)
368 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
369 # and there is no TransformMarcFieldToKoha
370 my $temp_item_marc = MARC
::Record
->new();
371 $temp_item_marc->append_fields($item_field);
373 # add biblionumber and biblioitemnumber
374 my $item = TransformMarcToKoha
( $dbh, $temp_item_marc, $frameworkcode, 'items' );
375 my $unlinked_item_subfields = _get_unlinked_item_subfields
($temp_item_marc, $frameworkcode);
376 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
377 $item->{'biblionumber'} = $biblionumber;
378 $item->{'biblioitemnumber'} = $biblioitemnumber;
380 # check for duplicate barcode
381 my %item_errors = CheckItemPreSave
($item);
383 push @errors, _repack_item_errors
($item_sequence_num, $item, \
%item_errors);
384 push @bad_item_fields, $item_field;
388 _set_defaults_for_add
($item);
389 _set_derived_columns_for_add
($item);
390 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
391 warn $error if $error;
392 push @itemnumbers, $itemnumber; # FIXME not checking error
393 $item->{'itemnumber'} = $itemnumber;
395 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
397 my $new_item_marc = _marc_from_item_hash
($item, $frameworkcode, $unlinked_item_subfields);
398 $item_field->replace_with($new_item_marc->field($itemtag));
401 # remove any MARC item fields for rejected items
402 foreach my $item_field (@bad_item_fields) {
403 $record->delete_field($item_field);
406 # update the MARC biblio
407 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
409 return (\
@itemnumbers, \
@errors);
412 =head2 ModItemFromMarc
414 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
416 This function updates an item record based on a supplied
417 C<MARC::Record> object containing an embedded item field.
418 This API is meant for the use of C<additem.pl>; for
419 other purposes, C<ModItem> should be used.
421 This function uses the hash %default_values_for_mod_from_marc,
422 which contains default values for item fields to
423 apply when modifying an item. This is needed beccause
424 if an item field's value is cleared, TransformMarcToKoha
425 does not include the column in the
426 hash that's passed to ModItem, which without
427 use of this hash makes it impossible to clear
428 an item field's value. See bug 2466.
430 Note that only columns that can be directly
431 changed from the cataloging and serials
432 item editors are included in this hash.
438 my %default_values_for_mod_from_marc = (
440 booksellerid
=> undef,
442 'items.cn_source' => undef,
445 # dateaccessioned => undef,
447 holdingbranch
=> undef,
449 itemcallnumber
=> undef,
454 permanent_location
=> undef,
459 replacementprice
=> undef,
460 replacementpricedate
=> undef,
463 stocknumber
=> undef,
468 sub ModItemFromMarc
{
469 my $item_marc = shift;
470 my $biblionumber = shift;
471 my $itemnumber = shift;
473 my $dbh = C4
::Context
->dbh;
474 my $frameworkcode = GetFrameworkCode
($biblionumber);
475 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField
( "items.itemnumber", $frameworkcode );
477 my $localitemmarc = MARC
::Record
->new;
478 $localitemmarc->append_fields( $item_marc->field($itemtag) );
479 my $item = &TransformMarcToKoha
( $dbh, $localitemmarc, $frameworkcode, 'items' );
480 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
481 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
483 my $unlinked_item_subfields = _get_unlinked_item_subfields
( $localitemmarc, $frameworkcode );
485 ModItem
($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
491 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
493 Change one or more columns in an item record and update
494 the MARC representation of the item.
496 The first argument is a hashref mapping from item column
497 names to the new values. The second and third arguments
498 are the biblionumber and itemnumber, respectively.
500 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
501 an arrayref containing subfields present in the original MARC
502 representation of the item (e.g., from the item editor) that are
503 not mapped to C<items> columns directly but should instead
504 be stored in C<items.more_subfields_xml> and included in
505 the biblio items tag for display and indexing.
507 If one of the changed columns is used to calculate
508 the derived value of a column such as C<items.cn_sort>,
509 this routine will perform the necessary calculation
516 my $biblionumber = shift;
517 my $itemnumber = shift;
519 # if $biblionumber is undefined, get it from the current item
520 unless (defined $biblionumber) {
521 $biblionumber = _get_single_item_column
('biblionumber', $itemnumber);
524 my $dbh = @_ ?
shift : C4
::Context
->dbh;
525 my $frameworkcode = @_ ?
shift : GetFrameworkCode
( $biblionumber );
527 my $unlinked_item_subfields;
529 $unlinked_item_subfields = shift;
530 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
533 $item->{'itemnumber'} = $itemnumber or return undef;
535 $item->{onloan
} = undef if $item->{itemlost
};
537 _set_derived_columns_for_mod
($item);
538 _do_column_fixes_for_mod
($item);
541 # attempt to change itemnumber
542 # attempt to change biblionumber (if we want
543 # an API to relink an item to a different bib,
544 # it should be a separate function)
547 _koha_modify_item
($item);
549 # request that bib be reindexed so that searching on current
550 # item status is possible
551 ModZebra
( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
553 logaction
("CATALOGUING", "MODIFY", $itemnumber, Dumper
($item)) if C4
::Context
->preference("CataloguingLog");
556 =head2 ModItemTransfer
558 ModItemTransfer($itenumber, $frombranch, $tobranch);
560 Marks an item as being transferred from one branch
565 sub ModItemTransfer
{
566 my ( $itemnumber, $frombranch, $tobranch ) = @_;
568 my $dbh = C4
::Context
->dbh;
570 # Remove the 'shelving cart' location status if it is being used.
571 CartToShelf
( $itemnumber ) if ( C4
::Context
->preference("ReturnToShelvingCart") );
573 #new entry in branchtransfers....
574 my $sth = $dbh->prepare(
575 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
576 VALUES (?, ?, NOW(), ?)");
577 $sth->execute($itemnumber, $frombranch, $tobranch);
579 ModItem
({ holdingbranch
=> $tobranch }, undef, $itemnumber);
580 ModDateLastSeen
($itemnumber);
584 =head2 ModDateLastSeen
586 ModDateLastSeen($itemnum);
588 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
589 C<$itemnum> is the item number
593 sub ModDateLastSeen
{
594 my ($itemnumber) = @_;
596 my $today = C4
::Dates
->new();
597 ModItem
({ itemlost
=> 0, datelastseen
=> $today->output("iso") }, undef, $itemnumber);
602 DelItem($dbh, $biblionumber, $itemnumber);
604 Exported function (core API) for deleting an item record in Koha.
609 my ( $dbh, $biblionumber, $itemnumber ) = @_;
611 # FIXME check the item has no current issues
613 _koha_delete_item
( $dbh, $itemnumber );
615 # get the MARC record
616 my $record = GetMarcBiblio
($biblionumber);
617 ModZebra
( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
620 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
621 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
622 # This last update statement makes that the timestamp column in deleteditems is updated too. If you remove these lines, please add a line to update the timestamp separately. See Bugzilla report 7146 and Biblio.pm (DelBiblio).
624 #search item field code
625 logaction
("CATALOGUING", "DELETE", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
628 =head2 CheckItemPreSave
630 my $item_ref = TransformMarcToKoha($marc, 'items');
632 my %errors = CheckItemPreSave($item_ref);
633 if (exists $errors{'duplicate_barcode'}) {
634 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
635 } elsif (exists $errors{'invalid_homebranch'}) {
636 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
637 } elsif (exists $errors{'invalid_holdingbranch'}) {
638 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
643 Given a hashref containing item fields, determine if it can be
644 inserted or updated in the database. Specifically, checks for
645 database integrity issues, and returns a hash containing any
646 of the following keys, if applicable.
650 =item duplicate_barcode
652 Barcode, if it duplicates one already found in the database.
654 =item invalid_homebranch
656 Home branch, if not defined in branches table.
658 =item invalid_holdingbranch
660 Holding branch, if not defined in branches table.
664 This function does NOT implement any policy-related checks,
665 e.g., whether current operator is allowed to save an
666 item that has a given branch code.
670 sub CheckItemPreSave
{
671 my $item_ref = shift;
676 # check for duplicate barcode
677 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
678 my $existing_itemnumber = GetItemnumberFromBarcode
($item_ref->{'barcode'});
679 if ($existing_itemnumber) {
680 if (!exists $item_ref->{'itemnumber'} # new item
681 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
682 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
687 # check for valid home branch
688 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
689 my $branch_name = C4
::Branch
::GetBranchName
($item_ref->{'homebranch'});
690 unless (defined $branch_name) {
691 # relies on fact that branches.branchname is a non-NULL column,
692 # so GetBranchName returns undef only if branch does not exist
693 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
697 # check for valid holding branch
698 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
699 my $branch_name = C4
::Branch
::GetBranchName
($item_ref->{'holdingbranch'});
700 unless (defined $branch_name) {
701 # relies on fact that branches.branchname is a non-NULL column,
702 # so GetBranchName returns undef only if branch does not exist
703 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
711 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
713 The following functions provide various ways of
714 getting an item record, a set of item records, or
715 lists of authorized values for certain item fields.
717 Some of the functions in this group are candidates
718 for refactoring -- for example, some of the code
719 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
720 has copy-and-paste work.
726 $itemstatushash = GetItemStatus($fwkcode);
728 Returns a list of valid values for the
729 C<items.notforloan> field.
731 NOTE: does B<not> return an individual item's
734 Can be MARC dependant.
736 But basically could be can be loan or not
737 Create a status selector with the following code
739 =head3 in PERL SCRIPT
741 my $itemstatushash = getitemstatus;
743 foreach my $thisstatus (keys %$itemstatushash) {
744 my %row =(value => $thisstatus,
745 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
747 push @itemstatusloop, \%row;
749 $template->param(statusloop=>\@itemstatusloop);
753 <select name="statusloop">
754 <option value="">Default</option>
755 <!-- TMPL_LOOP name="statusloop" -->
756 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
764 # returns a reference to a hash of references to status...
767 my $dbh = C4
::Context
->dbh;
769 $fwk = '' unless ($fwk);
770 my ( $tag, $subfield ) =
771 GetMarcFromKohaField
( "items.notforloan", $fwk );
772 if ( $tag and $subfield ) {
775 "SELECT authorised_value
776 FROM marc_subfield_structure
782 $sth->execute( $tag, $subfield, $fwk );
783 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
786 "SELECT authorised_value,lib
787 FROM authorised_values
792 $authvalsth->execute($authorisedvaluecat);
793 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
794 $itemstatus{$authorisedvalue} = $lib;
808 $itemstatus{"1"} = "Not For Loan";
812 =head2 GetItemLocation
814 $itemlochash = GetItemLocation($fwk);
816 Returns a list of valid values for the
817 C<items.location> field.
819 NOTE: does B<not> return an individual item's
822 where fwk stands for an optional framework code.
823 Create a location selector with the following code
825 =head3 in PERL SCRIPT
827 my $itemlochash = getitemlocation;
829 foreach my $thisloc (keys %$itemlochash) {
830 my $selected = 1 if $thisbranch eq $branch;
831 my %row =(locval => $thisloc,
832 selected => $selected,
833 locname => $itemlochash->{$thisloc},
835 push @itemlocloop, \%row;
837 $template->param(itemlocationloop => \@itemlocloop);
841 <select name="location">
842 <option value="">Default</option>
843 <!-- TMPL_LOOP name="itemlocationloop" -->
844 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
850 sub GetItemLocation
{
852 # returns a reference to a hash of references to location...
855 my $dbh = C4
::Context
->dbh;
857 $fwk = '' unless ($fwk);
858 my ( $tag, $subfield ) =
859 GetMarcFromKohaField
( "items.location", $fwk );
860 if ( $tag and $subfield ) {
863 "SELECT authorised_value
864 FROM marc_subfield_structure
869 $sth->execute( $tag, $subfield, $fwk );
870 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
873 "SELECT authorised_value,lib
874 FROM authorised_values
878 $authvalsth->execute($authorisedvaluecat);
879 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
880 $itemlocation{$authorisedvalue} = $lib;
882 return \
%itemlocation;
894 $itemlocation{"1"} = "Not For Loan";
895 return \
%itemlocation;
900 $items = GetLostItems( $where, $orderby );
902 This function gets a list of lost items.
908 C<$where> is a hashref. it containts a field of the items table as key
909 and the value to match as value. For example:
911 { barcode => 'abc123',
912 homebranch => 'CPL', }
914 C<$orderby> is a field of the items table by which the resultset
919 C<$items> is a reference to an array full of hashrefs with columns
920 from the "items" table as keys.
922 =item usage in the perl script:
924 my $where = { barcode => '0001548' };
925 my $items = GetLostItems( $where, "homebranch" );
926 $template->param( itemsloop => $items );
933 # Getting input args.
936 my $dbh = C4
::Context
->dbh;
941 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
942 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
943 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
945 authorised_values.category = 'LOST'
946 AND itemlost IS NOT NULL
949 my @query_parameters;
950 foreach my $key (keys %$where) {
951 $query .= " AND $key LIKE ?";
952 push @query_parameters, "%$where->{$key}%";
954 my @ordervalues = qw
/title author homebranch itype barcode price replacementprice lib datelastseen location/;
956 if ( defined $orderby && grep($orderby, @ordervalues)) {
957 $query .= ' ORDER BY '.$orderby;
960 my $sth = $dbh->prepare($query);
961 $sth->execute( @query_parameters );
963 while ( my $row = $sth->fetchrow_hashref ){
969 =head2 GetItemsForInventory
971 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
972 $location, $itemtype $datelastseen, $branch,
973 $offset, $size, $statushash);
975 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
977 The sub returns a reference to a list of hashes, each containing
978 itemnumber, author, title, barcode, item callnumber, and date last
979 seen. It is ordered by callnumber then title.
981 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
982 the datelastseen can be used to specify that you want to see items not seen since a past date only.
983 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
984 $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.
988 sub GetItemsForInventory
{
989 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
990 my $dbh = C4
::Context
->dbh;
991 my ( @bind_params, @where_strings );
993 my $query = <<'END_SQL';
994 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
996 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
997 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1000 for my $authvfield (keys %$statushash){
1001 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1002 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1003 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1009 push @where_strings, 'itemcallnumber >= ?';
1010 push @bind_params, $minlocation;
1014 push @where_strings, 'itemcallnumber <= ?';
1015 push @bind_params, $maxlocation;
1018 if ($datelastseen) {
1019 $datelastseen = format_date_in_iso($datelastseen);
1020 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1021 push @bind_params, $datelastseen;
1025 push @where_strings, 'items.location = ?';
1026 push @bind_params, $location;
1029 if ( $branchcode ) {
1030 if($branch eq "homebranch"){
1031 push @where_strings, 'items.homebranch = ?';
1033 push @where_strings, 'items.holdingbranch = ?';
1035 push @bind_params, $branchcode;
1039 push @where_strings, 'biblioitems.itemtype = ?';
1040 push @bind_params, $itemtype;
1043 if ( $ignoreissued) {
1044 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1045 push @where_strings, 'issues.date_due IS NULL';
1048 if ( @where_strings ) {
1050 $query .= join ' AND ', @where_strings;
1052 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1053 my $sth = $dbh->prepare($query);
1054 $sth->execute( @bind_params );
1058 while ( my $row = $sth->fetchrow_hashref ) {
1059 $offset-- if ($offset);
1060 $row->{datelastseen}=format_date($row->{datelastseen});
1061 if ( ( !$offset ) && $size ) {
1062 push @results, $row;
1069 =head2 GetItemsCount
1071 $count = &GetItemsCount( $biblionumber);
1073 This function return count of item with $biblionumber
1078 my ( $biblionumber ) = @_;
1079 my $dbh = C4::Context->dbh;
1080 my $query = "SELECT count(*)
1082 WHERE biblionumber=?";
1083 my $sth = $dbh->prepare($query);
1084 $sth->execute($biblionumber);
1085 my $count = $sth->fetchrow;
1089 =head2 GetItemInfosOf
1091 GetItemInfosOf(@itemnumbers);
1095 sub GetItemInfosOf {
1096 my @itemnumbers = @_;
1101 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1103 return get_infos_of( $query, 'itemnumber' );
1106 =head2 GetItemsByBiblioitemnumber
1108 GetItemsByBiblioitemnumber($biblioitemnumber);
1110 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1111 Called by C<C4::XISBN>
1115 sub GetItemsByBiblioitemnumber {
1116 my ( $bibitem ) = @_;
1117 my $dbh = C4::Context->dbh;
1118 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1119 # Get all items attached to a biblioitem
1122 $sth->execute($bibitem) || die $sth->errstr;
1123 while ( my $data = $sth->fetchrow_hashref ) {
1124 # Foreach item, get circulation information
1125 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1126 WHERE itemnumber = ?
1127 AND issues.borrowernumber = borrowers.borrowernumber"
1129 $sth2->execute( $data->{'itemnumber'} );
1130 if ( my $data2 = $sth2->fetchrow_hashref ) {
1131 # if item is out, set the due date and who it is out too
1132 $data->{'date_due'} = $data2->{'date_due'};
1133 $data->{'cardnumber'} = $data2->{'cardnumber'};
1134 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1137 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1138 $data->{'date_due'} = '';
1140 # Find the last 3 people who borrowed this item.
1141 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1142 AND old_issues.borrowernumber = borrowers.borrowernumber
1143 ORDER BY returndate desc,timestamp desc LIMIT 3";
1144 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1145 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1147 while ( my $data2 = $sth2->fetchrow_hashref ) {
1148 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1149 $data->{"card$i2"} = $data2->{'cardnumber'};
1150 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1153 push(@results,$data);
1160 @results = GetItemsInfo($biblionumber);
1162 Returns information about items with the given biblionumber.
1164 C<GetItemsInfo> returns a list of references-to-hash. Each element
1165 contains a number of keys. Most of them are attributes from the
1166 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1167 Koha database. Other keys include:
1171 =item C<$data-E<gt>{branchname}>
1173 The name (not the code) of the branch to which the book belongs.
1175 =item C<$data-E<gt>{datelastseen}>
1177 This is simply C<items.datelastseen>, except that while the date is
1178 stored in YYYY-MM-DD format in the database, here it is converted to
1179 DD/MM/YYYY format. A NULL date is returned as C<//>.
1181 =item C<$data-E<gt>{datedue}>
1183 =item C<$data-E<gt>{class}>
1185 This is the concatenation of C<biblioitems.classification>, the book's
1186 Dewey code, and C<biblioitems.subclass>.
1188 =item C<$data-E<gt>{ocount}>
1190 I think this is the number of copies of the book available.
1192 =item C<$data-E<gt>{order}>
1194 If this is set, it is set to C<One Order>.
1201 my ( $biblionumber ) = @_;
1202 my $dbh = C4::Context->dbh;
1203 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1209 biblioitems.itemtype,
1212 biblioitems.publicationyear,
1213 biblioitems.publishercode,
1214 biblioitems.volumedate,
1215 biblioitems.volumedesc,
1218 items.notforloan as itemnotforloan,
1219 itemtypes.description,
1220 itemtypes.notforloan as notforloan_per_itemtype,
1223 holding.opac_info as branch_opac_info
1225 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1226 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1227 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1228 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1229 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1230 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1231 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1232 my $sth = $dbh->prepare($query);
1233 $sth->execute($biblionumber);
1238 my $isth = $dbh->prepare(
1239 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1240 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1241 WHERE itemnumber = ?"
1243 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1244 while ( my $data = $sth->fetchrow_hashref ) {
1246 $isth->execute( $data->{'itemnumber'} );
1247 if ( my $idata = $isth->fetchrow_hashref ) {
1248 $data->{borrowernumber} = $idata->{borrowernumber};
1249 $data->{cardnumber} = $idata->{cardnumber};
1250 $data->{surname} = $idata->{surname};
1251 $data->{firstname} = $idata->{firstname};
1252 $data->{lastreneweddate} = $idata->{lastreneweddate};
1253 $datedue = $idata->{'date_due'};
1254 if (C4::Context->preference("IndependantBranches")){
1255 my $userenv = C4::Context->userenv;
1256 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1257 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1261 if ( $data->{'serial'}) {
1262 $ssth->execute($data->{'itemnumber'}) ;
1263 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1266 #get branch information.....
1267 my $bsth = $dbh->prepare(
1268 "SELECT * FROM branches WHERE branchcode = ?
1271 $bsth->execute( $data->{'holdingbranch'} );
1272 if ( my $bdata = $bsth->fetchrow_hashref ) {
1273 $data->{'branchname'} = $bdata->{'branchname'};
1275 $data->{'datedue'} = $datedue;
1277 # get notforloan complete status if applicable
1278 if ( my $code = C4::Koha::GetAuthValCode( 'items.notforloan', $data->{frameworkcode} ) ) {
1279 $data->{notforloanvalue} = C4::Koha::GetAuthorisedValueByCode( $code, $data->{itemnotforloan} );
1282 # get restricted status and description if applicable
1283 if ( my $code = C4::Koha::GetAuthValCode( 'items.restricted', $data->{frameworkcode} ) ) {
1284 $data->{restricted} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
1285 $data->{restrictedopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted}, 'opac' );
1288 # my stack procedures
1289 if ( my $code = C4::Koha::GetAuthValCode( 'items.stack', $data->{frameworkcode} ) ) {
1290 $data->{stack} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{stack} );
1292 # Find the last 3 people who borrowed this item.
1293 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1294 WHERE itemnumber = ?
1295 AND old_issues.borrowernumber = borrowers.borrowernumber
1296 ORDER BY returndate DESC
1298 $sth2->execute($data->{'itemnumber'});
1300 while (my $data2 = $sth2->fetchrow_hashref()) {
1301 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1302 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1303 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1307 $results[$i] = $data;
1311 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1317 =head2 GetItemsLocationInfo
1319 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1321 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1323 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1327 =item C<$data-E<gt>{homebranch}>
1329 Branch Name of the item's homebranch
1331 =item C<$data-E<gt>{holdingbranch}>
1333 Branch Name of the item's holdingbranch
1335 =item C<$data-E<gt>{location}>
1337 Item's shelving location code
1339 =item C<$data-E<gt>{location_intranet}>
1341 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1343 =item C<$data-E<gt>{location_opac}>
1345 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1348 =item C<$data-E<gt>{itemcallnumber}>
1350 Item's itemcallnumber
1352 =item C<$data-E<gt>{cn_sort}>
1354 Item's call number normalized for sorting
1360 sub GetItemsLocationInfo {
1361 my $biblionumber = shift;
1364 my $dbh = C4::Context->dbh;
1365 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1366 location, itemcallnumber, cn_sort
1367 FROM items, branches as a, branches as b
1368 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1369 AND biblionumber = ?
1370 ORDER BY cn_sort ASC";
1371 my $sth = $dbh->prepare($query);
1372 $sth->execute($biblionumber);
1374 while ( my $data = $sth->fetchrow_hashref ) {
1375 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1376 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1377 push @results, $data;
1382 =head2 GetHostItemsInfo
1384 $hostiteminfo = GetHostItemsInfo($hostfield);
1385 Returns the iteminfo for items linked to records via a host field
1389 sub GetHostItemsInfo {
1391 my @returnitemsInfo;
1393 if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1394 C4::Context->preference('marcflavour') eq 'NORMARC'){
1395 foreach my $hostfield ( $record->field('773') ) {
1396 my $hostbiblionumber = $hostfield->subfield("0");
1397 my $linkeditemnumber = $hostfield->subfield("9");
1398 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1399 foreach my $hostitemInfo (@hostitemInfos){
1400 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1401 push (@returnitemsInfo,$hostitemInfo);
1406 } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1407 foreach my $hostfield ( $record->field('461') ) {
1408 my $hostbiblionumber = $hostfield->subfield("0");
1409 my $linkeditemnumber = $hostfield->subfield("9");
1410 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1411 foreach my $hostitemInfo (@hostitemInfos){
1412 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1413 push (@returnitemsInfo,$hostitemInfo);
1419 return @returnitemsInfo;
1423 =head2 GetLastAcquisitions
1425 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1426 'itemtypes' => ('BK','BD')}, 10);
1430 sub GetLastAcquisitions {
1431 my ($data,$max) = @_;
1433 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1435 my $number_of_branches = @{$data->{branches}};
1436 my $number_of_itemtypes = @{$data->{itemtypes}};
1439 my @where = ('WHERE 1 ');
1440 $number_of_branches and push @where
1441 , 'AND holdingbranch IN ('
1442 , join(',', ('?') x $number_of_branches )
1446 $number_of_itemtypes and push @where
1447 , "AND $itemtype IN ("
1448 , join(',', ('?') x $number_of_itemtypes )
1452 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1453 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1454 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1456 GROUP BY biblio.biblionumber
1457 ORDER BY dateaccessioned DESC LIMIT $max";
1459 my $dbh = C4::Context->dbh;
1460 my $sth = $dbh->prepare($query);
1462 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1465 while( my $row = $sth->fetchrow_hashref){
1466 push @results, {date => $row->{dateaccessioned}
1467 , biblionumber => $row->{biblionumber}
1468 , title => $row->{title}};
1474 =head2 GetItemnumbersForBiblio
1476 my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1478 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1482 sub GetItemnumbersForBiblio {
1483 my $biblionumber = shift;
1485 my $dbh = C4::Context->dbh;
1486 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1487 $sth->execute($biblionumber);
1488 while (my $result = $sth->fetchrow_hashref) {
1489 push @items, $result->{'itemnumber'};
1494 =head2 get_itemnumbers_of
1496 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1498 Given a list of biblionumbers, return the list of corresponding itemnumbers
1499 for each biblionumber.
1501 Return a reference on a hash where keys are biblionumbers and values are
1502 references on array of itemnumbers.
1506 sub get_itemnumbers_of {
1507 my @biblionumbers = @_;
1509 my $dbh = C4::Context->dbh;
1515 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1517 my $sth = $dbh->prepare($query);
1518 $sth->execute(@biblionumbers);
1522 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1523 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1526 return \%itemnumbers_of;
1529 =head2 get_hostitemnumbers_of
1531 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1533 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1535 Return a reference on a hash where key is a biblionumber and values are
1536 references on array of itemnumbers.
1541 sub get_hostitemnumbers_of {
1542 my ($biblionumber) = @_;
1543 my $marcrecord = GetMarcBiblio($biblionumber);
1544 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1546 my $marcflavor = C4::Context->preference('marcflavour');
1547 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1551 } elsif ($marcflavor eq 'UNIMARC') {
1557 foreach my $hostfield ( $marcrecord->field($tag) ) {
1558 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1559 my $linkeditemnumber = $hostfield->subfield($item_s);
1561 if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1563 @itemnumbers = @$itemnumbers;
1565 foreach my $itemnumber (@itemnumbers){
1566 if ($itemnumber eq $linkeditemnumber){
1567 push (@returnhostitemnumbers,$itemnumber);
1572 return @returnhostitemnumbers;
1576 =head2 GetItemnumberFromBarcode
1578 $result = GetItemnumberFromBarcode($barcode);
1582 sub GetItemnumberFromBarcode {
1584 my $dbh = C4::Context->dbh;
1587 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1588 $rq->execute($barcode);
1589 my ($result) = $rq->fetchrow;
1593 =head2 GetBarcodeFromItemnumber
1595 $result = GetBarcodeFromItemnumber($itemnumber);
1599 sub GetBarcodeFromItemnumber {
1600 my ($itemnumber) = @_;
1601 my $dbh = C4::Context->dbh;
1604 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1605 $rq->execute($itemnumber);
1606 my ($result) = $rq->fetchrow;
1610 =head2 GetHiddenItemnumbers
1614 $result = GetHiddenItemnumbers(@items);
1620 sub GetHiddenItemnumbers {
1624 my $yaml = C4::Context->preference('OpacHiddenItems');
1625 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1628 $hidingrules = YAML::Load($yaml);
1631 warn "Unable to parse OpacHiddenItems syspref : $@";
1634 my $dbh = C4::Context->dbh;
1637 foreach my $item (@items) {
1639 # We check each rule
1640 foreach my $field (keys %$hidingrules) {
1642 if (exists $item->{$field}) {
1643 $val = $item->{$field};
1646 my $query = "SELECT $field from items where itemnumber = ?";
1647 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1649 $val = '' unless defined $val;
1651 # If the results matches the values in the yaml file
1652 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1654 # We add the itemnumber to the list
1655 push @resultitems, $item->{'itemnumber'};
1657 # If at least one rule matched for an item, no need to test the others
1662 return @resultitems;
1665 =head3 get_item_authorised_values
1667 find the types and values for all authorised values assigned to this item.
1669 parameters: itemnumber
1671 returns: a hashref malling the authorised value to the value set for this itemnumber
1673 $authorised_values = {
1679 'RESTRICTED' => undef,
1682 'branches' => 'CPL',
1683 'cn_source' => undef,
1684 'itemtypes' => 'SER',
1687 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1691 sub get_item_authorised_values {
1692 my $itemnumber = shift;
1694 # assume that these entries in the authorised_value table are item level.
1695 my $query = q(SELECT distinct authorised_value, kohafield
1696 FROM marc_subfield_structure
1697 WHERE kohafield like 'item%'
1698 AND authorised_value != '' );
1700 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1701 my $iteminfo = GetItem( $itemnumber );
1702 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1704 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1705 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1706 $field =~ s/^items\.//;
1707 if ( exists $iteminfo->{ $field } ) {
1708 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1711 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1715 =head3 get_authorised_value_images
1717 find a list of icons that are appropriate for display based on the
1718 authorised values for a biblio.
1720 parameters: listref of authorised values, such as comes from
1721 get_item_authorised_values or
1722 from C4::Biblio::get_biblio_authorised_values
1724 returns: listref of hashrefs for each image. Each hashref looks like this:
1726 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1731 Notes: Currently, I put on the full path to the images on the staff
1732 side. This should either be configurable or not done at all. Since I
1733 have to deal with 'intranet' or 'opac' in
1734 get_biblio_authorised_values, perhaps I should be passing it in.
1738 sub get_authorised_value_images {
1739 my $authorised_values = shift;
1743 my $authorised_value_list = GetAuthorisedValues();
1744 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1745 foreach my $this_authorised_value ( @$authorised_value_list ) {
1746 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1747 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1748 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1749 if ( defined $this_authorised_value->{'imageurl'} ) {
1750 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1751 label => $this_authorised_value->{'lib'},
1752 category => $this_authorised_value->{'category'},
1753 value => $this_authorised_value->{'authorised_value'}, };
1758 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1763 =head1 LIMITED USE FUNCTIONS
1765 The following functions, while part of the public API,
1766 are not exported. This is generally because they are
1767 meant to be used by only one script for a specific
1768 purpose, and should not be used in any other context
1769 without careful thought.
1775 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1777 Returns MARC::Record of the item passed in parameter.
1778 This function is meant for use only in C<cataloguing/additem.pl>,
1779 where it is needed to support that script's MARC-like
1785 my ( $biblionumber, $itemnumber ) = @_;
1787 # GetMarcItem has been revised so that it does the following:
1788 # 1. Gets the item information from the items table.
1789 # 2. Converts it to a MARC field for storage in the bib record.
1791 # The previous behavior was:
1792 # 1. Get the bib record.
1793 # 2. Return the MARC tag corresponding to the item record.
1795 # The difference is that one treats the items row as authoritative,
1796 # while the other treats the MARC representation as authoritative
1797 # under certain circumstances.
1799 my $itemrecord = GetItem($itemnumber);
1801 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1802 # Also, don't emit a subfield if the underlying field is blank.
1805 return Item2Marc($itemrecord,$biblionumber);
1809 my ($itemrecord,$biblionumber)=@_;
1812 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1813 } keys %{ $itemrecord }
1815 my $itemmarc = TransformKohaToMarc($mungeditem);
1816 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1818 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1819 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1820 foreach my $field ($itemmarc->field($itemtag)){
1821 $field->add_subfields(@$unlinked_item_subfields);
1827 =head1 PRIVATE FUNCTIONS AND VARIABLES
1829 The following functions are not meant to be called
1830 directly, but are documented in order to explain
1831 the inner workings of C<C4::Items>.
1835 =head2 %derived_columns
1837 This hash keeps track of item columns that
1838 are strictly derived from other columns in
1839 the item record and are not meant to be set
1842 Each key in the hash should be the name of a
1843 column (as named by TransformMarcToKoha). Each
1844 value should be hashref whose keys are the
1845 columns on which the derived column depends. The
1846 hashref should also contain a 'BUILDER' key
1847 that is a reference to a sub that calculates
1852 my %derived_columns = (
1853 'items.cn_sort' => {
1854 'itemcallnumber' => 1,
1855 'items.cn_source' => 1,
1856 'BUILDER' => \&_calc_items_cn_sort,
1860 =head2 _set_derived_columns_for_add
1862 _set_derived_column_for_add($item);
1864 Given an item hash representing a new item to be added,
1865 calculate any derived columns. Currently the only
1866 such column is C<items.cn_sort>.
1870 sub _set_derived_columns_for_add {
1873 foreach my $column (keys %derived_columns) {
1874 my $builder = $derived_columns{$column}->{'BUILDER'};
1875 my $source_values = {};
1876 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1877 next if $source_column eq 'BUILDER';
1878 $source_values->{$source_column} = $item->{$source_column};
1880 $builder->($item, $source_values);
1884 =head2 _set_derived_columns_for_mod
1886 _set_derived_column_for_mod($item);
1888 Given an item hash representing a new item to be modified.
1889 calculate any derived columns. Currently the only
1890 such column is C<items.cn_sort>.
1892 This routine differs from C<_set_derived_columns_for_add>
1893 in that it needs to handle partial item records. In other
1894 words, the caller of C<ModItem> may have supplied only one
1895 or two columns to be changed, so this function needs to
1896 determine whether any of the columns to be changed affect
1897 any of the derived columns. Also, if a derived column
1898 depends on more than one column, but the caller is not
1899 changing all of then, this routine retrieves the unchanged
1900 values from the database in order to ensure a correct
1905 sub _set_derived_columns_for_mod {
1908 foreach my $column (keys %derived_columns) {
1909 my $builder = $derived_columns{$column}->{'BUILDER'};
1910 my $source_values = {};
1911 my %missing_sources = ();
1912 my $must_recalc = 0;
1913 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1914 next if $source_column eq 'BUILDER';
1915 if (exists $item->{$source_column}) {
1917 $source_values->{$source_column} = $item->{$source_column};
1919 $missing_sources{$source_column} = 1;
1923 foreach my $source_column (keys %missing_sources) {
1924 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1926 $builder->($item, $source_values);
1931 =head2 _do_column_fixes_for_mod
1933 _do_column_fixes_for_mod($item);
1935 Given an item hashref containing one or more
1936 columns to modify, fix up certain values.
1937 Specifically, set to 0 any passed value
1938 of C<notforloan>, C<damaged>, C<itemlost>, or
1939 C<wthdrawn> that is either undefined or
1940 contains the empty string.
1944 sub _do_column_fixes_for_mod {
1947 if (exists $item->{'notforloan'} and
1948 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1949 $item->{'notforloan'} = 0;
1951 if (exists $item->{'damaged'} and
1952 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1953 $item->{'damaged'} = 0;
1955 if (exists $item->{'itemlost'} and
1956 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1957 $item->{'itemlost'} = 0;
1959 if (exists $item->{'wthdrawn'} and
1960 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1961 $item->{'wthdrawn'} = 0;
1963 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1964 $item->{'permanent_location'} = $item->{'location'};
1966 if (exists $item->{'timestamp'}) {
1967 delete $item->{'timestamp'};
1971 =head2 _get_single_item_column
1973 _get_single_item_column($column, $itemnumber);
1975 Retrieves the value of a single column from an C<items>
1976 row specified by C<$itemnumber>.
1980 sub _get_single_item_column {
1982 my $itemnumber = shift;
1984 my $dbh = C4::Context->dbh;
1985 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1986 $sth->execute($itemnumber);
1987 my ($value) = $sth->fetchrow();
1991 =head2 _calc_items_cn_sort
1993 _calc_items_cn_sort($item, $source_values);
1995 Helper routine to calculate C<items.cn_sort>.
1999 sub _calc_items_cn_sort {
2001 my $source_values = shift;
2003 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2006 =head2 _set_defaults_for_add
2008 _set_defaults_for_add($item_hash);
2010 Given an item hash representing an item to be added, set
2011 correct default values for columns whose default value
2012 is not handled by the DBMS. This includes the following
2019 C<items.dateaccessioned>
2041 sub _set_defaults_for_add {
2043 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2044 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2047 =head2 _koha_new_item
2049 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2051 Perform the actual insert into the C<items> table.
2055 sub _koha_new_item
{
2056 my ( $item, $barcode ) = @_;
2057 my $dbh=C4
::Context
->dbh;
2060 "INSERT INTO items SET
2062 biblioitemnumber = ?,
2064 dateaccessioned = ?,
2068 replacementprice = ?,
2069 replacementpricedate = ?,
2070 datelastborrowed = ?,
2083 permanent_location = ?,
2095 more_subfields_xml = ?,
2099 my $sth = $dbh->prepare($query);
2100 my $today = C4
::Dates
->today('iso');
2102 $item->{'biblionumber'},
2103 $item->{'biblioitemnumber'},
2105 $item->{'dateaccessioned'},
2106 $item->{'booksellerid'},
2107 $item->{'homebranch'},
2109 $item->{'replacementprice'},
2110 $item->{'replacementpricedate'} || $today,
2111 $item->{datelastborrowed
},
2112 $item->{datelastseen
} || $today,
2114 $item->{'notforloan'},
2116 $item->{'itemlost'},
2117 $item->{'wthdrawn'},
2118 $item->{'itemcallnumber'},
2119 $item->{'restricted'},
2120 $item->{'itemnotes'},
2121 $item->{'holdingbranch'},
2123 $item->{'location'},
2124 $item->{'permanent_location'},
2127 $item->{'renewals'},
2128 $item->{'reserves'},
2129 $item->{'items.cn_source'},
2130 $item->{'items.cn_sort'},
2133 $item->{'materials'},
2135 $item->{'enumchron'},
2136 $item->{'more_subfields_xml'},
2137 $item->{'copynumber'},
2138 $item->{'stocknumber'},
2142 if ( defined $sth->errstr ) {
2143 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2146 $itemnumber = $dbh->{'mysql_insertid'};
2149 return ( $itemnumber, $error );
2152 =head2 MoveItemFromBiblio
2154 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2156 Moves an item from a biblio to another
2158 Returns undef if the move failed or the biblionumber of the destination record otherwise
2162 sub MoveItemFromBiblio
{
2163 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2164 my $dbh = C4
::Context
->dbh;
2165 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2166 $sth->execute( $tobiblio );
2167 my ( $tobiblioitem ) = $sth->fetchrow();
2168 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2169 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2171 ModZebra
( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2172 ModZebra
( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2173 # Checking if the item we want to move is in an order
2174 require C4
::Acquisition
;
2175 my $order = C4
::Acquisition
::GetOrderFromItemnumber
($itemnumber);
2177 # Replacing the biblionumber within the order if necessary
2178 $order->{'biblionumber'} = $tobiblio;
2179 C4
::Acquisition
::ModOrder
($order);
2188 DelItemCheck($dbh, $biblionumber, $itemnumber);
2190 Exported function (core API) for deleting an item record in Koha if there no current issue.
2195 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2198 my $countanalytics=GetAnalyticsCount
($itemnumber);
2201 # check that there is no issue on this item before deletion.
2202 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2203 $sth->execute($itemnumber);
2205 my $item = GetItem
($itemnumber);
2206 my $onloan=$sth->fetchrow;
2209 $error = "book_on_loan"
2211 elsif ( !(C4
::Context
->userenv->{flags
} & 1) and
2212 C4
::Context
->preference("IndependantBranches") and
2213 (C4
::Context
->userenv->{branch
} ne
2214 $item->{C4
::Context
->preference("HomeOrHoldingBranch")||'homebranch'}) )
2216 $error = "not_same_branch";
2219 # check it doesnt have a waiting reserve
2220 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2221 $sth->execute($itemnumber);
2222 my $reserve=$sth->fetchrow;
2224 $error = "book_reserved";
2225 } elsif ($countanalytics > 0){
2226 $error = "linked_analytics";
2228 DelItem
($dbh, $biblionumber, $itemnumber);
2235 =head2 _koha_modify_item
2237 my ($itemnumber,$error) =_koha_modify_item( $item );
2239 Perform the actual update of the C<items> row. Note that this
2240 routine accepts a hashref specifying the columns to update.
2244 sub _koha_modify_item
{
2246 my $dbh=C4
::Context
->dbh;
2249 my $query = "UPDATE items SET ";
2251 for my $key ( keys %$item ) {
2253 push @bind, $item->{$key};
2256 $query .= " WHERE itemnumber=?";
2257 push @bind, $item->{'itemnumber'};
2258 my $sth = C4
::Context
->dbh->prepare($query);
2259 $sth->execute(@bind);
2260 if ( C4
::Context
->dbh->errstr ) {
2261 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2264 return ($item->{'itemnumber'},$error);
2267 =head2 _koha_delete_item
2269 _koha_delete_item( $dbh, $itemnum );
2271 Internal function to delete an item record from the koha tables
2275 sub _koha_delete_item
{
2276 my ( $dbh, $itemnum ) = @_;
2278 # save the deleted item to deleteditems table
2279 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2280 $sth->execute($itemnum);
2281 my $data = $sth->fetchrow_hashref();
2282 my $query = "INSERT INTO deleteditems SET ";
2284 foreach my $key ( keys %$data ) {
2285 $query .= "$key = ?,";
2286 push( @bind, $data->{$key} );
2289 $sth = $dbh->prepare($query);
2290 $sth->execute(@bind);
2292 # delete from items table
2293 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2294 $sth->execute($itemnum);
2298 =head2 _marc_from_item_hash
2300 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2302 Given an item hash representing a complete item record,
2303 create a C<MARC::Record> object containing an embedded
2304 tag representing that item.
2306 The third, optional parameter C<$unlinked_item_subfields> is
2307 an arrayref of subfields (not mapped to C<items> fields per the
2308 framework) to be added to the MARC representation
2313 sub _marc_from_item_hash
{
2315 my $frameworkcode = shift;
2316 my $unlinked_item_subfields;
2318 $unlinked_item_subfields = shift;
2321 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2322 # Also, don't emit a subfield if the underlying field is blank.
2323 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2324 (/^items\./ ?
($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2325 : () } keys %{ $item } };
2327 my $item_marc = MARC
::Record
->new();
2328 foreach my $item_field ( keys %{$mungeditem} ) {
2329 my ( $tag, $subfield ) = GetMarcFromKohaField
( $item_field, $frameworkcode );
2330 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2331 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2332 foreach my $value (@values){
2333 if ( my $field = $item_marc->field($tag) ) {
2334 $field->add_subfields( $subfield => $value );
2336 my $add_subfields = [];
2337 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2338 $add_subfields = $unlinked_item_subfields;
2340 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @
$add_subfields );
2348 =head2 _repack_item_errors
2350 Add an error message hash generated by C<CheckItemPreSave>
2351 to a list of errors.
2355 sub _repack_item_errors
{
2356 my $item_sequence_num = shift;
2357 my $item_ref = shift;
2358 my $error_ref = shift;
2360 my @repacked_errors = ();
2362 foreach my $error_code (sort keys %{ $error_ref }) {
2363 my $repacked_error = {};
2364 $repacked_error->{'item_sequence'} = $item_sequence_num;
2365 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ?
$item_ref->{'barcode'} : '';
2366 $repacked_error->{'error_code'} = $error_code;
2367 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2368 push @repacked_errors, $repacked_error;
2371 return @repacked_errors;
2374 =head2 _get_unlinked_item_subfields
2376 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2380 sub _get_unlinked_item_subfields
{
2381 my $original_item_marc = shift;
2382 my $frameworkcode = shift;
2384 my $marcstructure = GetMarcStructure
(1, $frameworkcode);
2386 # assume that this record has only one field, and that that
2387 # field contains only the item information
2389 my @fields = $original_item_marc->fields();
2390 if ($#fields > -1) {
2391 my $field = $fields[0];
2392 my $tag = $field->tag();
2393 foreach my $subfield ($field->subfields()) {
2394 if (defined $subfield->[1] and
2395 $subfield->[1] ne '' and
2396 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2397 push @
$subfields, $subfield->[0] => $subfield->[1];
2404 =head2 _get_unlinked_subfields_xml
2406 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2410 sub _get_unlinked_subfields_xml
{
2411 my $unlinked_item_subfields = shift;
2414 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2415 my $marc = MARC
::Record
->new();
2416 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2417 # used in the framework
2418 $marc->append_fields(MARC
::Field
->new('999', ' ', ' ', @
$unlinked_item_subfields));
2419 $marc->encoding("UTF-8");
2420 $xml = $marc->as_xml("USMARC");
2426 =head2 _parse_unlinked_item_subfields_from_xml
2428 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2432 sub _parse_unlinked_item_subfields_from_xml
{
2434 require C4
::Charset
;
2435 return unless defined $xml and $xml ne "";
2436 my $marc = MARC
::Record
->new_from_xml(C4
::Charset
::StripNonXmlChars
($xml),'UTF-8');
2437 my $unlinked_subfields = [];
2438 my @fields = $marc->fields();
2439 if ($#fields > -1) {
2440 foreach my $subfield ($fields[0]->subfields()) {
2441 push @
$unlinked_subfields, $subfield->[0] => $subfield->[1];
2444 return $unlinked_subfields;
2447 =head2 GetAnalyticsCount
2449 $count= &GetAnalyticsCount($itemnumber)
2451 counts Usage of itemnumber in Analytical bibliorecords.
2455 sub GetAnalyticsCount
{
2456 my ($itemnumber) = @_;
2458 if (C4
::Context
->preference('NoZebra')) {
2459 # Read the index Koha-Auth-Number for this authid and count the lines
2460 my $result = C4
::Search
::NZanalyse
("hi=$itemnumber");
2461 my @tab = split /;/,$result;
2464 ### ZOOM search here
2466 $query= "hi=".$itemnumber;
2467 my ($err,$res,$result) = C4
::Search
::SimpleSearch
($query,0,10);
2475 $holds = &GetItemHolds($biblionumber, $itemnumber);
2479 This function return the count of holds with $biblionumber and $itemnumber
2484 my ($biblionumber, $itemnumber) = @_;
2486 my $dbh = C4
::Context
->dbh;
2487 my $query = "SELECT count(*)
2489 WHERE biblionumber=? AND itemnumber=?";
2490 my $sth = $dbh->prepare($query);
2491 $sth->execute($biblionumber, $itemnumber);
2492 $holds = $sth->fetchrow;
2496 # Return the list of the column names of items table
2497 sub _get_items_columns
{
2498 my $dbh = C4
::Context
->dbh;
2499 my $sth = $dbh->column_info(undef, undef, 'items', '%');
2501 my $results = $sth->fetchall_hashref('COLUMN_NAME');
2502 return keys %$results;
2507 my $items = SearchItems($field, $value);
2509 SearchItems will search for items on a specific given field.
2510 For instance you can search all items with a specific stocknumber like this:
2512 my $items = SearchItems('stocknumber', $stocknumber);
2517 my ($field, $value) = @_;
2519 my $dbh = C4
::Context
->dbh;
2520 my @columns = _get_items_columns
;
2522 if(0 < grep /^$field$/, @columns) {
2523 my $query = "SELECT $field FROM items WHERE $field = ?";
2524 my $sth = $dbh->prepare( $query );
2525 $sth->execute( $value );
2526 $results = $sth->fetchall_arrayref({});
2532 =head1 OTHER FUNCTIONS
2536 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2538 Find the given $subfield in the given $tag in the given
2539 MARC::Record $record. If the subfield is found, returns
2540 the (indicators, value) pair; otherwise, (undef, undef) is
2544 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2545 I suggest we export it from this module.
2550 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2553 if ( $tagfield < 10 ) {
2554 if ( $record->field($tagfield) ) {
2555 push @result, $record->field($tagfield)->data();
2560 foreach my $field ( $record->field($tagfield) ) {
2561 my @subfields = $field->subfields();
2562 foreach my $subfield (@subfields) {
2563 if ( @
$subfield[0] eq $insubfield ) {
2564 push @result, @
$subfield[1];
2565 $indicator = $field->indicator(1) . $field->indicator(2);
2570 return ( $indicator, @result );
2574 =head2 PrepareItemrecordDisplay
2576 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2578 Returns a hash with all the fields for Display a given item data in a template
2580 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2584 sub PrepareItemrecordDisplay
{
2586 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2588 my $dbh = C4
::Context
->dbh;
2589 $frameworkcode = &GetFrameworkCode
($bibnum) if $bibnum;
2590 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField
( "items.itemnumber", $frameworkcode );
2591 my $tagslib = &GetMarcStructure
( 1, $frameworkcode );
2593 # return nothing if we don't have found an existing framework.
2594 return q{} unless $tagslib;
2597 $itemrecord = C4
::Items
::GetMarcItem
( $bibnum, $itemnum );
2600 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2601 foreach my $tag ( sort keys %{$tagslib} ) {
2602 my $previous_tag = '';
2605 # loop through each subfield
2607 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2608 next if ( subfield_is_koha_internal_p
($subfield) );
2609 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2611 $subfield_data{tag
} = $tag;
2612 $subfield_data{subfield
} = $subfield;
2613 $subfield_data{countsubfield
} = $cntsubf++;
2614 $subfield_data{kohafield
} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2615 $subfield_data{id
} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2617 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2618 $subfield_data{marc_lib
} = $tagslib->{$tag}->{$subfield}->{lib
};
2619 $subfield_data{mandatory
} = $tagslib->{$tag}->{$subfield}->{mandatory
};
2620 $subfield_data{repeatable
} = $tagslib->{$tag}->{$subfield}->{repeatable
};
2621 $subfield_data{hidden
} = "display:none"
2622 if $tagslib->{$tag}->{$subfield}->{hidden
};
2623 my ( $x, $defaultvalue );
2625 ( $x, $defaultvalue ) = _find_value
( $tag, $subfield, $itemrecord );
2627 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue
} unless $defaultvalue;
2628 if ( !defined $defaultvalue ) {
2629 $defaultvalue = q
||;
2631 $defaultvalue =~ s/"/"/g;
2633 # search for itemcallnumber if applicable
2634 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.itemcallnumber'
2635 && C4
::Context
->preference('itemcallnumber') ) {
2636 my $CNtag = substr( C4
::Context
->preference('itemcallnumber'), 0, 3 );
2637 my $CNsubfield = substr( C4
::Context
->preference('itemcallnumber'), 3, 1 );
2639 my $temp = $itemrecord->field($CNtag);
2641 $defaultvalue = $temp->subfield($CNsubfield);
2645 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.itemcallnumber'
2647 && $defaultvalues->{'callnumber'} ) {
2650 $temp = $itemrecord->field($subfield);
2653 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2656 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.homebranch' )
2658 && $defaultvalues->{'branchcode'} ) {
2661 $temp = $itemrecord->field($subfield);
2664 $defaultvalue = $defaultvalues->{branchcode
} if $defaultvalues;
2667 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.location' )
2669 && $defaultvalues->{'location'} ) {
2670 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2672 $defaultvalue = $defaultvalues->{location
} if $defaultvalues;
2675 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
2676 my @authorised_values;
2679 # builds list, depending on authorised value...
2681 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2682 if ( ( C4
::Context
->preference("IndependantBranches") )
2683 && ( C4
::Context
->userenv->{flags
} % 2 != 1 ) ) {
2684 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2685 $sth->execute( C4
::Context
->userenv->{branch
} );
2686 push @authorised_values, ""
2687 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2688 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2689 push @authorised_values, $branchcode;
2690 $authorised_lib{$branchcode} = $branchname;
2693 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2695 push @authorised_values, ""
2696 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2697 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2698 push @authorised_values, $branchcode;
2699 $authorised_lib{$branchcode} = $branchname;
2704 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "itemtypes" ) {
2705 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2707 push @authorised_values, ""
2708 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2709 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2710 push @authorised_values, $itemtype;
2711 $authorised_lib{$itemtype} = $description;
2714 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "cn_source" ) {
2715 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2717 my $class_sources = GetClassSources
();
2718 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
2720 foreach my $class_source (sort keys %$class_sources) {
2721 next unless $class_sources->{$class_source}->{'used'} or
2722 ($class_source eq $default_source);
2723 push @authorised_values, $class_source;
2724 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2727 #---- "true" authorised value
2729 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value
} );
2730 push @authorised_values, ""
2731 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2732 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2733 push @authorised_values, $value;
2734 $authorised_lib{$value} = $lib;
2737 $subfield_data{marc_value
} = CGI
::scrolling_list
(
2738 -name
=> 'field_value',
2739 -values => \
@authorised_values,
2740 -default => "$defaultvalue",
2741 -labels
=> \
%authorised_lib,
2746 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder
} ) {
2748 my $plugin = C4
::Context
->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2751 my $extended_param = plugin_parameters
( $dbh, $temp, $tagslib, $subfield_data{id
}, undef );
2752 my ( $function_name, $javascript ) = plugin_javascript
( $dbh, $temp, $tagslib, $subfield_data{id
}, undef );
2753 $subfield_data{random
} = int(rand(1000000)); # why do we need 2 different randoms?
2754 $subfield_data{marc_value
} = qq[<input tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="67" maxlength
="255"
2755 onfocus
="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2756 onblur
=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2757 <a href
="#" class="buttonDot" onclick
="Clic$function_name('$subfield_data{id}'); return false;" title
="Tag Editor">...</a
>
2760 warn "Plugin Failed: $plugin";
2761 $subfield_data{marc_value
} = qq(<input tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="67" maxlength
="255" />); # supply default input form
2764 elsif ( $tag eq '' ) { # it's an hidden field
2765 $subfield_data{marc_value
} = qq(<input type
="hidden" tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="67" maxlength
="255" value
="$defaultvalue" />);
2767 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2768 $subfield_data{marc_value
} = qq(<input type
="text" tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="67" maxlength
="255" value
="$defaultvalue" />);
2770 elsif ( length($defaultvalue) > 100
2771 or (C4
::Context
->preference("marcflavour") eq "UNIMARC" and
2772 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2773 or (C4
::Context
->preference("marcflavour") eq "MARC21" and
2774 500 <= $tag && $tag < 600 )
2776 # oversize field (textarea)
2777 $subfield_data{marc_value
} = qq(<textarea tabindex
="1" id
="$subfield_data{id}" name
="field_value" class="input_marceditor" size
="67" maxlength
="255">$defaultvalue</textarea
>\n");
2779 $subfield_data{marc_value} = "<input type
=\"text
\" name
=\"field_value
\" value
=\"$defaultvalue\" size
=\"50\" maxlength
=\"255\" />";
2781 push( @loop_data, \%subfield_data );
2786 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2787 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2790 'itemtagfield' => $itemtagfield,
2791 'itemtagsubfield' => $itemtagsubfield,
2792 'itemnumber' => $itemnumber,
2793 'iteminformation' => \@loop_data