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/;
29 use C4::Search qw/SimpleSearch/;
33 use List::MoreUtils qw/any/;
34 use Data::Dumper; # used as part of logging item record changes, not just for
35 # debugging; so please don't remove this
37 use vars qw($VERSION @ISA @EXPORT);
43 @ISA = qw( Exporter );
66 GetItemsByBiblioitemnumber
71 get_hostitemnumbers_of
72 GetItemnumberFromBarcode
73 GetBarcodeFromItemnumber
85 PrepareItemrecordDisplay
92 C4::Items - item management functions
96 This module contains an API for manipulating item
97 records in Koha, and is used by cataloguing, circulation,
98 acquisitions, and serials management.
100 A Koha item record is stored in two places: the
101 items table and embedded in a MARC tag in the XML
102 version of the associated bib record in C<biblioitems.marcxml>.
103 This is done to allow the item information to be readily
104 indexed (e.g., by Zebra), but means that each item
105 modification transaction must keep the items table
106 and the MARC XML in sync at all times.
108 Consequently, all code that creates, modifies, or deletes
109 item records B<must> use an appropriate function from
110 C<C4::Items>. If no existing function is suitable, it is
111 better to add one to C<C4::Items> than to use add
112 one-off SQL statements to add or modify items.
114 The items table will be considered authoritative. In other
115 words, if there is ever a discrepancy between the items
116 table and the MARC XML, the items table should be considered
119 =head1 HISTORICAL NOTE
121 Most of the functions in C<C4::Items> were originally in
122 the C<C4::Biblio> module.
124 =head1 CORE EXPORTED FUNCTIONS
126 The following functions are meant for use by users
133 $item = GetItem($itemnumber,$barcode,$serial);
135 Return item information, for a given itemnumber or barcode.
136 The return value is a hashref mapping item column
137 names to values. If C<$serial> is true, include serial publication data.
142 my ($itemnumber,$barcode, $serial) = @_;
143 my $dbh = C4::Context->dbh;
146 my $sth = $dbh->prepare("
148 WHERE itemnumber = ?");
149 $sth->execute($itemnumber);
150 $data = $sth->fetchrow_hashref;
152 my $sth = $dbh->prepare("
156 $sth->execute($barcode);
157 $data = $sth->fetchrow_hashref;
160 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
161 $ssth->execute($data->{'itemnumber'}) ;
162 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
164 #if we don't have an items.itype, use biblioitems.itemtype.
165 if( ! $data->{'itype'} ) {
166 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
167 $sth->execute($data->{'biblionumber'});
168 ($data->{'itype'}) = $sth->fetchrow_array;
175 CartToShelf($itemnumber);
177 Set the current shelving location of the item record
178 to its stored permanent shelving location. This is
179 primarily used to indicate when an item whose current
180 location is a special processing ('PROC') or shelving cart
181 ('CART') location is back in the stacks.
186 my ( $itemnumber ) = @_;
188 unless ( $itemnumber ) {
189 croak "FAILED CartToShelf() - no itemnumber supplied";
192 my $item = GetItem($itemnumber);
193 $item->{location} = $item->{permanent_location};
194 ModItem($item, undef, $itemnumber);
197 =head2 AddItemFromMarc
199 my ($biblionumber, $biblioitemnumber, $itemnumber)
200 = AddItemFromMarc($source_item_marc, $biblionumber);
202 Given a MARC::Record object containing an embedded item
203 record and a biblionumber, create a new item record.
207 sub AddItemFromMarc {
208 my ( $source_item_marc, $biblionumber ) = @_;
209 my $dbh = C4::Context->dbh;
211 # parse item hash from MARC
212 my $frameworkcode = GetFrameworkCode( $biblionumber );
213 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
215 my $localitemmarc=MARC::Record->new;
216 $localitemmarc->append_fields($source_item_marc->field($itemtag));
217 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
218 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
219 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
224 my ($biblionumber, $biblioitemnumber, $itemnumber)
225 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
227 Given a hash containing item column names as keys,
228 create a new Koha item record.
230 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
231 do not need to be supplied for general use; they exist
232 simply to allow them to be picked up from AddItemFromMarc.
234 The final optional parameter, C<$unlinked_item_subfields>, contains
235 an arrayref containing subfields present in the original MARC
236 representation of the item (e.g., from the item editor) that are
237 not mapped to C<items> columns directly but should instead
238 be stored in C<items.more_subfields_xml> and included in
239 the biblio items tag for display and indexing.
245 my $biblionumber = shift;
247 my $dbh = @_ ? shift : C4::Context->dbh;
248 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
249 my $unlinked_item_subfields;
251 $unlinked_item_subfields = shift
254 # needs old biblionumber and biblioitemnumber
255 $item->{'biblionumber'} = $biblionumber;
256 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
257 $sth->execute( $item->{'biblionumber'} );
258 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
260 _set_defaults_for_add($item);
261 _set_derived_columns_for_add($item);
262 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
263 # FIXME - checks here
264 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
265 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
266 $itype_sth->execute( $item->{'biblionumber'} );
267 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
270 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
271 $item->{'itemnumber'} = $itemnumber;
273 ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
275 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
277 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
280 =head2 AddItemBatchFromMarc
282 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
283 $biblionumber, $biblioitemnumber, $frameworkcode);
285 Efficiently create item records from a MARC biblio record with
286 embedded item fields. This routine is suitable for batch jobs.
288 This API assumes that the bib record has already been
289 saved to the C<biblio> and C<biblioitems> tables. It does
290 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
291 are populated, but it will do so via a call to ModBibiloMarc.
293 The goal of this API is to have a similar effect to using AddBiblio
294 and AddItems in succession, but without inefficient repeated
295 parsing of the MARC XML bib record.
297 This function returns an arrayref of new itemsnumbers and an arrayref of item
298 errors encountered during the processing. Each entry in the errors
299 list is a hashref containing the following keys:
305 Sequence number of original item tag in the MARC record.
309 Item barcode, provide to assist in the construction of
310 useful error messages.
312 =item error_condition
314 Code representing the error condition. Can be 'duplicate_barcode',
315 'invalid_homebranch', or 'invalid_holdingbranch'.
317 =item error_information
319 Additional information appropriate to the error condition.
325 sub AddItemBatchFromMarc {
326 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
328 my @itemnumbers = ();
330 my $dbh = C4::Context->dbh;
332 # loop through the item tags and start creating items
333 my @bad_item_fields = ();
334 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
335 my $item_sequence_num = 0;
336 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
337 $item_sequence_num++;
338 # we take the item field and stick it into a new
339 # MARC record -- this is required so far because (FIXME)
340 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
341 # and there is no TransformMarcFieldToKoha
342 my $temp_item_marc = MARC::Record->new();
343 $temp_item_marc->append_fields($item_field);
345 # add biblionumber and biblioitemnumber
346 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
347 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
348 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
349 $item->{'biblionumber'} = $biblionumber;
350 $item->{'biblioitemnumber'} = $biblioitemnumber;
352 # check for duplicate barcode
353 my %item_errors = CheckItemPreSave($item);
355 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
356 push @bad_item_fields, $item_field;
360 _set_defaults_for_add($item);
361 _set_derived_columns_for_add($item);
362 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
363 warn $error if $error;
364 push @itemnumbers, $itemnumber; # FIXME not checking error
365 $item->{'itemnumber'} = $itemnumber;
367 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
369 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
370 $item_field->replace_with($new_item_marc->field($itemtag));
373 # remove any MARC item fields for rejected items
374 foreach my $item_field (@bad_item_fields) {
375 $record->delete_field($item_field);
378 # update the MARC biblio
379 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
381 return (\@itemnumbers, \@errors);
384 =head2 ModItemFromMarc
386 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
388 This function updates an item record based on a supplied
389 C<MARC::Record> object containing an embedded item field.
390 This API is meant for the use of C<additem.pl>; for
391 other purposes, C<ModItem> should be used.
393 This function uses the hash %default_values_for_mod_from_marc,
394 which contains default values for item fields to
395 apply when modifying an item. This is needed beccause
396 if an item field's value is cleared, TransformMarcToKoha
397 does not include the column in the
398 hash that's passed to ModItem, which without
399 use of this hash makes it impossible to clear
400 an item field's value. See bug 2466.
402 Note that only columns that can be directly
403 changed from the cataloging and serials
404 item editors are included in this hash.
410 my %default_values_for_mod_from_marc = (
412 booksellerid => undef,
414 'items.cn_source' => undef,
417 # dateaccessioned => undef,
419 holdingbranch => undef,
421 itemcallnumber => undef,
426 permanent_location => undef,
431 replacementprice => undef,
432 replacementpricedate => undef,
435 stocknumber => undef,
440 sub ModItemFromMarc {
441 my $item_marc = shift;
442 my $biblionumber = shift;
443 my $itemnumber = shift;
445 my $dbh = C4::Context->dbh;
446 my $frameworkcode = GetFrameworkCode($biblionumber);
447 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
449 my $localitemmarc = MARC::Record->new;
450 $localitemmarc->append_fields( $item_marc->field($itemtag) );
451 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
452 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
453 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
455 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
457 ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
463 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
465 Change one or more columns in an item record and update
466 the MARC representation of the item.
468 The first argument is a hashref mapping from item column
469 names to the new values. The second and third arguments
470 are the biblionumber and itemnumber, respectively.
472 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
473 an arrayref containing subfields present in the original MARC
474 representation of the item (e.g., from the item editor) that are
475 not mapped to C<items> columns directly but should instead
476 be stored in C<items.more_subfields_xml> and included in
477 the biblio items tag for display and indexing.
479 If one of the changed columns is used to calculate
480 the derived value of a column such as C<items.cn_sort>,
481 this routine will perform the necessary calculation
488 my $biblionumber = shift;
489 my $itemnumber = shift;
491 # if $biblionumber is undefined, get it from the current item
492 unless (defined $biblionumber) {
493 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
496 my $dbh = @_ ? shift : C4::Context->dbh;
497 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
499 my $unlinked_item_subfields;
501 $unlinked_item_subfields = shift;
502 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
505 $item->{'itemnumber'} = $itemnumber or return undef;
507 $item->{onloan} = undef if $item->{itemlost};
509 _set_derived_columns_for_mod($item);
510 _do_column_fixes_for_mod($item);
513 # attempt to change itemnumber
514 # attempt to change biblionumber (if we want
515 # an API to relink an item to a different bib,
516 # it should be a separate function)
519 _koha_modify_item($item);
521 # request that bib be reindexed so that searching on current
522 # item status is possible
523 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
525 logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
528 =head2 ModItemTransfer
530 ModItemTransfer($itenumber, $frombranch, $tobranch);
532 Marks an item as being transferred from one branch
537 sub ModItemTransfer {
538 my ( $itemnumber, $frombranch, $tobranch ) = @_;
540 my $dbh = C4::Context->dbh;
542 #new entry in branchtransfers....
543 my $sth = $dbh->prepare(
544 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
545 VALUES (?, ?, NOW(), ?)");
546 $sth->execute($itemnumber, $frombranch, $tobranch);
548 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
549 ModDateLastSeen($itemnumber);
553 =head2 ModDateLastSeen
555 ModDateLastSeen($itemnum);
557 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
558 C<$itemnum> is the item number
562 sub ModDateLastSeen {
563 my ($itemnumber) = @_;
565 my $today = C4::Dates->new();
566 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
571 DelItem($dbh, $biblionumber, $itemnumber);
573 Exported function (core API) for deleting an item record in Koha.
578 my ( $dbh, $biblionumber, $itemnumber ) = @_;
580 # FIXME check the item has no current issues
582 _koha_delete_item( $dbh, $itemnumber );
584 # get the MARC record
585 my $record = GetMarcBiblio($biblionumber);
586 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
589 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
590 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
591 # 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).
593 #search item field code
594 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
597 =head2 CheckItemPreSave
599 my $item_ref = TransformMarcToKoha($marc, 'items');
601 my %errors = CheckItemPreSave($item_ref);
602 if (exists $errors{'duplicate_barcode'}) {
603 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
604 } elsif (exists $errors{'invalid_homebranch'}) {
605 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
606 } elsif (exists $errors{'invalid_holdingbranch'}) {
607 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
612 Given a hashref containing item fields, determine if it can be
613 inserted or updated in the database. Specifically, checks for
614 database integrity issues, and returns a hash containing any
615 of the following keys, if applicable.
619 =item duplicate_barcode
621 Barcode, if it duplicates one already found in the database.
623 =item invalid_homebranch
625 Home branch, if not defined in branches table.
627 =item invalid_holdingbranch
629 Holding branch, if not defined in branches table.
633 This function does NOT implement any policy-related checks,
634 e.g., whether current operator is allowed to save an
635 item that has a given branch code.
639 sub CheckItemPreSave {
640 my $item_ref = shift;
645 # check for duplicate barcode
646 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
647 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
648 if ($existing_itemnumber) {
649 if (!exists $item_ref->{'itemnumber'} # new item
650 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
651 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
656 # check for valid home branch
657 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
658 my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
659 unless (defined $branch_name) {
660 # relies on fact that branches.branchname is a non-NULL column,
661 # so GetBranchName returns undef only if branch does not exist
662 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
666 # check for valid holding branch
667 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
668 my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
669 unless (defined $branch_name) {
670 # relies on fact that branches.branchname is a non-NULL column,
671 # so GetBranchName returns undef only if branch does not exist
672 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
680 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
682 The following functions provide various ways of
683 getting an item record, a set of item records, or
684 lists of authorized values for certain item fields.
686 Some of the functions in this group are candidates
687 for refactoring -- for example, some of the code
688 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
689 has copy-and-paste work.
695 $itemstatushash = GetItemStatus($fwkcode);
697 Returns a list of valid values for the
698 C<items.notforloan> field.
700 NOTE: does B<not> return an individual item's
703 Can be MARC dependant.
705 But basically could be can be loan or not
706 Create a status selector with the following code
708 =head3 in PERL SCRIPT
710 my $itemstatushash = getitemstatus;
712 foreach my $thisstatus (keys %$itemstatushash) {
713 my %row =(value => $thisstatus,
714 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
716 push @itemstatusloop, \%row;
718 $template->param(statusloop=>\@itemstatusloop);
722 <select name="statusloop">
723 <option value="">Default</option>
724 <!-- TMPL_LOOP name="statusloop" -->
725 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
733 # returns a reference to a hash of references to status...
736 my $dbh = C4::Context->dbh;
738 $fwk = '' unless ($fwk);
739 my ( $tag, $subfield ) =
740 GetMarcFromKohaField( "items.notforloan", $fwk );
741 if ( $tag and $subfield ) {
744 "SELECT authorised_value
745 FROM marc_subfield_structure
751 $sth->execute( $tag, $subfield, $fwk );
752 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
755 "SELECT authorised_value,lib
756 FROM authorised_values
761 $authvalsth->execute($authorisedvaluecat);
762 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
763 $itemstatus{$authorisedvalue} = $lib;
777 $itemstatus{"1"} = "Not For Loan";
781 =head2 GetItemLocation
783 $itemlochash = GetItemLocation($fwk);
785 Returns a list of valid values for the
786 C<items.location> field.
788 NOTE: does B<not> return an individual item's
791 where fwk stands for an optional framework code.
792 Create a location selector with the following code
794 =head3 in PERL SCRIPT
796 my $itemlochash = getitemlocation;
798 foreach my $thisloc (keys %$itemlochash) {
799 my $selected = 1 if $thisbranch eq $branch;
800 my %row =(locval => $thisloc,
801 selected => $selected,
802 locname => $itemlochash->{$thisloc},
804 push @itemlocloop, \%row;
806 $template->param(itemlocationloop => \@itemlocloop);
810 <select name="location">
811 <option value="">Default</option>
812 <!-- TMPL_LOOP name="itemlocationloop" -->
813 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
819 sub GetItemLocation {
821 # returns a reference to a hash of references to location...
824 my $dbh = C4::Context->dbh;
826 $fwk = '' unless ($fwk);
827 my ( $tag, $subfield ) =
828 GetMarcFromKohaField( "items.location", $fwk );
829 if ( $tag and $subfield ) {
832 "SELECT authorised_value
833 FROM marc_subfield_structure
838 $sth->execute( $tag, $subfield, $fwk );
839 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
842 "SELECT authorised_value,lib
843 FROM authorised_values
847 $authvalsth->execute($authorisedvaluecat);
848 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
849 $itemlocation{$authorisedvalue} = $lib;
851 return \%itemlocation;
863 $itemlocation{"1"} = "Not For Loan";
864 return \%itemlocation;
869 $items = GetLostItems( $where, $orderby );
871 This function gets a list of lost items.
877 C<$where> is a hashref. it containts a field of the items table as key
878 and the value to match as value. For example:
880 { barcode => 'abc123',
881 homebranch => 'CPL', }
883 C<$orderby> is a field of the items table by which the resultset
888 C<$items> is a reference to an array full of hashrefs with columns
889 from the "items" table as keys.
891 =item usage in the perl script:
893 my $where = { barcode => '0001548' };
894 my $items = GetLostItems( $where, "homebranch" );
895 $template->param( itemsloop => $items );
902 # Getting input args.
905 my $dbh = C4::Context->dbh;
910 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
911 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
912 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
914 authorised_values.category = 'LOST'
915 AND itemlost IS NOT NULL
918 my @query_parameters;
919 foreach my $key (keys %$where) {
920 $query .= " AND $key LIKE ?";
921 push @query_parameters, "%$where->{$key}%";
923 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
925 if ( defined $orderby && grep($orderby, @ordervalues)) {
926 $query .= ' ORDER BY '.$orderby;
929 my $sth = $dbh->prepare($query);
930 $sth->execute( @query_parameters );
932 while ( my $row = $sth->fetchrow_hashref ){
938 =head2 GetItemsForInventory
940 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
941 $location, $itemtype $datelastseen, $branch,
942 $offset, $size, $statushash);
944 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
946 The sub returns a reference to a list of hashes, each containing
947 itemnumber, author, title, barcode, item callnumber, and date last
948 seen. It is ordered by callnumber then title.
950 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
951 the datelastseen can be used to specify that you want to see items not seen since a past date only.
952 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
953 $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.
957 sub GetItemsForInventory {
958 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
959 my $dbh = C4::Context->dbh;
960 my ( @bind_params, @where_strings );
962 my $query = <<'END_SQL';
963 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
965 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
966 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
969 for my $authvfield (keys %$statushash){
970 if ( scalar @{$statushash->{$authvfield}} > 0 ){
971 my $joinedvals = join ',', @{$statushash->{$authvfield}};
972 push @where_strings, "$authvfield in (" . $joinedvals . ")";
978 push @where_strings, 'itemcallnumber >= ?';
979 push @bind_params, $minlocation;
983 push @where_strings, 'itemcallnumber <= ?';
984 push @bind_params, $maxlocation;
988 $datelastseen = format_date_in_iso($datelastseen);
989 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
990 push @bind_params, $datelastseen;
994 push @where_strings, 'items.location = ?';
995 push @bind_params, $location;
999 if($branch eq "homebranch"){
1000 push @where_strings, 'items.homebranch = ?';
1002 push @where_strings, 'items.holdingbranch = ?';
1004 push @bind_params, $branchcode;
1008 push @where_strings, 'biblioitems.itemtype = ?';
1009 push @bind_params, $itemtype;
1012 if ( $ignoreissued) {
1013 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1014 push @where_strings, 'issues.date_due IS NULL';
1017 if ( @where_strings ) {
1019 $query .= join ' AND ', @where_strings;
1021 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1022 my $sth = $dbh->prepare($query);
1023 $sth->execute( @bind_params );
1027 while ( my $row = $sth->fetchrow_hashref ) {
1028 $offset-- if ($offset);
1029 $row->{datelastseen}=format_date($row->{datelastseen});
1030 if ( ( !$offset ) && $size ) {
1031 push @results, $row;
1038 =head2 GetItemsCount
1040 $count = &GetItemsCount( $biblionumber);
1042 This function return count of item with $biblionumber
1047 my ( $biblionumber ) = @_;
1048 my $dbh = C4::Context->dbh;
1049 my $query = "SELECT count(*)
1051 WHERE biblionumber=?";
1052 my $sth = $dbh->prepare($query);
1053 $sth->execute($biblionumber);
1054 my $count = $sth->fetchrow;
1058 =head2 GetItemInfosOf
1060 GetItemInfosOf(@itemnumbers);
1064 sub GetItemInfosOf {
1065 my @itemnumbers = @_;
1070 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1072 return get_infos_of( $query, 'itemnumber' );
1075 =head2 GetItemsByBiblioitemnumber
1077 GetItemsByBiblioitemnumber($biblioitemnumber);
1079 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1080 Called by C<C4::XISBN>
1084 sub GetItemsByBiblioitemnumber {
1085 my ( $bibitem ) = @_;
1086 my $dbh = C4::Context->dbh;
1087 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1088 # Get all items attached to a biblioitem
1091 $sth->execute($bibitem) || die $sth->errstr;
1092 while ( my $data = $sth->fetchrow_hashref ) {
1093 # Foreach item, get circulation information
1094 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1095 WHERE itemnumber = ?
1096 AND issues.borrowernumber = borrowers.borrowernumber"
1098 $sth2->execute( $data->{'itemnumber'} );
1099 if ( my $data2 = $sth2->fetchrow_hashref ) {
1100 # if item is out, set the due date and who it is out too
1101 $data->{'date_due'} = $data2->{'date_due'};
1102 $data->{'cardnumber'} = $data2->{'cardnumber'};
1103 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1106 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1107 $data->{'date_due'} = '';
1109 # Find the last 3 people who borrowed this item.
1110 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1111 AND old_issues.borrowernumber = borrowers.borrowernumber
1112 ORDER BY returndate desc,timestamp desc LIMIT 3";
1113 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1114 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1116 while ( my $data2 = $sth2->fetchrow_hashref ) {
1117 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1118 $data->{"card$i2"} = $data2->{'cardnumber'};
1119 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1122 push(@results,$data);
1129 @results = GetItemsInfo($biblionumber);
1131 Returns information about items with the given biblionumber.
1133 C<GetItemsInfo> returns a list of references-to-hash. Each element
1134 contains a number of keys. Most of them are attributes from the
1135 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1136 Koha database. Other keys include:
1140 =item C<$data-E<gt>{branchname}>
1142 The name (not the code) of the branch to which the book belongs.
1144 =item C<$data-E<gt>{datelastseen}>
1146 This is simply C<items.datelastseen>, except that while the date is
1147 stored in YYYY-MM-DD format in the database, here it is converted to
1148 DD/MM/YYYY format. A NULL date is returned as C<//>.
1150 =item C<$data-E<gt>{datedue}>
1152 =item C<$data-E<gt>{class}>
1154 This is the concatenation of C<biblioitems.classification>, the book's
1155 Dewey code, and C<biblioitems.subclass>.
1157 =item C<$data-E<gt>{ocount}>
1159 I think this is the number of copies of the book available.
1161 =item C<$data-E<gt>{order}>
1163 If this is set, it is set to C<One Order>.
1170 my ( $biblionumber ) = @_;
1171 my $dbh = C4::Context->dbh;
1172 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1178 biblioitems.itemtype,
1181 biblioitems.publicationyear,
1182 biblioitems.publishercode,
1183 biblioitems.volumedate,
1184 biblioitems.volumedesc,
1187 items.notforloan as itemnotforloan,
1188 itemtypes.description,
1189 itemtypes.notforloan as notforloan_per_itemtype,
1192 holding.opac_info as branch_opac_info
1194 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1195 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1196 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1197 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1198 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1199 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1200 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname,items.dateaccessioned desc" ;
1201 my $sth = $dbh->prepare($query);
1202 $sth->execute($biblionumber);
1207 my $isth = $dbh->prepare(
1208 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1209 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1210 WHERE itemnumber = ?"
1212 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1213 while ( my $data = $sth->fetchrow_hashref ) {
1215 $isth->execute( $data->{'itemnumber'} );
1216 if ( my $idata = $isth->fetchrow_hashref ) {
1217 $data->{borrowernumber} = $idata->{borrowernumber};
1218 $data->{cardnumber} = $idata->{cardnumber};
1219 $data->{surname} = $idata->{surname};
1220 $data->{firstname} = $idata->{firstname};
1221 $data->{lastreneweddate} = $idata->{lastreneweddate};
1222 $datedue = $idata->{'date_due'};
1223 if (C4::Context->preference("IndependantBranches")){
1224 my $userenv = C4::Context->userenv;
1225 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1226 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1230 if ( $data->{'serial'}) {
1231 $ssth->execute($data->{'itemnumber'}) ;
1232 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1235 #get branch information.....
1236 my $bsth = $dbh->prepare(
1237 "SELECT * FROM branches WHERE branchcode = ?
1240 $bsth->execute( $data->{'holdingbranch'} );
1241 if ( my $bdata = $bsth->fetchrow_hashref ) {
1242 $data->{'branchname'} = $bdata->{'branchname'};
1244 $data->{'datedue'} = $datedue;
1246 # get notforloan complete status if applicable
1247 my $sthnflstatus = $dbh->prepare(
1248 'SELECT authorised_value
1249 FROM marc_subfield_structure
1250 WHERE kohafield="items.notforloan"
1254 $sthnflstatus->execute;
1255 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1256 if ($authorised_valuecode) {
1257 $sthnflstatus = $dbh->prepare(
1258 "SELECT lib FROM authorised_values
1260 AND authorised_value=?"
1262 $sthnflstatus->execute( $authorised_valuecode,
1263 $data->{itemnotforloan} );
1264 my ($lib) = $sthnflstatus->fetchrow;
1265 $data->{notforloanvalue} = $lib;
1268 # get restricted status and description if applicable
1269 my $restrictedstatus = $dbh->prepare(
1270 'SELECT authorised_value
1271 FROM marc_subfield_structure
1272 WHERE kohafield="items.restricted"
1276 $restrictedstatus->execute;
1277 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1278 if ($authorised_valuecode) {
1279 $restrictedstatus = $dbh->prepare(
1280 "SELECT lib,lib_opac FROM authorised_values
1282 AND authorised_value=?"
1284 $restrictedstatus->execute( $authorised_valuecode,
1285 $data->{restricted} );
1287 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1288 $data->{restricted} = $rstdata->{'lib'};
1289 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1293 # my stack procedures
1294 my $stackstatus = $dbh->prepare(
1295 'SELECT authorised_value
1296 FROM marc_subfield_structure
1297 WHERE kohafield="items.stack"
1300 $stackstatus->execute;
1302 ($authorised_valuecode) = $stackstatus->fetchrow;
1303 if ($authorised_valuecode) {
1304 $stackstatus = $dbh->prepare(
1306 FROM authorised_values
1308 AND authorised_value=?
1311 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1312 my ($lib) = $stackstatus->fetchrow;
1313 $data->{stack} = $lib;
1315 # Find the last 3 people who borrowed this item.
1316 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1317 WHERE itemnumber = ?
1318 AND old_issues.borrowernumber = borrowers.borrowernumber
1319 ORDER BY returndate DESC
1321 $sth2->execute($data->{'itemnumber'});
1323 while (my $data2 = $sth2->fetchrow_hashref()) {
1324 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1325 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1326 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1330 $results[$i] = $data;
1334 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1340 =head2 GetItemsLocationInfo
1342 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1344 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1346 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1350 =item C<$data-E<gt>{homebranch}>
1352 Branch Name of the item's homebranch
1354 =item C<$data-E<gt>{holdingbranch}>
1356 Branch Name of the item's holdingbranch
1358 =item C<$data-E<gt>{location}>
1360 Item's shelving location code
1362 =item C<$data-E<gt>{location_intranet}>
1364 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1366 =item C<$data-E<gt>{location_opac}>
1368 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1371 =item C<$data-E<gt>{itemcallnumber}>
1373 Item's itemcallnumber
1375 =item C<$data-E<gt>{cn_sort}>
1377 Item's call number normalized for sorting
1383 sub GetItemsLocationInfo {
1384 my $biblionumber = shift;
1387 my $dbh = C4::Context->dbh;
1388 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1389 location, itemcallnumber, cn_sort
1390 FROM items, branches as a, branches as b
1391 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1392 AND biblionumber = ?
1393 ORDER BY cn_sort ASC";
1394 my $sth = $dbh->prepare($query);
1395 $sth->execute($biblionumber);
1397 while ( my $data = $sth->fetchrow_hashref ) {
1398 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1399 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1400 push @results, $data;
1405 =head2 GetHostItemsInfo
1407 $hostiteminfo = GetHostItemsInfo($hostfield);
1408 Returns the iteminfo for items linked to records via a host field
1412 sub GetHostItemsInfo {
1414 my @returnitemsInfo;
1416 if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1417 C4::Context->preference('marcflavour') eq 'NORMARC'){
1418 foreach my $hostfield ( $record->field('773') ) {
1419 my $hostbiblionumber = $hostfield->subfield("0");
1420 my $linkeditemnumber = $hostfield->subfield("9");
1421 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1422 foreach my $hostitemInfo (@hostitemInfos){
1423 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1424 push (@returnitemsInfo,$hostitemInfo);
1429 } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1430 foreach my $hostfield ( $record->field('461') ) {
1431 my $hostbiblionumber = $hostfield->subfield("0");
1432 my $linkeditemnumber = $hostfield->subfield("9");
1433 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1434 foreach my $hostitemInfo (@hostitemInfos){
1435 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1436 push (@returnitemsInfo,$hostitemInfo);
1442 return @returnitemsInfo;
1446 =head2 GetLastAcquisitions
1448 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1449 'itemtypes' => ('BK','BD')}, 10);
1453 sub GetLastAcquisitions {
1454 my ($data,$max) = @_;
1456 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1458 my $number_of_branches = @{$data->{branches}};
1459 my $number_of_itemtypes = @{$data->{itemtypes}};
1462 my @where = ('WHERE 1 ');
1463 $number_of_branches and push @where
1464 , 'AND holdingbranch IN ('
1465 , join(',', ('?') x $number_of_branches )
1469 $number_of_itemtypes and push @where
1470 , "AND $itemtype IN ("
1471 , join(',', ('?') x $number_of_itemtypes )
1475 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1476 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1477 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1479 GROUP BY biblio.biblionumber
1480 ORDER BY dateaccessioned DESC LIMIT $max";
1482 my $dbh = C4::Context->dbh;
1483 my $sth = $dbh->prepare($query);
1485 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1488 while( my $row = $sth->fetchrow_hashref){
1489 push @results, {date => $row->{dateaccessioned}
1490 , biblionumber => $row->{biblionumber}
1491 , title => $row->{title}};
1497 =head2 get_itemnumbers_of
1499 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1501 Given a list of biblionumbers, return the list of corresponding itemnumbers
1502 for each biblionumber.
1504 Return a reference on a hash where keys are biblionumbers and values are
1505 references on array of itemnumbers.
1509 sub get_itemnumbers_of {
1510 my @biblionumbers = @_;
1512 my $dbh = C4::Context->dbh;
1518 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1520 my $sth = $dbh->prepare($query);
1521 $sth->execute(@biblionumbers);
1525 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1526 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1529 return \%itemnumbers_of;
1532 =head2 get_hostitemnumbers_of
1534 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1536 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1538 Return a reference on a hash where key is a biblionumber and values are
1539 references on array of itemnumbers.
1544 sub get_hostitemnumbers_of {
1545 my ($biblionumber) = @_;
1546 my $marcrecord = GetMarcBiblio($biblionumber);
1547 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1549 my $marcflavor = C4::Context->preference('marcflavour');
1550 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1554 } elsif ($marcflavor eq 'UNIMARC') {
1560 foreach my $hostfield ( $marcrecord->field($tag) ) {
1561 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1562 my $linkeditemnumber = $hostfield->subfield($item_s);
1564 if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1566 @itemnumbers = @$itemnumbers;
1568 foreach my $itemnumber (@itemnumbers){
1569 if ($itemnumber eq $linkeditemnumber){
1570 push (@returnhostitemnumbers,$itemnumber);
1575 return @returnhostitemnumbers;
1579 =head2 GetItemnumberFromBarcode
1581 $result = GetItemnumberFromBarcode($barcode);
1585 sub GetItemnumberFromBarcode {
1587 my $dbh = C4::Context->dbh;
1590 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1591 $rq->execute($barcode);
1592 my ($result) = $rq->fetchrow;
1596 =head2 GetBarcodeFromItemnumber
1598 $result = GetBarcodeFromItemnumber($itemnumber);
1602 sub GetBarcodeFromItemnumber {
1603 my ($itemnumber) = @_;
1604 my $dbh = C4::Context->dbh;
1607 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1608 $rq->execute($itemnumber);
1609 my ($result) = $rq->fetchrow;
1613 =head2 GetHiddenItemnumbers
1617 $result = GetHiddenItemnumbers(@items);
1623 sub GetHiddenItemnumbers {
1627 my $yaml = C4::Context->preference('OpacHiddenItems');
1628 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1631 $hidingrules = YAML::Load($yaml);
1634 warn "Unable to parse OpacHiddenItems syspref : $@";
1637 my $dbh = C4::Context->dbh;
1640 foreach my $item (@items) {
1642 # We check each rule
1643 foreach my $field (keys %$hidingrules) {
1645 if (exists $item->{$field}) {
1646 $val = $item->{$field};
1649 my $query = "SELECT $field from items where itemnumber = ?";
1650 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1652 $val = '' unless defined $val;
1654 # If the results matches the values in the yaml file
1655 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1657 # We add the itemnumber to the list
1658 push @resultitems, $item->{'itemnumber'};
1660 # If at least one rule matched for an item, no need to test the others
1665 return @resultitems;
1668 =head3 get_item_authorised_values
1670 find the types and values for all authorised values assigned to this item.
1672 parameters: itemnumber
1674 returns: a hashref malling the authorised value to the value set for this itemnumber
1676 $authorised_values = {
1682 'RESTRICTED' => undef,
1685 'branches' => 'CPL',
1686 'cn_source' => undef,
1687 'itemtypes' => 'SER',
1690 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1694 sub get_item_authorised_values {
1695 my $itemnumber = shift;
1697 # assume that these entries in the authorised_value table are item level.
1698 my $query = q(SELECT distinct authorised_value, kohafield
1699 FROM marc_subfield_structure
1700 WHERE kohafield like 'item%'
1701 AND authorised_value != '' );
1703 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1704 my $iteminfo = GetItem( $itemnumber );
1705 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1707 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1708 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1709 $field =~ s/^items\.//;
1710 if ( exists $iteminfo->{ $field } ) {
1711 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1714 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1718 =head3 get_authorised_value_images
1720 find a list of icons that are appropriate for display based on the
1721 authorised values for a biblio.
1723 parameters: listref of authorised values, such as comes from
1724 get_item_authorised_values or
1725 from C4::Biblio::get_biblio_authorised_values
1727 returns: listref of hashrefs for each image. Each hashref looks like this:
1729 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1734 Notes: Currently, I put on the full path to the images on the staff
1735 side. This should either be configurable or not done at all. Since I
1736 have to deal with 'intranet' or 'opac' in
1737 get_biblio_authorised_values, perhaps I should be passing it in.
1741 sub get_authorised_value_images {
1742 my $authorised_values = shift;
1746 my $authorised_value_list = GetAuthorisedValues();
1747 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1748 foreach my $this_authorised_value ( @$authorised_value_list ) {
1749 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1750 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1751 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1752 if ( defined $this_authorised_value->{'imageurl'} ) {
1753 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1754 label => $this_authorised_value->{'lib'},
1755 category => $this_authorised_value->{'category'},
1756 value => $this_authorised_value->{'authorised_value'}, };
1761 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1766 =head1 LIMITED USE FUNCTIONS
1768 The following functions, while part of the public API,
1769 are not exported. This is generally because they are
1770 meant to be used by only one script for a specific
1771 purpose, and should not be used in any other context
1772 without careful thought.
1778 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1780 Returns MARC::Record of the item passed in parameter.
1781 This function is meant for use only in C<cataloguing/additem.pl>,
1782 where it is needed to support that script's MARC-like
1788 my ( $biblionumber, $itemnumber ) = @_;
1790 # GetMarcItem has been revised so that it does the following:
1791 # 1. Gets the item information from the items table.
1792 # 2. Converts it to a MARC field for storage in the bib record.
1794 # The previous behavior was:
1795 # 1. Get the bib record.
1796 # 2. Return the MARC tag corresponding to the item record.
1798 # The difference is that one treats the items row as authoritative,
1799 # while the other treats the MARC representation as authoritative
1800 # under certain circumstances.
1802 my $itemrecord = GetItem($itemnumber);
1804 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1805 # Also, don't emit a subfield if the underlying field is blank.
1808 return Item2Marc($itemrecord,$biblionumber);
1812 my ($itemrecord,$biblionumber)=@_;
1815 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1816 } keys %{ $itemrecord }
1818 my $itemmarc = TransformKohaToMarc($mungeditem);
1819 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1821 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1822 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1823 foreach my $field ($itemmarc->field($itemtag)){
1824 $field->add_subfields(@$unlinked_item_subfields);
1830 =head1 PRIVATE FUNCTIONS AND VARIABLES
1832 The following functions are not meant to be called
1833 directly, but are documented in order to explain
1834 the inner workings of C<C4::Items>.
1838 =head2 %derived_columns
1840 This hash keeps track of item columns that
1841 are strictly derived from other columns in
1842 the item record and are not meant to be set
1845 Each key in the hash should be the name of a
1846 column (as named by TransformMarcToKoha). Each
1847 value should be hashref whose keys are the
1848 columns on which the derived column depends. The
1849 hashref should also contain a 'BUILDER' key
1850 that is a reference to a sub that calculates
1855 my %derived_columns = (
1856 'items.cn_sort' => {
1857 'itemcallnumber' => 1,
1858 'items.cn_source' => 1,
1859 'BUILDER' => \&_calc_items_cn_sort,
1863 =head2 _set_derived_columns_for_add
1865 _set_derived_column_for_add($item);
1867 Given an item hash representing a new item to be added,
1868 calculate any derived columns. Currently the only
1869 such column is C<items.cn_sort>.
1873 sub _set_derived_columns_for_add {
1876 foreach my $column (keys %derived_columns) {
1877 my $builder = $derived_columns{$column}->{'BUILDER'};
1878 my $source_values = {};
1879 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1880 next if $source_column eq 'BUILDER';
1881 $source_values->{$source_column} = $item->{$source_column};
1883 $builder->($item, $source_values);
1887 =head2 _set_derived_columns_for_mod
1889 _set_derived_column_for_mod($item);
1891 Given an item hash representing a new item to be modified.
1892 calculate any derived columns. Currently the only
1893 such column is C<items.cn_sort>.
1895 This routine differs from C<_set_derived_columns_for_add>
1896 in that it needs to handle partial item records. In other
1897 words, the caller of C<ModItem> may have supplied only one
1898 or two columns to be changed, so this function needs to
1899 determine whether any of the columns to be changed affect
1900 any of the derived columns. Also, if a derived column
1901 depends on more than one column, but the caller is not
1902 changing all of then, this routine retrieves the unchanged
1903 values from the database in order to ensure a correct
1908 sub _set_derived_columns_for_mod {
1911 foreach my $column (keys %derived_columns) {
1912 my $builder = $derived_columns{$column}->{'BUILDER'};
1913 my $source_values = {};
1914 my %missing_sources = ();
1915 my $must_recalc = 0;
1916 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1917 next if $source_column eq 'BUILDER';
1918 if (exists $item->{$source_column}) {
1920 $source_values->{$source_column} = $item->{$source_column};
1922 $missing_sources{$source_column} = 1;
1926 foreach my $source_column (keys %missing_sources) {
1927 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1929 $builder->($item, $source_values);
1934 =head2 _do_column_fixes_for_mod
1936 _do_column_fixes_for_mod($item);
1938 Given an item hashref containing one or more
1939 columns to modify, fix up certain values.
1940 Specifically, set to 0 any passed value
1941 of C<notforloan>, C<damaged>, C<itemlost>, or
1942 C<wthdrawn> that is either undefined or
1943 contains the empty string.
1947 sub _do_column_fixes_for_mod {
1950 if (exists $item->{'notforloan'} and
1951 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1952 $item->{'notforloan'} = 0;
1954 if (exists $item->{'damaged'} and
1955 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1956 $item->{'damaged'} = 0;
1958 if (exists $item->{'itemlost'} and
1959 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1960 $item->{'itemlost'} = 0;
1962 if (exists $item->{'wthdrawn'} and
1963 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1964 $item->{'wthdrawn'} = 0;
1966 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1967 $item->{'permanent_location'} = $item->{'location'};
1969 if (exists $item->{'timestamp'}) {
1970 delete $item->{'timestamp'};
1974 =head2 _get_single_item_column
1976 _get_single_item_column($column, $itemnumber);
1978 Retrieves the value of a single column from an C<items>
1979 row specified by C<$itemnumber>.
1983 sub _get_single_item_column {
1985 my $itemnumber = shift;
1987 my $dbh = C4::Context->dbh;
1988 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1989 $sth->execute($itemnumber);
1990 my ($value) = $sth->fetchrow();
1994 =head2 _calc_items_cn_sort
1996 _calc_items_cn_sort($item, $source_values);
1998 Helper routine to calculate C<items.cn_sort>.
2002 sub _calc_items_cn_sort {
2004 my $source_values = shift;
2006 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2009 =head2 _set_defaults_for_add
2011 _set_defaults_for_add($item_hash);
2013 Given an item hash representing an item to be added, set
2014 correct default values for columns whose default value
2015 is not handled by the DBMS. This includes the following
2022 C<items.dateaccessioned>
2044 sub _set_defaults_for_add {
2046 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2047 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2050 =head2 _koha_new_item
2052 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2054 Perform the actual insert into the C<items> table.
2058 sub _koha_new_item {
2059 my ( $item, $barcode ) = @_;
2060 my $dbh=C4::Context->dbh;
2063 "INSERT INTO items SET
2065 biblioitemnumber = ?,
2067 dateaccessioned = ?,
2071 replacementprice = ?,
2072 replacementpricedate = ?,
2073 datelastborrowed = ?,
2086 permanent_location = ?,
2098 more_subfields_xml = ?,
2102 my $sth = $dbh->prepare($query);
2103 my $today = C4::Dates->today('iso');
2105 $item->{'biblionumber'},
2106 $item->{'biblioitemnumber'},
2108 $item->{'dateaccessioned'},
2109 $item->{'booksellerid'},
2110 $item->{'homebranch'},
2112 $item->{'replacementprice'},
2113 $item->{'replacementpricedate'} || $today,
2114 $item->{datelastborrowed},
2115 $item->{datelastseen} || $today,
2117 $item->{'notforloan'},
2119 $item->{'itemlost'},
2120 $item->{'wthdrawn'},
2121 $item->{'itemcallnumber'},
2122 $item->{'restricted'},
2123 $item->{'itemnotes'},
2124 $item->{'holdingbranch'},
2126 $item->{'location'},
2127 $item->{'permanent_location'},
2130 $item->{'renewals'},
2131 $item->{'reserves'},
2132 $item->{'items.cn_source'},
2133 $item->{'items.cn_sort'},
2136 $item->{'materials'},
2138 $item->{'enumchron'},
2139 $item->{'more_subfields_xml'},
2140 $item->{'copynumber'},
2141 $item->{'stocknumber'},
2145 if ( defined $sth->errstr ) {
2146 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2149 $itemnumber = $dbh->{'mysql_insertid'};
2152 return ( $itemnumber, $error );
2155 =head2 MoveItemFromBiblio
2157 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2159 Moves an item from a biblio to another
2161 Returns undef if the move failed or the biblionumber of the destination record otherwise
2165 sub MoveItemFromBiblio {
2166 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2167 my $dbh = C4::Context->dbh;
2168 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2169 $sth->execute( $tobiblio );
2170 my ( $tobiblioitem ) = $sth->fetchrow();
2171 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2172 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2174 ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2175 ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2176 # Checking if the item we want to move is in an order
2177 require C4::Acquisition;
2178 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2180 # Replacing the biblionumber within the order if necessary
2181 $order->{'biblionumber'} = $tobiblio;
2182 C4::Acquisition::ModOrder($order);
2191 DelItemCheck($dbh, $biblionumber, $itemnumber);
2193 Exported function (core API) for deleting an item record in Koha if there no current issue.
2198 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2201 my $countanalytics=GetAnalyticsCount($itemnumber);
2204 # check that there is no issue on this item before deletion.
2205 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2206 $sth->execute($itemnumber);
2208 my $item = GetItem($itemnumber);
2209 my $onloan=$sth->fetchrow;
2212 $error = "book_on_loan"
2214 elsif ( !(C4::Context->userenv->{flags} & 1) and
2215 C4::Context->preference("IndependantBranches") and
2216 (C4::Context->userenv->{branch} ne
2217 $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2219 $error = "not_same_branch";
2222 # check it doesnt have a waiting reserve
2223 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2224 $sth->execute($itemnumber);
2225 my $reserve=$sth->fetchrow;
2227 $error = "book_reserved";
2228 } elsif ($countanalytics > 0){
2229 $error = "linked_analytics";
2231 DelItem($dbh, $biblionumber, $itemnumber);
2238 =head2 _koha_modify_item
2240 my ($itemnumber,$error) =_koha_modify_item( $item );
2242 Perform the actual update of the C<items> row. Note that this
2243 routine accepts a hashref specifying the columns to update.
2247 sub _koha_modify_item {
2249 my $dbh=C4::Context->dbh;
2252 my $query = "UPDATE items SET ";
2254 for my $key ( keys %$item ) {
2256 push @bind, $item->{$key};
2259 $query .= " WHERE itemnumber=?";
2260 push @bind, $item->{'itemnumber'};
2261 my $sth = C4::Context->dbh->prepare($query);
2262 $sth->execute(@bind);
2263 if ( C4::Context->dbh->errstr ) {
2264 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2267 return ($item->{'itemnumber'},$error);
2270 =head2 _koha_delete_item
2272 _koha_delete_item( $dbh, $itemnum );
2274 Internal function to delete an item record from the koha tables
2278 sub _koha_delete_item {
2279 my ( $dbh, $itemnum ) = @_;
2281 # save the deleted item to deleteditems table
2282 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2283 $sth->execute($itemnum);
2284 my $data = $sth->fetchrow_hashref();
2285 my $query = "INSERT INTO deleteditems SET ";
2287 foreach my $key ( keys %$data ) {
2288 $query .= "$key = ?,";
2289 push( @bind, $data->{$key} );
2292 $sth = $dbh->prepare($query);
2293 $sth->execute(@bind);
2295 # delete from items table
2296 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2297 $sth->execute($itemnum);
2301 =head2 _marc_from_item_hash
2303 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2305 Given an item hash representing a complete item record,
2306 create a C<MARC::Record> object containing an embedded
2307 tag representing that item.
2309 The third, optional parameter C<$unlinked_item_subfields> is
2310 an arrayref of subfields (not mapped to C<items> fields per the
2311 framework) to be added to the MARC representation
2316 sub _marc_from_item_hash {
2318 my $frameworkcode = shift;
2319 my $unlinked_item_subfields;
2321 $unlinked_item_subfields = shift;
2324 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2325 # Also, don't emit a subfield if the underlying field is blank.
2326 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2327 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2328 : () } keys %{ $item } };
2330 my $item_marc = MARC::Record->new();
2331 foreach my $item_field ( keys %{$mungeditem} ) {
2332 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2333 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2334 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2335 foreach my $value (@values){
2336 if ( my $field = $item_marc->field($tag) ) {
2337 $field->add_subfields( $subfield => $value );
2339 my $add_subfields = [];
2340 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2341 $add_subfields = $unlinked_item_subfields;
2343 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2351 =head2 _repack_item_errors
2353 Add an error message hash generated by C<CheckItemPreSave>
2354 to a list of errors.
2358 sub _repack_item_errors {
2359 my $item_sequence_num = shift;
2360 my $item_ref = shift;
2361 my $error_ref = shift;
2363 my @repacked_errors = ();
2365 foreach my $error_code (sort keys %{ $error_ref }) {
2366 my $repacked_error = {};
2367 $repacked_error->{'item_sequence'} = $item_sequence_num;
2368 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2369 $repacked_error->{'error_code'} = $error_code;
2370 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2371 push @repacked_errors, $repacked_error;
2374 return @repacked_errors;
2377 =head2 _get_unlinked_item_subfields
2379 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2383 sub _get_unlinked_item_subfields {
2384 my $original_item_marc = shift;
2385 my $frameworkcode = shift;
2387 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2389 # assume that this record has only one field, and that that
2390 # field contains only the item information
2392 my @fields = $original_item_marc->fields();
2393 if ($#fields > -1) {
2394 my $field = $fields[0];
2395 my $tag = $field->tag();
2396 foreach my $subfield ($field->subfields()) {
2397 if (defined $subfield->[1] and
2398 $subfield->[1] ne '' and
2399 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2400 push @$subfields, $subfield->[0] => $subfield->[1];
2407 =head2 _get_unlinked_subfields_xml
2409 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2413 sub _get_unlinked_subfields_xml {
2414 my $unlinked_item_subfields = shift;
2417 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2418 my $marc = MARC::Record->new();
2419 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2420 # used in the framework
2421 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2422 $marc->encoding("UTF-8");
2423 $xml = $marc->as_xml("USMARC");
2429 =head2 _parse_unlinked_item_subfields_from_xml
2431 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2435 sub _parse_unlinked_item_subfields_from_xml {
2437 require C4::Charset;
2438 return unless defined $xml and $xml ne "";
2439 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2440 my $unlinked_subfields = [];
2441 my @fields = $marc->fields();
2442 if ($#fields > -1) {
2443 foreach my $subfield ($fields[0]->subfields()) {
2444 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2447 return $unlinked_subfields;
2450 =head2 GetAnalyticsCount
2452 $count= &GetAnalyticsCount($itemnumber)
2454 counts Usage of itemnumber in Analytical bibliorecords.
2458 sub GetAnalyticsCount {
2459 my ($itemnumber) = @_;
2460 if (C4::Context->preference('NoZebra')) {
2461 # Read the index Koha-Auth-Number for this authid and count the lines
2462 my $result = C4::Search::NZanalyse("hi=$itemnumber");
2463 my @tab = split /;/,$result;
2466 ### ZOOM search here
2468 $query= "hi=".$itemnumber;
2469 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2477 $holds = &GetItemHolds($biblionumber, $itemnumber);
2481 This function return the count of holds with $biblionumber and $itemnumber
2486 my ($biblionumber, $itemnumber) = @_;
2488 my $dbh = C4::Context->dbh;
2489 my $query = "SELECT count(*)
2491 WHERE biblionumber=? AND itemnumber=?";
2492 my $sth = $dbh->prepare($query);
2493 $sth->execute($biblionumber, $itemnumber);
2494 $holds = $sth->fetchrow;
2498 # Return the list of the column names of items table
2499 sub _get_items_columns {
2500 my $dbh = C4::Context->dbh;
2501 my $sth = $dbh->column_info(undef, undef, 'items', '%');
2503 my $results = $sth->fetchall_hashref('COLUMN_NAME');
2504 return keys %$results;
2509 my $items = SearchItems($field, $value);
2511 SearchItems will search for items on a specific given field.
2512 For instance you can search all items with a specific stocknumber like this:
2514 my $items = SearchItems('stocknumber', $stocknumber);
2519 my ($field, $value) = @_;
2521 my $dbh = C4::Context->dbh;
2522 my @columns = _get_items_columns;
2524 if(0 < grep /^$field$/, @columns) {
2525 my $query = "SELECT $field FROM items WHERE $field = ?";
2526 my $sth = $dbh->prepare( $query );
2527 $sth->execute( $value );
2528 $results = $sth->fetchall_arrayref({});
2534 =head1 OTHER FUNCTIONS
2538 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2540 Find the given $subfield in the given $tag in the given
2541 MARC::Record $record. If the subfield is found, returns
2542 the (indicators, value) pair; otherwise, (undef, undef) is
2546 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2547 I suggest we export it from this module.
2552 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2555 if ( $tagfield < 10 ) {
2556 if ( $record->field($tagfield) ) {
2557 push @result, $record->field($tagfield)->data();
2562 foreach my $field ( $record->field($tagfield) ) {
2563 my @subfields = $field->subfields();
2564 foreach my $subfield (@subfields) {
2565 if ( @$subfield[0] eq $insubfield ) {
2566 push @result, @$subfield[1];
2567 $indicator = $field->indicator(1) . $field->indicator(2);
2572 return ( $indicator, @result );
2576 =head2 PrepareItemrecordDisplay
2578 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2580 Returns a hash with all the fields for Display a given item data in a template
2582 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2586 sub PrepareItemrecordDisplay {
2588 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2590 my $dbh = C4::Context->dbh;
2591 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2592 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2593 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2595 # return nothing if we don't have found an existing framework.
2596 return q{} unless $tagslib;
2599 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2602 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2603 foreach my $tag ( sort keys %{$tagslib} ) {
2604 my $previous_tag = '';
2607 # loop through each subfield
2609 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2610 next if ( subfield_is_koha_internal_p($subfield) );
2611 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2613 $subfield_data{tag} = $tag;
2614 $subfield_data{subfield} = $subfield;
2615 $subfield_data{countsubfield} = $cntsubf++;
2616 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2618 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2619 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2620 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2621 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2622 $subfield_data{hidden} = "display:none"
2623 if $tagslib->{$tag}->{$subfield}->{hidden};
2624 my ( $x, $defaultvalue );
2626 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2628 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2629 if ( !defined $defaultvalue ) {
2630 $defaultvalue = q||;
2632 $defaultvalue =~ s/"/"/g;
2634 # search for itemcallnumber if applicable
2635 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2636 && C4::Context->preference('itemcallnumber') ) {
2637 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2638 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2640 my $temp = $itemrecord->field($CNtag);
2642 $defaultvalue = $temp->subfield($CNsubfield);
2646 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2648 && $defaultvalues->{'callnumber'} ) {
2651 $temp = $itemrecord->field($subfield);
2654 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2657 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2659 && $defaultvalues->{'branchcode'} ) {
2662 $temp = $itemrecord->field($subfield);
2665 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2668 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2670 && $defaultvalues->{'location'} ) {
2671 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2673 $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2676 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2677 my @authorised_values;
2680 # builds list, depending on authorised value...
2682 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2683 if ( ( C4::Context->preference("IndependantBranches") )
2684 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2685 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2686 $sth->execute( C4::Context->userenv->{branch} );
2687 push @authorised_values, ""
2688 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2689 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2690 push @authorised_values, $branchcode;
2691 $authorised_lib{$branchcode} = $branchname;
2694 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2696 push @authorised_values, ""
2697 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2698 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2699 push @authorised_values, $branchcode;
2700 $authorised_lib{$branchcode} = $branchname;
2705 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2706 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2708 push @authorised_values, ""
2709 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2710 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2711 push @authorised_values, $itemtype;
2712 $authorised_lib{$itemtype} = $description;
2715 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2716 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2718 my $class_sources = GetClassSources();
2719 my $default_source = C4::Context->preference("DefaultClassificationSource");
2721 foreach my $class_source (sort keys %$class_sources) {
2722 next unless $class_sources->{$class_source}->{'used'} or
2723 ($class_source eq $default_source);
2724 push @authorised_values, $class_source;
2725 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2728 #---- "true" authorised value
2730 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2731 push @authorised_values, ""
2732 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2733 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2734 push @authorised_values, $value;
2735 $authorised_lib{$value} = $lib;
2738 $subfield_data{marc_value} = CGI::scrolling_list(
2739 -name => 'field_value',
2740 -values => \@authorised_values,
2741 -default => "$defaultvalue",
2742 -labels => \%authorised_lib,
2747 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2749 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2752 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2753 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2754 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2755 my $index_subfield = int(rand(1000000));
2756 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
2757 $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
2758 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2759 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2760 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2763 warn "Plugin Failed: $plugin";
2764 $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
2767 elsif ( $tag eq '' ) { # it's an hidden field
2768 $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" />);
2770 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2771 $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" />);
2773 elsif ( length($defaultvalue) > 100
2774 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2775 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2776 or (C4::Context->preference("marcflavour") eq "MARC21" and
2777 500 <= $tag && $tag < 600 )
2779 # oversize field (textarea)
2780 $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");
2782 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2784 push( @loop_data, \%subfield_data );
2789 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2790 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2793 'itemtagfield' => $itemtagfield,
2794 'itemtagsubfield' => $itemtagsubfield,
2795 'itemnumber' => $itemnumber,
2796 'iteminformation' => \@loop_data