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" );
653 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
654 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
655 # 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).
657 #search item field code
658 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
661 =head2 CheckItemPreSave
663 my $item_ref = TransformMarcToKoha($marc, 'items');
665 my %errors = CheckItemPreSave($item_ref);
666 if (exists $errors{'duplicate_barcode'}) {
667 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
668 } elsif (exists $errors{'invalid_homebranch'}) {
669 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
670 } elsif (exists $errors{'invalid_holdingbranch'}) {
671 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
676 Given a hashref containing item fields, determine if it can be
677 inserted or updated in the database. Specifically, checks for
678 database integrity issues, and returns a hash containing any
679 of the following keys, if applicable.
683 =item duplicate_barcode
685 Barcode, if it duplicates one already found in the database.
687 =item invalid_homebranch
689 Home branch, if not defined in branches table.
691 =item invalid_holdingbranch
693 Holding branch, if not defined in branches table.
697 This function does NOT implement any policy-related checks,
698 e.g., whether current operator is allowed to save an
699 item that has a given branch code.
703 sub CheckItemPreSave {
704 my $item_ref = shift;
709 # check for duplicate barcode
710 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
711 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
712 if ($existing_itemnumber) {
713 if (!exists $item_ref->{'itemnumber'} # new item
714 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
715 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
720 # check for valid home branch
721 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
722 my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
723 unless (defined $branch_name) {
724 # relies on fact that branches.branchname is a non-NULL column,
725 # so GetBranchName returns undef only if branch does not exist
726 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
730 # check for valid holding branch
731 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
732 my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
733 unless (defined $branch_name) {
734 # relies on fact that branches.branchname is a non-NULL column,
735 # so GetBranchName returns undef only if branch does not exist
736 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
744 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
746 The following functions provide various ways of
747 getting an item record, a set of item records, or
748 lists of authorized values for certain item fields.
750 Some of the functions in this group are candidates
751 for refactoring -- for example, some of the code
752 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
753 has copy-and-paste work.
759 $itemstatushash = GetItemStatus($fwkcode);
761 Returns a list of valid values for the
762 C<items.notforloan> field.
764 NOTE: does B<not> return an individual item's
767 Can be MARC dependant.
769 But basically could be can be loan or not
770 Create a status selector with the following code
772 =head3 in PERL SCRIPT
774 my $itemstatushash = getitemstatus;
776 foreach my $thisstatus (keys %$itemstatushash) {
777 my %row =(value => $thisstatus,
778 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
780 push @itemstatusloop, \%row;
782 $template->param(statusloop=>\@itemstatusloop);
786 <select name="statusloop" id="statusloop">
787 <option value="">Default</option>
788 [% FOREACH statusloo IN statusloop %]
789 [% IF ( statusloo.selected ) %]
790 <option value="[% statusloo.value %]" selected="selected">[% statusloo.statusname %]</option>
792 <option value="[% statusloo.value %]">[% statusloo.statusname %]</option>
801 # returns a reference to a hash of references to status...
804 my $dbh = C4::Context->dbh;
806 $fwk = '' unless ($fwk);
807 my ( $tag, $subfield ) =
808 GetMarcFromKohaField( "items.notforloan", $fwk );
809 if ( $tag and $subfield ) {
812 "SELECT authorised_value
813 FROM marc_subfield_structure
819 $sth->execute( $tag, $subfield, $fwk );
820 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
823 "SELECT authorised_value,lib
824 FROM authorised_values
829 $authvalsth->execute($authorisedvaluecat);
830 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
831 $itemstatus{$authorisedvalue} = $lib;
845 $itemstatus{"1"} = "Not For Loan";
849 =head2 GetItemLocation
851 $itemlochash = GetItemLocation($fwk);
853 Returns a list of valid values for the
854 C<items.location> field.
856 NOTE: does B<not> return an individual item's
859 where fwk stands for an optional framework code.
860 Create a location selector with the following code
862 =head3 in PERL SCRIPT
864 my $itemlochash = getitemlocation;
866 foreach my $thisloc (keys %$itemlochash) {
867 my $selected = 1 if $thisbranch eq $branch;
868 my %row =(locval => $thisloc,
869 selected => $selected,
870 locname => $itemlochash->{$thisloc},
872 push @itemlocloop, \%row;
874 $template->param(itemlocationloop => \@itemlocloop);
878 <select name="location">
879 <option value="">Default</option>
880 <!-- TMPL_LOOP name="itemlocationloop" -->
881 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
887 sub GetItemLocation {
889 # returns a reference to a hash of references to location...
892 my $dbh = C4::Context->dbh;
894 $fwk = '' unless ($fwk);
895 my ( $tag, $subfield ) =
896 GetMarcFromKohaField( "items.location", $fwk );
897 if ( $tag and $subfield ) {
900 "SELECT authorised_value
901 FROM marc_subfield_structure
906 $sth->execute( $tag, $subfield, $fwk );
907 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
910 "SELECT authorised_value,lib
911 FROM authorised_values
915 $authvalsth->execute($authorisedvaluecat);
916 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
917 $itemlocation{$authorisedvalue} = $lib;
919 return \%itemlocation;
931 $itemlocation{"1"} = "Not For Loan";
932 return \%itemlocation;
937 $items = GetLostItems( $where, $orderby );
939 This function gets a list of lost items.
945 C<$where> is a hashref. it containts a field of the items table as key
946 and the value to match as value. For example:
948 { barcode => 'abc123',
949 homebranch => 'CPL', }
951 C<$orderby> is a field of the items table by which the resultset
956 C<$items> is a reference to an array full of hashrefs with columns
957 from the "items" table as keys.
959 =item usage in the perl script:
961 my $where = { barcode => '0001548' };
962 my $items = GetLostItems( $where, "homebranch" );
963 $template->param( itemsloop => $items );
970 # Getting input args.
973 my $dbh = C4::Context->dbh;
976 SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
977 itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber
979 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
980 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
981 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
983 authorised_values.category = 'LOST'
984 AND itemlost IS NOT NULL
987 my @query_parameters;
988 foreach my $key (keys %$where) {
989 $query .= " AND $key LIKE ?";
990 push @query_parameters, "%$where->{$key}%";
992 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
994 if ( defined $orderby && grep($orderby, @ordervalues)) {
995 $query .= ' ORDER BY '.$orderby;
998 my $sth = $dbh->prepare($query);
999 $sth->execute( @query_parameters );
1001 while ( my $row = $sth->fetchrow_hashref ){
1007 =head2 GetItemsForInventory
1009 ($itemlist, $iTotalRecords) = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $offset, $size, $statushash);
1011 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1013 The sub returns a reference to a list of hashes, each containing
1014 itemnumber, author, title, barcode, item callnumber, and date last
1015 seen. It is ordered by callnumber then title.
1017 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1018 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1019 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1020 $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.
1022 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
1026 sub GetItemsForInventory {
1027 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
1028 my $dbh = C4::Context->dbh;
1029 my ( @bind_params, @where_strings );
1031 my $select_columns = q{
1032 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, stocknumber
1034 my $select_count = q{SELECT COUNT(*)};
1037 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1038 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1041 for my $authvfield (keys %$statushash){
1042 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1043 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1044 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1050 push @where_strings, 'itemcallnumber >= ?';
1051 push @bind_params, $minlocation;
1055 push @where_strings, 'itemcallnumber <= ?';
1056 push @bind_params, $maxlocation;
1059 if ($datelastseen) {
1060 $datelastseen = format_date_in_iso($datelastseen);
1061 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1062 push @bind_params, $datelastseen;
1066 push @where_strings, 'items.location = ?';
1067 push @bind_params, $location;
1070 if ( $branchcode ) {
1071 if($branch eq "homebranch"){
1072 push @where_strings, 'items.homebranch = ?';
1074 push @where_strings, 'items.holdingbranch = ?';
1076 push @bind_params, $branchcode;
1080 push @where_strings, 'biblioitems.itemtype = ?';
1081 push @bind_params, $itemtype;
1084 if ( $ignoreissued) {
1085 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1086 push @where_strings, 'issues.date_due IS NULL';
1089 if ( @where_strings ) {
1091 $query .= join ' AND ', @where_strings;
1093 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1094 my $count_query = $select_count . $query;
1095 $query .= " LIMIT $offset, $size" if ($offset and $size);
1096 $query = $select_columns . $query;
1097 my $sth = $dbh->prepare($query);
1098 $sth->execute( @bind_params );
1101 my $tmpresults = $sth->fetchall_arrayref({});
1102 $sth = $dbh->prepare( $count_query );
1103 $sth->execute( @bind_params );
1104 my ($iTotalRecords) = $sth->fetchrow_array();
1106 foreach my $row (@$tmpresults) {
1109 foreach (keys %$row) {
1110 # If the koha field is mapped to a marc field
1111 my ($f, $sf) = GetMarcFromKohaField("items.$_", $row->{'frameworkcode'});
1113 # We replace the code with it's description
1114 my $authvals = C4::Koha::GetKohaAuthorisedValuesFromField($f, $sf, $row->{'frameworkcode'});
1115 $row->{$_} = $authvals->{$row->{$_}} if defined $authvals->{$row->{$_}};
1118 push @results, $row;
1121 return (\@results, $iTotalRecords);
1124 =head2 GetItemsCount
1126 $count = &GetItemsCount( $biblionumber);
1128 This function return count of item with $biblionumber
1133 my ( $biblionumber ) = @_;
1134 my $dbh = C4::Context->dbh;
1135 my $query = "SELECT count(*)
1137 WHERE biblionumber=?";
1138 my $sth = $dbh->prepare($query);
1139 $sth->execute($biblionumber);
1140 my $count = $sth->fetchrow;
1144 =head2 GetItemInfosOf
1146 GetItemInfosOf(@itemnumbers);
1150 sub GetItemInfosOf {
1151 my @itemnumbers = @_;
1156 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1158 return get_infos_of( $query, 'itemnumber' );
1161 =head2 GetItemsByBiblioitemnumber
1163 GetItemsByBiblioitemnumber($biblioitemnumber);
1165 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1166 Called by C<C4::XISBN>
1170 sub GetItemsByBiblioitemnumber {
1171 my ( $bibitem ) = @_;
1172 my $dbh = C4::Context->dbh;
1173 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1174 # Get all items attached to a biblioitem
1177 $sth->execute($bibitem) || die $sth->errstr;
1178 while ( my $data = $sth->fetchrow_hashref ) {
1179 # Foreach item, get circulation information
1180 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1181 WHERE itemnumber = ?
1182 AND issues.borrowernumber = borrowers.borrowernumber"
1184 $sth2->execute( $data->{'itemnumber'} );
1185 if ( my $data2 = $sth2->fetchrow_hashref ) {
1186 # if item is out, set the due date and who it is out too
1187 $data->{'date_due'} = $data2->{'date_due'};
1188 $data->{'cardnumber'} = $data2->{'cardnumber'};
1189 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1192 # set date_due to blank, so in the template we check itemlost, and withdrawn
1193 $data->{'date_due'} = '';
1195 # Find the last 3 people who borrowed this item.
1196 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1197 AND old_issues.borrowernumber = borrowers.borrowernumber
1198 ORDER BY returndate desc,timestamp desc LIMIT 3";
1199 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1200 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1202 while ( my $data2 = $sth2->fetchrow_hashref ) {
1203 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1204 $data->{"card$i2"} = $data2->{'cardnumber'};
1205 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1208 push(@results,$data);
1215 @results = GetItemsInfo($biblionumber);
1217 Returns information about items with the given biblionumber.
1219 C<GetItemsInfo> returns a list of references-to-hash. Each element
1220 contains a number of keys. Most of them are attributes from the
1221 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1222 Koha database. Other keys include:
1226 =item C<$data-E<gt>{branchname}>
1228 The name (not the code) of the branch to which the book belongs.
1230 =item C<$data-E<gt>{datelastseen}>
1232 This is simply C<items.datelastseen>, except that while the date is
1233 stored in YYYY-MM-DD format in the database, here it is converted to
1234 DD/MM/YYYY format. A NULL date is returned as C<//>.
1236 =item C<$data-E<gt>{datedue}>
1238 =item C<$data-E<gt>{class}>
1240 This is the concatenation of C<biblioitems.classification>, the book's
1241 Dewey code, and C<biblioitems.subclass>.
1243 =item C<$data-E<gt>{ocount}>
1245 I think this is the number of copies of the book available.
1247 =item C<$data-E<gt>{order}>
1249 If this is set, it is set to C<One Order>.
1256 my ( $biblionumber ) = @_;
1257 my $dbh = C4::Context->dbh;
1258 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1264 biblioitems.itemtype,
1267 biblioitems.publicationyear,
1268 biblioitems.publishercode,
1269 biblioitems.volumedate,
1270 biblioitems.volumedesc,
1273 items.notforloan as itemnotforloan,
1274 itemtypes.description,
1275 itemtypes.notforloan as notforloan_per_itemtype,
1278 holding.opac_info as branch_opac_info
1280 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1281 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1282 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1283 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1284 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1285 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1286 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1287 my $sth = $dbh->prepare($query);
1288 $sth->execute($biblionumber);
1293 my $isth = $dbh->prepare(
1294 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1295 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1296 WHERE itemnumber = ?"
1298 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1299 while ( my $data = $sth->fetchrow_hashref ) {
1301 $isth->execute( $data->{'itemnumber'} );
1302 if ( my $idata = $isth->fetchrow_hashref ) {
1303 $data->{borrowernumber} = $idata->{borrowernumber};
1304 $data->{cardnumber} = $idata->{cardnumber};
1305 $data->{surname} = $idata->{surname};
1306 $data->{firstname} = $idata->{firstname};
1307 $data->{lastreneweddate} = $idata->{lastreneweddate};
1308 $datedue = $idata->{'date_due'};
1309 if (C4::Context->preference("IndependentBranches")){
1310 my $userenv = C4::Context->userenv;
1311 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1312 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1316 if ( $data->{'serial'}) {
1317 $ssth->execute($data->{'itemnumber'}) ;
1318 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1321 #get branch information.....
1322 my $bsth = $dbh->prepare(
1323 "SELECT * FROM branches WHERE branchcode = ?
1326 $bsth->execute( $data->{'holdingbranch'} );
1327 if ( my $bdata = $bsth->fetchrow_hashref ) {
1328 $data->{'branchname'} = $bdata->{'branchname'};
1330 $data->{'datedue'} = $datedue;
1332 # get notforloan complete status if applicable
1333 if ( my $code = C4::Koha::GetAuthValCode( 'items.notforloan', $data->{frameworkcode} ) ) {
1334 $data->{notforloanvalue} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan} );
1335 $data->{notforloanvalueopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan}, 1 );
1338 # get restricted status and description if applicable
1339 if ( my $code = C4::Koha::GetAuthValCode( 'items.restricted', $data->{frameworkcode} ) ) {
1340 $data->{restrictedopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted}, 1 );
1341 $data->{restricted} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
1344 # my stack procedures
1345 if ( my $code = C4::Koha::GetAuthValCode( 'items.stack', $data->{frameworkcode} ) ) {
1346 $data->{stack} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{stack} );
1348 # Find the last 3 people who borrowed this item.
1349 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1350 WHERE itemnumber = ?
1351 AND old_issues.borrowernumber = borrowers.borrowernumber
1352 ORDER BY returndate DESC
1354 $sth2->execute($data->{'itemnumber'});
1356 while (my $data2 = $sth2->fetchrow_hashref()) {
1357 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1358 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1359 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1363 $results[$i] = $data;
1367 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1373 =head2 GetItemsLocationInfo
1375 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1377 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1379 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1383 =item C<$data-E<gt>{homebranch}>
1385 Branch Name of the item's homebranch
1387 =item C<$data-E<gt>{holdingbranch}>
1389 Branch Name of the item's holdingbranch
1391 =item C<$data-E<gt>{location}>
1393 Item's shelving location code
1395 =item C<$data-E<gt>{location_intranet}>
1397 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1399 =item C<$data-E<gt>{location_opac}>
1401 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1404 =item C<$data-E<gt>{itemcallnumber}>
1406 Item's itemcallnumber
1408 =item C<$data-E<gt>{cn_sort}>
1410 Item's call number normalized for sorting
1416 sub GetItemsLocationInfo {
1417 my $biblionumber = shift;
1420 my $dbh = C4::Context->dbh;
1421 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1422 location, itemcallnumber, cn_sort
1423 FROM items, branches as a, branches as b
1424 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1425 AND biblionumber = ?
1426 ORDER BY cn_sort ASC";
1427 my $sth = $dbh->prepare($query);
1428 $sth->execute($biblionumber);
1430 while ( my $data = $sth->fetchrow_hashref ) {
1431 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1432 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1433 push @results, $data;
1438 =head2 GetHostItemsInfo
1440 $hostiteminfo = GetHostItemsInfo($hostfield);
1441 Returns the iteminfo for items linked to records via a host field
1445 sub GetHostItemsInfo {
1447 my @returnitemsInfo;
1449 if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1450 C4::Context->preference('marcflavour') eq 'NORMARC'){
1451 foreach my $hostfield ( $record->field('773') ) {
1452 my $hostbiblionumber = $hostfield->subfield("0");
1453 my $linkeditemnumber = $hostfield->subfield("9");
1454 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1455 foreach my $hostitemInfo (@hostitemInfos){
1456 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1457 push (@returnitemsInfo,$hostitemInfo);
1462 } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1463 foreach my $hostfield ( $record->field('461') ) {
1464 my $hostbiblionumber = $hostfield->subfield("0");
1465 my $linkeditemnumber = $hostfield->subfield("9");
1466 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1467 foreach my $hostitemInfo (@hostitemInfos){
1468 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1469 push (@returnitemsInfo,$hostitemInfo);
1475 return @returnitemsInfo;
1479 =head2 GetLastAcquisitions
1481 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1482 'itemtypes' => ('BK','BD')}, 10);
1486 sub GetLastAcquisitions {
1487 my ($data,$max) = @_;
1489 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1491 my $number_of_branches = @{$data->{branches}};
1492 my $number_of_itemtypes = @{$data->{itemtypes}};
1495 my @where = ('WHERE 1 ');
1496 $number_of_branches and push @where
1497 , 'AND holdingbranch IN ('
1498 , join(',', ('?') x $number_of_branches )
1502 $number_of_itemtypes and push @where
1503 , "AND $itemtype IN ("
1504 , join(',', ('?') x $number_of_itemtypes )
1508 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1509 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1510 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1512 GROUP BY biblio.biblionumber
1513 ORDER BY dateaccessioned DESC LIMIT $max";
1515 my $dbh = C4::Context->dbh;
1516 my $sth = $dbh->prepare($query);
1518 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1521 while( my $row = $sth->fetchrow_hashref){
1522 push @results, {date => $row->{dateaccessioned}
1523 , biblionumber => $row->{biblionumber}
1524 , title => $row->{title}};
1530 =head2 GetItemnumbersForBiblio
1532 my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1534 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1538 sub GetItemnumbersForBiblio {
1539 my $biblionumber = shift;
1541 my $dbh = C4::Context->dbh;
1542 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1543 $sth->execute($biblionumber);
1544 while (my $result = $sth->fetchrow_hashref) {
1545 push @items, $result->{'itemnumber'};
1550 =head2 get_itemnumbers_of
1552 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1554 Given a list of biblionumbers, return the list of corresponding itemnumbers
1555 for each biblionumber.
1557 Return a reference on a hash where keys are biblionumbers and values are
1558 references on array of itemnumbers.
1562 sub get_itemnumbers_of {
1563 my @biblionumbers = @_;
1565 my $dbh = C4::Context->dbh;
1571 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1573 my $sth = $dbh->prepare($query);
1574 $sth->execute(@biblionumbers);
1578 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1579 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1582 return \%itemnumbers_of;
1585 =head2 get_hostitemnumbers_of
1587 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1589 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1591 Return a reference on a hash where key is a biblionumber and values are
1592 references on array of itemnumbers.
1597 sub get_hostitemnumbers_of {
1598 my ($biblionumber) = @_;
1599 my $marcrecord = GetMarcBiblio($biblionumber);
1600 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1602 my $marcflavor = C4::Context->preference('marcflavour');
1603 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1607 } elsif ($marcflavor eq 'UNIMARC') {
1613 foreach my $hostfield ( $marcrecord->field($tag) ) {
1614 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1615 my $linkeditemnumber = $hostfield->subfield($item_s);
1617 if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1619 @itemnumbers = @$itemnumbers;
1621 foreach my $itemnumber (@itemnumbers){
1622 if ($itemnumber eq $linkeditemnumber){
1623 push (@returnhostitemnumbers,$itemnumber);
1628 return @returnhostitemnumbers;
1632 =head2 GetItemnumberFromBarcode
1634 $result = GetItemnumberFromBarcode($barcode);
1638 sub GetItemnumberFromBarcode {
1640 my $dbh = C4::Context->dbh;
1643 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1644 $rq->execute($barcode);
1645 my ($result) = $rq->fetchrow;
1649 =head2 GetBarcodeFromItemnumber
1651 $result = GetBarcodeFromItemnumber($itemnumber);
1655 sub GetBarcodeFromItemnumber {
1656 my ($itemnumber) = @_;
1657 my $dbh = C4::Context->dbh;
1660 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1661 $rq->execute($itemnumber);
1662 my ($result) = $rq->fetchrow;
1666 =head2 GetHiddenItemnumbers
1668 my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
1670 Given a list of items it checks which should be hidden from the OPAC given
1671 the current configuration. Returns a list of itemnumbers corresponding to
1672 those that should be hidden.
1676 sub GetHiddenItemnumbers {
1680 my $yaml = C4::Context->preference('OpacHiddenItems');
1681 return () if (! $yaml =~ /\S/ );
1682 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1685 $hidingrules = YAML::Load($yaml);
1688 warn "Unable to parse OpacHiddenItems syspref : $@";
1691 my $dbh = C4::Context->dbh;
1694 foreach my $item (@items) {
1696 # We check each rule
1697 foreach my $field (keys %$hidingrules) {
1699 if (exists $item->{$field}) {
1700 $val = $item->{$field};
1703 my $query = "SELECT $field from items where itemnumber = ?";
1704 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1706 $val = '' unless defined $val;
1708 # If the results matches the values in the yaml file
1709 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1711 # We add the itemnumber to the list
1712 push @resultitems, $item->{'itemnumber'};
1714 # If at least one rule matched for an item, no need to test the others
1719 return @resultitems;
1722 =head3 get_item_authorised_values
1724 find the types and values for all authorised values assigned to this item.
1726 parameters: itemnumber
1728 returns: a hashref malling the authorised value to the value set for this itemnumber
1730 $authorised_values = {
1736 'RESTRICTED' => undef,
1739 'branches' => 'CPL',
1740 'cn_source' => undef,
1741 'itemtypes' => 'SER',
1744 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1748 sub get_item_authorised_values {
1749 my $itemnumber = shift;
1751 # assume that these entries in the authorised_value table are item level.
1752 my $query = q(SELECT distinct authorised_value, kohafield
1753 FROM marc_subfield_structure
1754 WHERE kohafield like 'item%'
1755 AND authorised_value != '' );
1757 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1758 my $iteminfo = GetItem( $itemnumber );
1759 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1761 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1762 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1763 $field =~ s/^items\.//;
1764 if ( exists $iteminfo->{ $field } ) {
1765 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1768 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1772 =head3 get_authorised_value_images
1774 find a list of icons that are appropriate for display based on the
1775 authorised values for a biblio.
1777 parameters: listref of authorised values, such as comes from
1778 get_item_authorised_values or
1779 from C4::Biblio::get_biblio_authorised_values
1781 returns: listref of hashrefs for each image. Each hashref looks like this:
1783 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1788 Notes: Currently, I put on the full path to the images on the staff
1789 side. This should either be configurable or not done at all. Since I
1790 have to deal with 'intranet' or 'opac' in
1791 get_biblio_authorised_values, perhaps I should be passing it in.
1795 sub get_authorised_value_images {
1796 my $authorised_values = shift;
1800 my $authorised_value_list = GetAuthorisedValues();
1801 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1802 foreach my $this_authorised_value ( @$authorised_value_list ) {
1803 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1804 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1805 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1806 if ( defined $this_authorised_value->{'imageurl'} ) {
1807 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1808 label => $this_authorised_value->{'lib'},
1809 category => $this_authorised_value->{'category'},
1810 value => $this_authorised_value->{'authorised_value'}, };
1815 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1820 =head1 LIMITED USE FUNCTIONS
1822 The following functions, while part of the public API,
1823 are not exported. This is generally because they are
1824 meant to be used by only one script for a specific
1825 purpose, and should not be used in any other context
1826 without careful thought.
1832 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1834 Returns MARC::Record of the item passed in parameter.
1835 This function is meant for use only in C<cataloguing/additem.pl>,
1836 where it is needed to support that script's MARC-like
1842 my ( $biblionumber, $itemnumber ) = @_;
1844 # GetMarcItem has been revised so that it does the following:
1845 # 1. Gets the item information from the items table.
1846 # 2. Converts it to a MARC field for storage in the bib record.
1848 # The previous behavior was:
1849 # 1. Get the bib record.
1850 # 2. Return the MARC tag corresponding to the item record.
1852 # The difference is that one treats the items row as authoritative,
1853 # while the other treats the MARC representation as authoritative
1854 # under certain circumstances.
1856 my $itemrecord = GetItem($itemnumber);
1858 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1859 # Also, don't emit a subfield if the underlying field is blank.
1862 return Item2Marc($itemrecord,$biblionumber);
1866 my ($itemrecord,$biblionumber)=@_;
1869 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1870 } keys %{ $itemrecord }
1872 my $itemmarc = TransformKohaToMarc($mungeditem);
1873 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1875 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1876 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1877 foreach my $field ($itemmarc->field($itemtag)){
1878 $field->add_subfields(@$unlinked_item_subfields);
1884 =head1 PRIVATE FUNCTIONS AND VARIABLES
1886 The following functions are not meant to be called
1887 directly, but are documented in order to explain
1888 the inner workings of C<C4::Items>.
1892 =head2 %derived_columns
1894 This hash keeps track of item columns that
1895 are strictly derived from other columns in
1896 the item record and are not meant to be set
1899 Each key in the hash should be the name of a
1900 column (as named by TransformMarcToKoha). Each
1901 value should be hashref whose keys are the
1902 columns on which the derived column depends. The
1903 hashref should also contain a 'BUILDER' key
1904 that is a reference to a sub that calculates
1909 my %derived_columns = (
1910 'items.cn_sort' => {
1911 'itemcallnumber' => 1,
1912 'items.cn_source' => 1,
1913 'BUILDER' => \&_calc_items_cn_sort,
1917 =head2 _set_derived_columns_for_add
1919 _set_derived_column_for_add($item);
1921 Given an item hash representing a new item to be added,
1922 calculate any derived columns. Currently the only
1923 such column is C<items.cn_sort>.
1927 sub _set_derived_columns_for_add {
1930 foreach my $column (keys %derived_columns) {
1931 my $builder = $derived_columns{$column}->{'BUILDER'};
1932 my $source_values = {};
1933 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1934 next if $source_column eq 'BUILDER';
1935 $source_values->{$source_column} = $item->{$source_column};
1937 $builder->($item, $source_values);
1941 =head2 _set_derived_columns_for_mod
1943 _set_derived_column_for_mod($item);
1945 Given an item hash representing a new item to be modified.
1946 calculate any derived columns. Currently the only
1947 such column is C<items.cn_sort>.
1949 This routine differs from C<_set_derived_columns_for_add>
1950 in that it needs to handle partial item records. In other
1951 words, the caller of C<ModItem> may have supplied only one
1952 or two columns to be changed, so this function needs to
1953 determine whether any of the columns to be changed affect
1954 any of the derived columns. Also, if a derived column
1955 depends on more than one column, but the caller is not
1956 changing all of then, this routine retrieves the unchanged
1957 values from the database in order to ensure a correct
1962 sub _set_derived_columns_for_mod {
1965 foreach my $column (keys %derived_columns) {
1966 my $builder = $derived_columns{$column}->{'BUILDER'};
1967 my $source_values = {};
1968 my %missing_sources = ();
1969 my $must_recalc = 0;
1970 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1971 next if $source_column eq 'BUILDER';
1972 if (exists $item->{$source_column}) {
1974 $source_values->{$source_column} = $item->{$source_column};
1976 $missing_sources{$source_column} = 1;
1980 foreach my $source_column (keys %missing_sources) {
1981 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1983 $builder->($item, $source_values);
1988 =head2 _do_column_fixes_for_mod
1990 _do_column_fixes_for_mod($item);
1992 Given an item hashref containing one or more
1993 columns to modify, fix up certain values.
1994 Specifically, set to 0 any passed value
1995 of C<notforloan>, C<damaged>, C<itemlost>, or
1996 C<withdrawn> that is either undefined or
1997 contains the empty string.
2001 sub _do_column_fixes_for_mod {
2004 if (exists $item->{'notforloan'} and
2005 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
2006 $item->{'notforloan'} = 0;
2008 if (exists $item->{'damaged'} and
2009 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
2010 $item->{'damaged'} = 0;
2012 if (exists $item->{'itemlost'} and
2013 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
2014 $item->{'itemlost'} = 0;
2016 if (exists $item->{'withdrawn'} and
2017 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
2018 $item->{'withdrawn'} = 0;
2020 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
2021 $item->{'permanent_location'} = $item->{'location'};
2023 if (exists $item->{'timestamp'}) {
2024 delete $item->{'timestamp'};
2028 =head2 _get_single_item_column
2030 _get_single_item_column($column, $itemnumber);
2032 Retrieves the value of a single column from an C<items>
2033 row specified by C<$itemnumber>.
2037 sub _get_single_item_column {
2039 my $itemnumber = shift;
2041 my $dbh = C4::Context->dbh;
2042 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2043 $sth->execute($itemnumber);
2044 my ($value) = $sth->fetchrow();
2048 =head2 _calc_items_cn_sort
2050 _calc_items_cn_sort($item, $source_values);
2052 Helper routine to calculate C<items.cn_sort>.
2056 sub _calc_items_cn_sort {
2058 my $source_values = shift;
2060 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2063 =head2 _set_defaults_for_add
2065 _set_defaults_for_add($item_hash);
2067 Given an item hash representing an item to be added, set
2068 correct default values for columns whose default value
2069 is not handled by the DBMS. This includes the following
2076 C<items.dateaccessioned>
2098 sub _set_defaults_for_add {
2100 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2101 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
2104 =head2 _koha_new_item
2106 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2108 Perform the actual insert into the C<items> table.
2112 sub _koha_new_item {
2113 my ( $item, $barcode ) = @_;
2114 my $dbh=C4::Context->dbh;
2117 "INSERT INTO items SET
2119 biblioitemnumber = ?,
2121 dateaccessioned = ?,
2125 replacementprice = ?,
2126 replacementpricedate = ?,
2127 datelastborrowed = ?,
2135 coded_location_qualifier = ?,
2141 permanent_location = ?,
2153 more_subfields_xml = ?,
2157 my $sth = $dbh->prepare($query);
2158 my $today = C4::Dates->today('iso');
2160 $item->{'biblionumber'},
2161 $item->{'biblioitemnumber'},
2163 $item->{'dateaccessioned'},
2164 $item->{'booksellerid'},
2165 $item->{'homebranch'},
2167 $item->{'replacementprice'},
2168 $item->{'replacementpricedate'} || $today,
2169 $item->{datelastborrowed},
2170 $item->{datelastseen} || $today,
2172 $item->{'notforloan'},
2174 $item->{'itemlost'},
2175 $item->{'withdrawn'},
2176 $item->{'itemcallnumber'},
2177 $item->{'coded_location_qualifier'},
2178 $item->{'restricted'},
2179 $item->{'itemnotes'},
2180 $item->{'holdingbranch'},
2182 $item->{'location'},
2183 $item->{'permanent_location'},
2186 $item->{'renewals'},
2187 $item->{'reserves'},
2188 $item->{'items.cn_source'},
2189 $item->{'items.cn_sort'},
2192 $item->{'materials'},
2194 $item->{'enumchron'},
2195 $item->{'more_subfields_xml'},
2196 $item->{'copynumber'},
2197 $item->{'stocknumber'},
2201 if ( defined $sth->errstr ) {
2202 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2205 $itemnumber = $dbh->{'mysql_insertid'};
2208 return ( $itemnumber, $error );
2211 =head2 MoveItemFromBiblio
2213 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2215 Moves an item from a biblio to another
2217 Returns undef if the move failed or the biblionumber of the destination record otherwise
2221 sub MoveItemFromBiblio {
2222 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2223 my $dbh = C4::Context->dbh;
2224 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2225 $sth->execute( $tobiblio );
2226 my ( $tobiblioitem ) = $sth->fetchrow();
2227 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2228 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2230 ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
2231 ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
2232 # Checking if the item we want to move is in an order
2233 require C4::Acquisition;
2234 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2236 # Replacing the biblionumber within the order if necessary
2237 $order->{'biblionumber'} = $tobiblio;
2238 C4::Acquisition::ModOrder($order);
2247 DelItemCheck($dbh, $biblionumber, $itemnumber);
2249 Exported function (core API) for deleting an item record in Koha if there no current issue.
2254 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2257 my $countanalytics=GetAnalyticsCount($itemnumber);
2260 # check that there is no issue on this item before deletion.
2261 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2262 $sth->execute($itemnumber);
2264 my $item = GetItem($itemnumber);
2265 my $onloan=$sth->fetchrow;
2268 $error = "book_on_loan"
2270 elsif ( !( C4::Context->userenv->{flags} & 1 )
2271 and C4::Context->preference("IndependentBranches")
2272 and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
2274 $error = "not_same_branch";
2277 # check it doesnt have a waiting reserve
2278 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2279 $sth->execute($itemnumber);
2280 my $reserve=$sth->fetchrow;
2282 $error = "book_reserved";
2283 } elsif ($countanalytics > 0){
2284 $error = "linked_analytics";
2286 DelItem($dbh, $biblionumber, $itemnumber);
2293 =head2 _koha_modify_item
2295 my ($itemnumber,$error) =_koha_modify_item( $item );
2297 Perform the actual update of the C<items> row. Note that this
2298 routine accepts a hashref specifying the columns to update.
2302 sub _koha_modify_item {
2304 my $dbh=C4::Context->dbh;
2307 my $query = "UPDATE items SET ";
2309 for my $key ( keys %$item ) {
2310 next if ( $key eq 'itemnumber' );
2312 push @bind, $item->{$key};
2315 $query .= " WHERE itemnumber=?";
2316 push @bind, $item->{'itemnumber'};
2317 my $sth = C4::Context->dbh->prepare($query);
2318 $sth->execute(@bind);
2319 if ( C4::Context->dbh->errstr ) {
2320 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2323 return ($item->{'itemnumber'},$error);
2326 =head2 _koha_delete_item
2328 _koha_delete_item( $dbh, $itemnum );
2330 Internal function to delete an item record from the koha tables
2334 sub _koha_delete_item {
2335 my ( $dbh, $itemnum ) = @_;
2337 # save the deleted item to deleteditems table
2338 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2339 $sth->execute($itemnum);
2340 my $data = $sth->fetchrow_hashref();
2341 my $query = "INSERT INTO deleteditems SET ";
2343 foreach my $key ( keys %$data ) {
2344 $query .= "$key = ?,";
2345 push( @bind, $data->{$key} );
2348 $sth = $dbh->prepare($query);
2349 $sth->execute(@bind);
2351 # delete from items table
2352 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2353 $sth->execute($itemnum);
2357 =head2 _marc_from_item_hash
2359 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2361 Given an item hash representing a complete item record,
2362 create a C<MARC::Record> object containing an embedded
2363 tag representing that item.
2365 The third, optional parameter C<$unlinked_item_subfields> is
2366 an arrayref of subfields (not mapped to C<items> fields per the
2367 framework) to be added to the MARC representation
2372 sub _marc_from_item_hash {
2374 my $frameworkcode = shift;
2375 my $unlinked_item_subfields;
2377 $unlinked_item_subfields = shift;
2380 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2381 # Also, don't emit a subfield if the underlying field is blank.
2382 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2383 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2384 : () } keys %{ $item } };
2386 my $item_marc = MARC::Record->new();
2387 foreach my $item_field ( keys %{$mungeditem} ) {
2388 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2389 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2390 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2391 foreach my $value (@values){
2392 if ( my $field = $item_marc->field($tag) ) {
2393 $field->add_subfields( $subfield => $value );
2395 my $add_subfields = [];
2396 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2397 $add_subfields = $unlinked_item_subfields;
2399 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2407 =head2 _repack_item_errors
2409 Add an error message hash generated by C<CheckItemPreSave>
2410 to a list of errors.
2414 sub _repack_item_errors {
2415 my $item_sequence_num = shift;
2416 my $item_ref = shift;
2417 my $error_ref = shift;
2419 my @repacked_errors = ();
2421 foreach my $error_code (sort keys %{ $error_ref }) {
2422 my $repacked_error = {};
2423 $repacked_error->{'item_sequence'} = $item_sequence_num;
2424 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2425 $repacked_error->{'error_code'} = $error_code;
2426 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2427 push @repacked_errors, $repacked_error;
2430 return @repacked_errors;
2433 =head2 _get_unlinked_item_subfields
2435 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2439 sub _get_unlinked_item_subfields {
2440 my $original_item_marc = shift;
2441 my $frameworkcode = shift;
2443 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2445 # assume that this record has only one field, and that that
2446 # field contains only the item information
2448 my @fields = $original_item_marc->fields();
2449 if ($#fields > -1) {
2450 my $field = $fields[0];
2451 my $tag = $field->tag();
2452 foreach my $subfield ($field->subfields()) {
2453 if (defined $subfield->[1] and
2454 $subfield->[1] ne '' and
2455 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2456 push @$subfields, $subfield->[0] => $subfield->[1];
2463 =head2 _get_unlinked_subfields_xml
2465 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2469 sub _get_unlinked_subfields_xml {
2470 my $unlinked_item_subfields = shift;
2473 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2474 my $marc = MARC::Record->new();
2475 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2476 # used in the framework
2477 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2478 $marc->encoding("UTF-8");
2479 $xml = $marc->as_xml("USMARC");
2485 =head2 _parse_unlinked_item_subfields_from_xml
2487 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2491 sub _parse_unlinked_item_subfields_from_xml {
2493 require C4::Charset;
2494 return unless defined $xml and $xml ne "";
2495 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2496 my $unlinked_subfields = [];
2497 my @fields = $marc->fields();
2498 if ($#fields > -1) {
2499 foreach my $subfield ($fields[0]->subfields()) {
2500 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2503 return $unlinked_subfields;
2506 =head2 GetAnalyticsCount
2508 $count= &GetAnalyticsCount($itemnumber)
2510 counts Usage of itemnumber in Analytical bibliorecords.
2514 sub GetAnalyticsCount {
2515 my ($itemnumber) = @_;
2518 ### ZOOM search here
2520 $query= "hi=".$itemnumber;
2521 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2528 $holds = &GetItemHolds($biblionumber, $itemnumber);
2532 This function return the count of holds with $biblionumber and $itemnumber
2537 my ($biblionumber, $itemnumber) = @_;
2539 my $dbh = C4::Context->dbh;
2540 my $query = "SELECT count(*)
2542 WHERE biblionumber=? AND itemnumber=?";
2543 my $sth = $dbh->prepare($query);
2544 $sth->execute($biblionumber, $itemnumber);
2545 $holds = $sth->fetchrow;
2549 # Return the list of the column names of items table
2550 sub _get_items_columns {
2551 my $dbh = C4::Context->dbh;
2552 my $sth = $dbh->column_info(undef, undef, 'items', '%');
2554 my $results = $sth->fetchall_hashref('COLUMN_NAME');
2555 return keys %$results;
2560 my $items = SearchItems($field, $value);
2562 SearchItems will search for items on a specific given field.
2563 For instance you can search all items with a specific stocknumber like this:
2565 my $items = SearchItems('stocknumber', $stocknumber);
2570 my ($field, $value) = @_;
2572 my $dbh = C4::Context->dbh;
2573 my @columns = _get_items_columns;
2575 if(0 < grep /^$field$/, @columns) {
2576 my $query = "SELECT $field FROM items WHERE $field = ?";
2577 my $sth = $dbh->prepare( $query );
2578 $sth->execute( $value );
2579 $results = $sth->fetchall_arrayref({});
2585 =head1 OTHER FUNCTIONS
2589 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2591 Find the given $subfield in the given $tag in the given
2592 MARC::Record $record. If the subfield is found, returns
2593 the (indicators, value) pair; otherwise, (undef, undef) is
2597 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2598 I suggest we export it from this module.
2603 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2606 if ( $tagfield < 10 ) {
2607 if ( $record->field($tagfield) ) {
2608 push @result, $record->field($tagfield)->data();
2613 foreach my $field ( $record->field($tagfield) ) {
2614 my @subfields = $field->subfields();
2615 foreach my $subfield (@subfields) {
2616 if ( @$subfield[0] eq $insubfield ) {
2617 push @result, @$subfield[1];
2618 $indicator = $field->indicator(1) . $field->indicator(2);
2623 return ( $indicator, @result );
2627 =head2 PrepareItemrecordDisplay
2629 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2631 Returns a hash with all the fields for Display a given item data in a template
2633 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2637 sub PrepareItemrecordDisplay {
2639 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2641 my $dbh = C4::Context->dbh;
2642 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2643 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2644 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2646 # return nothing if we don't have found an existing framework.
2647 return q{} unless $tagslib;
2650 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2654 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2656 SELECT authorised_value,lib FROM authorised_values
2659 LEFT JOIN authorised_values_branches ON ( id = av_id )
2664 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2665 $query .= qq{ ORDER BY lib};
2666 my $authorised_values_sth = $dbh->prepare( $query );
2667 foreach my $tag ( sort keys %{$tagslib} ) {
2668 my $previous_tag = '';
2671 # loop through each subfield
2673 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2674 next if ( subfield_is_koha_internal_p($subfield) );
2675 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2677 $subfield_data{tag} = $tag;
2678 $subfield_data{subfield} = $subfield;
2679 $subfield_data{countsubfield} = $cntsubf++;
2680 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2681 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2683 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2684 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2685 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2686 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2687 $subfield_data{hidden} = "display:none"
2688 if $tagslib->{$tag}->{$subfield}->{hidden};
2689 my ( $x, $defaultvalue );
2691 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2693 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2694 if ( !defined $defaultvalue ) {
2695 $defaultvalue = q||;
2697 $defaultvalue =~ s/"/"/g;
2700 # search for itemcallnumber if applicable
2701 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2702 && C4::Context->preference('itemcallnumber') ) {
2703 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2704 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2705 if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2706 $defaultvalue = $field->subfield($CNsubfield);
2709 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2711 && $defaultvalues->{'callnumber'} ) {
2712 if( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ){
2713 # if the item record exists, only use default value if the item has no callnumber
2714 $defaultvalue = $defaultvalues->{callnumber};
2715 } elsif ( !$itemrecord and $defaultvalues ) {
2716 # if the item record *doesn't* exists, always use the default value
2717 $defaultvalue = $defaultvalues->{callnumber};
2720 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2722 && $defaultvalues->{'branchcode'} ) {
2723 if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2724 $defaultvalue = $defaultvalues->{branchcode};
2727 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2729 && $defaultvalues->{'location'} ) {
2731 if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2732 # if the item record exists, only use default value if the item has no locationr
2733 $defaultvalue = $defaultvalues->{location};
2734 } elsif ( !$itemrecord and $defaultvalues ) {
2735 # if the item record *doesn't* exists, always use the default value
2736 $defaultvalue = $defaultvalues->{location};
2739 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2740 my @authorised_values;
2743 # builds list, depending on authorised value...
2745 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2746 if ( ( C4::Context->preference("IndependentBranches") )
2747 && ( C4::Context->userenv && C4::Context->userenv->{flags} % 2 != 1 ) ) {
2748 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2749 $sth->execute( C4::Context->userenv->{branch} );
2750 push @authorised_values, ""
2751 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2752 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2753 push @authorised_values, $branchcode;
2754 $authorised_lib{$branchcode} = $branchname;
2757 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2759 push @authorised_values, ""
2760 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2761 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2762 push @authorised_values, $branchcode;
2763 $authorised_lib{$branchcode} = $branchname;
2767 $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2768 if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2769 $defaultvalue = $defaultvalues->{branchcode};
2773 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2774 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2776 push @authorised_values, ""
2777 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2778 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2779 push @authorised_values, $itemtype;
2780 $authorised_lib{$itemtype} = $description;
2783 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2784 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2786 my $class_sources = GetClassSources();
2787 my $default_source = C4::Context->preference("DefaultClassificationSource");
2789 foreach my $class_source (sort keys %$class_sources) {
2790 next unless $class_sources->{$class_source}->{'used'} or
2791 ($class_source eq $default_source);
2792 push @authorised_values, $class_source;
2793 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2796 $defaultvalue = $default_source;
2798 #---- "true" authorised value
2800 $authorised_values_sth->execute(
2801 $tagslib->{$tag}->{$subfield}->{authorised_value},
2802 $branch_limit ? $branch_limit : ()
2804 push @authorised_values, ""
2805 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2806 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2807 push @authorised_values, $value;
2808 $authorised_lib{$value} = $lib;
2811 $subfield_data{marc_value} = CGI::scrolling_list(
2812 -name => 'field_value',
2813 -values => \@authorised_values,
2814 -default => "$defaultvalue",
2815 -labels => \%authorised_lib,
2820 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2822 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2824 my $extended_param = plugin_parameters( $dbh, undef, $tagslib, $subfield_data{id}, undef );
2825 my ( $function_name, $javascript ) = plugin_javascript( $dbh, undef, $tagslib, $subfield_data{id}, undef );
2826 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2827 $subfield_data{marc_value} = qq[<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255"
2828 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2829 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2830 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2833 warn "Plugin Failed: $plugin";
2834 $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
2837 elsif ( $tag eq '' ) { # it's an hidden field
2838 $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" />);
2840 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2841 $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" />);
2843 elsif ( length($defaultvalue) > 100
2844 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2845 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2846 or (C4::Context->preference("marcflavour") eq "MARC21" and
2847 500 <= $tag && $tag < 600 )
2849 # oversize field (textarea)
2850 $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");
2852 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2854 push( @loop_data, \%subfield_data );
2859 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2860 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2863 'itemtagfield' => $itemtagfield,
2864 'itemtagsubfield' => $itemtagsubfield,
2865 'itemnumber' => $itemnumber,
2866 'iteminformation' => \@loop_data