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
84 PrepareItemrecordDisplay
91 C4::Items - item management functions
95 This module contains an API for manipulating item
96 records in Koha, and is used by cataloguing, circulation,
97 acquisitions, and serials management.
99 A Koha item record is stored in two places: the
100 items table and embedded in a MARC tag in the XML
101 version of the associated bib record in C<biblioitems.marcxml>.
102 This is done to allow the item information to be readily
103 indexed (e.g., by Zebra), but means that each item
104 modification transaction must keep the items table
105 and the MARC XML in sync at all times.
107 Consequently, all code that creates, modifies, or deletes
108 item records B<must> use an appropriate function from
109 C<C4::Items>. If no existing function is suitable, it is
110 better to add one to C<C4::Items> than to use add
111 one-off SQL statements to add or modify items.
113 The items table will be considered authoritative. In other
114 words, if there is ever a discrepancy between the items
115 table and the MARC XML, the items table should be considered
118 =head1 HISTORICAL NOTE
120 Most of the functions in C<C4::Items> were originally in
121 the C<C4::Biblio> module.
123 =head1 CORE EXPORTED FUNCTIONS
125 The following functions are meant for use by users
132 $item = GetItem($itemnumber,$barcode,$serial);
134 Return item information, for a given itemnumber or barcode.
135 The return value is a hashref mapping item column
136 names to values. If C<$serial> is true, include serial publication data.
141 my ($itemnumber,$barcode, $serial) = @_;
142 my $dbh = C4::Context->dbh;
145 my $sth = $dbh->prepare("
147 WHERE itemnumber = ?");
148 $sth->execute($itemnumber);
149 $data = $sth->fetchrow_hashref;
151 my $sth = $dbh->prepare("
155 $sth->execute($barcode);
156 $data = $sth->fetchrow_hashref;
159 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
160 $ssth->execute($data->{'itemnumber'}) ;
161 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
163 #if we don't have an items.itype, use biblioitems.itemtype.
164 if( ! $data->{'itype'} ) {
165 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
166 $sth->execute($data->{'biblionumber'});
167 ($data->{'itype'}) = $sth->fetchrow_array;
174 CartToShelf($itemnumber);
176 Set the current shelving location of the item record
177 to its stored permanent shelving location. This is
178 primarily used to indicate when an item whose current
179 location is a special processing ('PROC') or shelving cart
180 ('CART') location is back in the stacks.
185 my ( $itemnumber ) = @_;
187 unless ( $itemnumber ) {
188 croak "FAILED CartToShelf() - no itemnumber supplied";
191 my $item = GetItem($itemnumber);
192 $item->{location} = $item->{permanent_location};
193 ModItem($item, undef, $itemnumber);
196 =head2 AddItemFromMarc
198 my ($biblionumber, $biblioitemnumber, $itemnumber)
199 = AddItemFromMarc($source_item_marc, $biblionumber);
201 Given a MARC::Record object containing an embedded item
202 record and a biblionumber, create a new item record.
206 sub AddItemFromMarc {
207 my ( $source_item_marc, $biblionumber ) = @_;
208 my $dbh = C4::Context->dbh;
210 # parse item hash from MARC
211 my $frameworkcode = GetFrameworkCode( $biblionumber );
212 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
214 my $localitemmarc=MARC::Record->new;
215 $localitemmarc->append_fields($source_item_marc->field($itemtag));
216 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
217 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
218 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
223 my ($biblionumber, $biblioitemnumber, $itemnumber)
224 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
226 Given a hash containing item column names as keys,
227 create a new Koha item record.
229 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
230 do not need to be supplied for general use; they exist
231 simply to allow them to be picked up from AddItemFromMarc.
233 The final optional parameter, C<$unlinked_item_subfields>, contains
234 an arrayref containing subfields present in the original MARC
235 representation of the item (e.g., from the item editor) that are
236 not mapped to C<items> columns directly but should instead
237 be stored in C<items.more_subfields_xml> and included in
238 the biblio items tag for display and indexing.
244 my $biblionumber = shift;
246 my $dbh = @_ ? shift : C4::Context->dbh;
247 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
248 my $unlinked_item_subfields;
250 $unlinked_item_subfields = shift
253 # needs old biblionumber and biblioitemnumber
254 $item->{'biblionumber'} = $biblionumber;
255 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
256 $sth->execute( $item->{'biblionumber'} );
257 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
259 _set_defaults_for_add($item);
260 _set_derived_columns_for_add($item);
261 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
262 # FIXME - checks here
263 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
264 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
265 $itype_sth->execute( $item->{'biblionumber'} );
266 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
269 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
270 $item->{'itemnumber'} = $itemnumber;
272 ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
274 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
276 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
279 =head2 AddItemBatchFromMarc
281 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
282 $biblionumber, $biblioitemnumber, $frameworkcode);
284 Efficiently create item records from a MARC biblio record with
285 embedded item fields. This routine is suitable for batch jobs.
287 This API assumes that the bib record has already been
288 saved to the C<biblio> and C<biblioitems> tables. It does
289 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
290 are populated, but it will do so via a call to ModBibiloMarc.
292 The goal of this API is to have a similar effect to using AddBiblio
293 and AddItems in succession, but without inefficient repeated
294 parsing of the MARC XML bib record.
296 This function returns an arrayref of new itemsnumbers and an arrayref of item
297 errors encountered during the processing. Each entry in the errors
298 list is a hashref containing the following keys:
304 Sequence number of original item tag in the MARC record.
308 Item barcode, provide to assist in the construction of
309 useful error messages.
311 =item error_condition
313 Code representing the error condition. Can be 'duplicate_barcode',
314 'invalid_homebranch', or 'invalid_holdingbranch'.
316 =item error_information
318 Additional information appropriate to the error condition.
324 sub AddItemBatchFromMarc {
325 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
327 my @itemnumbers = ();
329 my $dbh = C4::Context->dbh;
331 # loop through the item tags and start creating items
332 my @bad_item_fields = ();
333 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
334 my $item_sequence_num = 0;
335 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
336 $item_sequence_num++;
337 # we take the item field and stick it into a new
338 # MARC record -- this is required so far because (FIXME)
339 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
340 # and there is no TransformMarcFieldToKoha
341 my $temp_item_marc = MARC::Record->new();
342 $temp_item_marc->append_fields($item_field);
344 # add biblionumber and biblioitemnumber
345 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
346 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
347 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
348 $item->{'biblionumber'} = $biblionumber;
349 $item->{'biblioitemnumber'} = $biblioitemnumber;
351 # check for duplicate barcode
352 my %item_errors = CheckItemPreSave($item);
354 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
355 push @bad_item_fields, $item_field;
359 _set_defaults_for_add($item);
360 _set_derived_columns_for_add($item);
361 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
362 warn $error if $error;
363 push @itemnumbers, $itemnumber; # FIXME not checking error
364 $item->{'itemnumber'} = $itemnumber;
366 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
368 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
369 $item_field->replace_with($new_item_marc->field($itemtag));
372 # remove any MARC item fields for rejected items
373 foreach my $item_field (@bad_item_fields) {
374 $record->delete_field($item_field);
377 # update the MARC biblio
378 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
380 return (\@itemnumbers, \@errors);
383 =head2 ModItemFromMarc
385 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
387 This function updates an item record based on a supplied
388 C<MARC::Record> object containing an embedded item field.
389 This API is meant for the use of C<additem.pl>; for
390 other purposes, C<ModItem> should be used.
392 This function uses the hash %default_values_for_mod_from_marc,
393 which contains default values for item fields to
394 apply when modifying an item. This is needed beccause
395 if an item field's value is cleared, TransformMarcToKoha
396 does not include the column in the
397 hash that's passed to ModItem, which without
398 use of this hash makes it impossible to clear
399 an item field's value. See bug 2466.
401 Note that only columns that can be directly
402 changed from the cataloging and serials
403 item editors are included in this hash.
409 my %default_values_for_mod_from_marc = (
411 booksellerid => undef,
413 'items.cn_source' => undef,
416 # dateaccessioned => undef,
418 holdingbranch => undef,
420 itemcallnumber => undef,
425 permanent_location => undef,
430 replacementprice => undef,
431 replacementpricedate => undef,
434 stocknumber => undef,
439 sub ModItemFromMarc {
440 my $item_marc = shift;
441 my $biblionumber = shift;
442 my $itemnumber = shift;
444 my $dbh = C4::Context->dbh;
445 my $frameworkcode = GetFrameworkCode($biblionumber);
446 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
448 my $localitemmarc = MARC::Record->new;
449 $localitemmarc->append_fields( $item_marc->field($itemtag) );
450 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
451 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
452 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
454 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
456 ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
462 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
464 Change one or more columns in an item record and update
465 the MARC representation of the item.
467 The first argument is a hashref mapping from item column
468 names to the new values. The second and third arguments
469 are the biblionumber and itemnumber, respectively.
471 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
472 an arrayref containing subfields present in the original MARC
473 representation of the item (e.g., from the item editor) that are
474 not mapped to C<items> columns directly but should instead
475 be stored in C<items.more_subfields_xml> and included in
476 the biblio items tag for display and indexing.
478 If one of the changed columns is used to calculate
479 the derived value of a column such as C<items.cn_sort>,
480 this routine will perform the necessary calculation
487 my $biblionumber = shift;
488 my $itemnumber = shift;
490 # if $biblionumber is undefined, get it from the current item
491 unless (defined $biblionumber) {
492 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
495 my $dbh = @_ ? shift : C4::Context->dbh;
496 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
498 my $unlinked_item_subfields;
500 $unlinked_item_subfields = shift;
501 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
504 $item->{'itemnumber'} = $itemnumber or return undef;
506 $item->{onloan} = undef if $item->{itemlost};
508 _set_derived_columns_for_mod($item);
509 _do_column_fixes_for_mod($item);
512 # attempt to change itemnumber
513 # attempt to change biblionumber (if we want
514 # an API to relink an item to a different bib,
515 # it should be a separate function)
518 _koha_modify_item($item);
520 # request that bib be reindexed so that searching on current
521 # item status is possible
522 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
524 logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
527 =head2 ModItemTransfer
529 ModItemTransfer($itenumber, $frombranch, $tobranch);
531 Marks an item as being transferred from one branch
536 sub ModItemTransfer {
537 my ( $itemnumber, $frombranch, $tobranch ) = @_;
539 my $dbh = C4::Context->dbh;
541 #new entry in branchtransfers....
542 my $sth = $dbh->prepare(
543 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
544 VALUES (?, ?, NOW(), ?)");
545 $sth->execute($itemnumber, $frombranch, $tobranch);
547 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
548 ModDateLastSeen($itemnumber);
552 =head2 ModDateLastSeen
554 ModDateLastSeen($itemnum);
556 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
557 C<$itemnum> is the item number
561 sub ModDateLastSeen {
562 my ($itemnumber) = @_;
564 my $today = C4::Dates->new();
565 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
570 DelItem($dbh, $biblionumber, $itemnumber);
572 Exported function (core API) for deleting an item record in Koha.
577 my ( $dbh, $biblionumber, $itemnumber ) = @_;
579 # FIXME check the item has no current issues
581 _koha_delete_item( $dbh, $itemnumber );
583 # get the MARC record
584 my $record = GetMarcBiblio($biblionumber);
585 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
588 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
589 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
590 # 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).
592 #search item field code
593 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
596 =head2 CheckItemPreSave
598 my $item_ref = TransformMarcToKoha($marc, 'items');
600 my %errors = CheckItemPreSave($item_ref);
601 if (exists $errors{'duplicate_barcode'}) {
602 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
603 } elsif (exists $errors{'invalid_homebranch'}) {
604 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
605 } elsif (exists $errors{'invalid_holdingbranch'}) {
606 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
611 Given a hashref containing item fields, determine if it can be
612 inserted or updated in the database. Specifically, checks for
613 database integrity issues, and returns a hash containing any
614 of the following keys, if applicable.
618 =item duplicate_barcode
620 Barcode, if it duplicates one already found in the database.
622 =item invalid_homebranch
624 Home branch, if not defined in branches table.
626 =item invalid_holdingbranch
628 Holding branch, if not defined in branches table.
632 This function does NOT implement any policy-related checks,
633 e.g., whether current operator is allowed to save an
634 item that has a given branch code.
638 sub CheckItemPreSave {
639 my $item_ref = shift;
644 # check for duplicate barcode
645 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
646 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
647 if ($existing_itemnumber) {
648 if (!exists $item_ref->{'itemnumber'} # new item
649 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
650 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
655 # check for valid home branch
656 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
657 my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
658 unless (defined $branch_name) {
659 # relies on fact that branches.branchname is a non-NULL column,
660 # so GetBranchName returns undef only if branch does not exist
661 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
665 # check for valid holding branch
666 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
667 my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
668 unless (defined $branch_name) {
669 # relies on fact that branches.branchname is a non-NULL column,
670 # so GetBranchName returns undef only if branch does not exist
671 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
679 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
681 The following functions provide various ways of
682 getting an item record, a set of item records, or
683 lists of authorized values for certain item fields.
685 Some of the functions in this group are candidates
686 for refactoring -- for example, some of the code
687 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
688 has copy-and-paste work.
694 $itemstatushash = GetItemStatus($fwkcode);
696 Returns a list of valid values for the
697 C<items.notforloan> field.
699 NOTE: does B<not> return an individual item's
702 Can be MARC dependant.
704 But basically could be can be loan or not
705 Create a status selector with the following code
707 =head3 in PERL SCRIPT
709 my $itemstatushash = getitemstatus;
711 foreach my $thisstatus (keys %$itemstatushash) {
712 my %row =(value => $thisstatus,
713 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
715 push @itemstatusloop, \%row;
717 $template->param(statusloop=>\@itemstatusloop);
721 <select name="statusloop">
722 <option value="">Default</option>
723 <!-- TMPL_LOOP name="statusloop" -->
724 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
732 # returns a reference to a hash of references to status...
735 my $dbh = C4::Context->dbh;
737 $fwk = '' unless ($fwk);
738 my ( $tag, $subfield ) =
739 GetMarcFromKohaField( "items.notforloan", $fwk );
740 if ( $tag and $subfield ) {
743 "SELECT authorised_value
744 FROM marc_subfield_structure
750 $sth->execute( $tag, $subfield, $fwk );
751 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
754 "SELECT authorised_value,lib
755 FROM authorised_values
760 $authvalsth->execute($authorisedvaluecat);
761 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
762 $itemstatus{$authorisedvalue} = $lib;
776 $itemstatus{"1"} = "Not For Loan";
780 =head2 GetItemLocation
782 $itemlochash = GetItemLocation($fwk);
784 Returns a list of valid values for the
785 C<items.location> field.
787 NOTE: does B<not> return an individual item's
790 where fwk stands for an optional framework code.
791 Create a location selector with the following code
793 =head3 in PERL SCRIPT
795 my $itemlochash = getitemlocation;
797 foreach my $thisloc (keys %$itemlochash) {
798 my $selected = 1 if $thisbranch eq $branch;
799 my %row =(locval => $thisloc,
800 selected => $selected,
801 locname => $itemlochash->{$thisloc},
803 push @itemlocloop, \%row;
805 $template->param(itemlocationloop => \@itemlocloop);
809 <select name="location">
810 <option value="">Default</option>
811 <!-- TMPL_LOOP name="itemlocationloop" -->
812 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
818 sub GetItemLocation {
820 # returns a reference to a hash of references to location...
823 my $dbh = C4::Context->dbh;
825 $fwk = '' unless ($fwk);
826 my ( $tag, $subfield ) =
827 GetMarcFromKohaField( "items.location", $fwk );
828 if ( $tag and $subfield ) {
831 "SELECT authorised_value
832 FROM marc_subfield_structure
837 $sth->execute( $tag, $subfield, $fwk );
838 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
841 "SELECT authorised_value,lib
842 FROM authorised_values
846 $authvalsth->execute($authorisedvaluecat);
847 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
848 $itemlocation{$authorisedvalue} = $lib;
850 return \%itemlocation;
862 $itemlocation{"1"} = "Not For Loan";
863 return \%itemlocation;
868 $items = GetLostItems( $where, $orderby );
870 This function gets a list of lost items.
876 C<$where> is a hashref. it containts a field of the items table as key
877 and the value to match as value. For example:
879 { barcode => 'abc123',
880 homebranch => 'CPL', }
882 C<$orderby> is a field of the items table by which the resultset
887 C<$items> is a reference to an array full of hashrefs with columns
888 from the "items" table as keys.
890 =item usage in the perl script:
892 my $where = { barcode => '0001548' };
893 my $items = GetLostItems( $where, "homebranch" );
894 $template->param( itemsloop => $items );
901 # Getting input args.
904 my $dbh = C4::Context->dbh;
909 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
910 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
911 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
913 authorised_values.category = 'LOST'
914 AND itemlost IS NOT NULL
917 my @query_parameters;
918 foreach my $key (keys %$where) {
919 $query .= " AND $key LIKE ?";
920 push @query_parameters, "%$where->{$key}%";
922 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
924 if ( defined $orderby && grep($orderby, @ordervalues)) {
925 $query .= ' ORDER BY '.$orderby;
928 my $sth = $dbh->prepare($query);
929 $sth->execute( @query_parameters );
931 while ( my $row = $sth->fetchrow_hashref ){
937 =head2 GetItemsForInventory
939 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
940 $location, $itemtype $datelastseen, $branch,
941 $offset, $size, $statushash);
943 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
945 The sub returns a reference to a list of hashes, each containing
946 itemnumber, author, title, barcode, item callnumber, and date last
947 seen. It is ordered by callnumber then title.
949 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
950 the datelastseen can be used to specify that you want to see items not seen since a past date only.
951 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
952 $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.
956 sub GetItemsForInventory {
957 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
958 my $dbh = C4::Context->dbh;
959 my ( @bind_params, @where_strings );
961 my $query = <<'END_SQL';
962 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
964 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
965 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
968 for my $authvfield (keys %$statushash){
969 if ( scalar @{$statushash->{$authvfield}} > 0 ){
970 my $joinedvals = join ',', @{$statushash->{$authvfield}};
971 push @where_strings, "$authvfield in (" . $joinedvals . ")";
977 push @where_strings, 'itemcallnumber >= ?';
978 push @bind_params, $minlocation;
982 push @where_strings, 'itemcallnumber <= ?';
983 push @bind_params, $maxlocation;
987 $datelastseen = format_date_in_iso($datelastseen);
988 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
989 push @bind_params, $datelastseen;
993 push @where_strings, 'items.location = ?';
994 push @bind_params, $location;
998 if($branch eq "homebranch"){
999 push @where_strings, 'items.homebranch = ?';
1001 push @where_strings, 'items.holdingbranch = ?';
1003 push @bind_params, $branchcode;
1007 push @where_strings, 'biblioitems.itemtype = ?';
1008 push @bind_params, $itemtype;
1011 if ( $ignoreissued) {
1012 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1013 push @where_strings, 'issues.date_due IS NULL';
1016 if ( @where_strings ) {
1018 $query .= join ' AND ', @where_strings;
1020 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1021 my $sth = $dbh->prepare($query);
1022 $sth->execute( @bind_params );
1026 while ( my $row = $sth->fetchrow_hashref ) {
1027 $offset-- if ($offset);
1028 $row->{datelastseen}=format_date($row->{datelastseen});
1029 if ( ( !$offset ) && $size ) {
1030 push @results, $row;
1037 =head2 GetItemsCount
1039 $count = &GetItemsCount( $biblionumber);
1041 This function return count of item with $biblionumber
1046 my ( $biblionumber ) = @_;
1047 my $dbh = C4::Context->dbh;
1048 my $query = "SELECT count(*)
1050 WHERE biblionumber=?";
1051 my $sth = $dbh->prepare($query);
1052 $sth->execute($biblionumber);
1053 my $count = $sth->fetchrow;
1057 =head2 GetItemInfosOf
1059 GetItemInfosOf(@itemnumbers);
1063 sub GetItemInfosOf {
1064 my @itemnumbers = @_;
1069 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1071 return get_infos_of( $query, 'itemnumber' );
1074 =head2 GetItemsByBiblioitemnumber
1076 GetItemsByBiblioitemnumber($biblioitemnumber);
1078 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1079 Called by C<C4::XISBN>
1083 sub GetItemsByBiblioitemnumber {
1084 my ( $bibitem ) = @_;
1085 my $dbh = C4::Context->dbh;
1086 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1087 # Get all items attached to a biblioitem
1090 $sth->execute($bibitem) || die $sth->errstr;
1091 while ( my $data = $sth->fetchrow_hashref ) {
1092 # Foreach item, get circulation information
1093 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1094 WHERE itemnumber = ?
1095 AND issues.borrowernumber = borrowers.borrowernumber"
1097 $sth2->execute( $data->{'itemnumber'} );
1098 if ( my $data2 = $sth2->fetchrow_hashref ) {
1099 # if item is out, set the due date and who it is out too
1100 $data->{'date_due'} = $data2->{'date_due'};
1101 $data->{'cardnumber'} = $data2->{'cardnumber'};
1102 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1105 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1106 $data->{'date_due'} = '';
1108 # Find the last 3 people who borrowed this item.
1109 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1110 AND old_issues.borrowernumber = borrowers.borrowernumber
1111 ORDER BY returndate desc,timestamp desc LIMIT 3";
1112 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1113 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1115 while ( my $data2 = $sth2->fetchrow_hashref ) {
1116 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1117 $data->{"card$i2"} = $data2->{'cardnumber'};
1118 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1121 push(@results,$data);
1128 @results = GetItemsInfo($biblionumber);
1130 Returns information about items with the given biblionumber.
1132 C<GetItemsInfo> returns a list of references-to-hash. Each element
1133 contains a number of keys. Most of them are attributes from the
1134 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1135 Koha database. Other keys include:
1139 =item C<$data-E<gt>{branchname}>
1141 The name (not the code) of the branch to which the book belongs.
1143 =item C<$data-E<gt>{datelastseen}>
1145 This is simply C<items.datelastseen>, except that while the date is
1146 stored in YYYY-MM-DD format in the database, here it is converted to
1147 DD/MM/YYYY format. A NULL date is returned as C<//>.
1149 =item C<$data-E<gt>{datedue}>
1151 =item C<$data-E<gt>{class}>
1153 This is the concatenation of C<biblioitems.classification>, the book's
1154 Dewey code, and C<biblioitems.subclass>.
1156 =item C<$data-E<gt>{ocount}>
1158 I think this is the number of copies of the book available.
1160 =item C<$data-E<gt>{order}>
1162 If this is set, it is set to C<One Order>.
1169 my ( $biblionumber ) = @_;
1170 my $dbh = C4::Context->dbh;
1171 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1177 biblioitems.itemtype,
1180 biblioitems.publicationyear,
1181 biblioitems.publishercode,
1182 biblioitems.volumedate,
1183 biblioitems.volumedesc,
1186 items.notforloan as itemnotforloan,
1187 itemtypes.description,
1188 itemtypes.notforloan as notforloan_per_itemtype,
1191 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1192 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1193 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1194 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1195 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1196 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1197 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname,items.dateaccessioned desc" ;
1198 my $sth = $dbh->prepare($query);
1199 $sth->execute($biblionumber);
1204 my $isth = $dbh->prepare(
1205 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1206 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1207 WHERE itemnumber = ?"
1209 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1210 while ( my $data = $sth->fetchrow_hashref ) {
1212 $isth->execute( $data->{'itemnumber'} );
1213 if ( my $idata = $isth->fetchrow_hashref ) {
1214 $data->{borrowernumber} = $idata->{borrowernumber};
1215 $data->{cardnumber} = $idata->{cardnumber};
1216 $data->{surname} = $idata->{surname};
1217 $data->{firstname} = $idata->{firstname};
1218 $data->{lastreneweddate} = $idata->{lastreneweddate};
1219 $datedue = $idata->{'date_due'};
1220 if (C4::Context->preference("IndependantBranches")){
1221 my $userenv = C4::Context->userenv;
1222 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1223 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1227 if ( $data->{'serial'}) {
1228 $ssth->execute($data->{'itemnumber'}) ;
1229 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1232 #get branch information.....
1233 my $bsth = $dbh->prepare(
1234 "SELECT * FROM branches WHERE branchcode = ?
1237 $bsth->execute( $data->{'holdingbranch'} );
1238 if ( my $bdata = $bsth->fetchrow_hashref ) {
1239 $data->{'branchname'} = $bdata->{'branchname'};
1241 $data->{'datedue'} = $datedue;
1243 # get notforloan complete status if applicable
1244 my $sthnflstatus = $dbh->prepare(
1245 'SELECT authorised_value
1246 FROM marc_subfield_structure
1247 WHERE kohafield="items.notforloan"
1251 $sthnflstatus->execute;
1252 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1253 if ($authorised_valuecode) {
1254 $sthnflstatus = $dbh->prepare(
1255 "SELECT lib FROM authorised_values
1257 AND authorised_value=?"
1259 $sthnflstatus->execute( $authorised_valuecode,
1260 $data->{itemnotforloan} );
1261 my ($lib) = $sthnflstatus->fetchrow;
1262 $data->{notforloanvalue} = $lib;
1265 # get restricted status and description if applicable
1266 my $restrictedstatus = $dbh->prepare(
1267 'SELECT authorised_value
1268 FROM marc_subfield_structure
1269 WHERE kohafield="items.restricted"
1273 $restrictedstatus->execute;
1274 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1275 if ($authorised_valuecode) {
1276 $restrictedstatus = $dbh->prepare(
1277 "SELECT lib,lib_opac FROM authorised_values
1279 AND authorised_value=?"
1281 $restrictedstatus->execute( $authorised_valuecode,
1282 $data->{restricted} );
1284 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1285 $data->{restricted} = $rstdata->{'lib'};
1286 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1290 # my stack procedures
1291 my $stackstatus = $dbh->prepare(
1292 'SELECT authorised_value
1293 FROM marc_subfield_structure
1294 WHERE kohafield="items.stack"
1297 $stackstatus->execute;
1299 ($authorised_valuecode) = $stackstatus->fetchrow;
1300 if ($authorised_valuecode) {
1301 $stackstatus = $dbh->prepare(
1303 FROM authorised_values
1305 AND authorised_value=?
1308 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1309 my ($lib) = $stackstatus->fetchrow;
1310 $data->{stack} = $lib;
1312 # Find the last 3 people who borrowed this item.
1313 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1314 WHERE itemnumber = ?
1315 AND old_issues.borrowernumber = borrowers.borrowernumber
1316 ORDER BY returndate DESC
1318 $sth2->execute($data->{'itemnumber'});
1320 while (my $data2 = $sth2->fetchrow_hashref()) {
1321 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1322 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1323 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1327 $results[$i] = $data;
1331 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1337 =head2 GetItemsLocationInfo
1339 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1341 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1343 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1347 =item C<$data-E<gt>{homebranch}>
1349 Branch Name of the item's homebranch
1351 =item C<$data-E<gt>{holdingbranch}>
1353 Branch Name of the item's holdingbranch
1355 =item C<$data-E<gt>{location}>
1357 Item's shelving location code
1359 =item C<$data-E<gt>{location_intranet}>
1361 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1363 =item C<$data-E<gt>{location_opac}>
1365 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1368 =item C<$data-E<gt>{itemcallnumber}>
1370 Item's itemcallnumber
1372 =item C<$data-E<gt>{cn_sort}>
1374 Item's call number normalized for sorting
1380 sub GetItemsLocationInfo {
1381 my $biblionumber = shift;
1384 my $dbh = C4::Context->dbh;
1385 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1386 location, itemcallnumber, cn_sort
1387 FROM items, branches as a, branches as b
1388 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1389 AND biblionumber = ?
1390 ORDER BY cn_sort ASC";
1391 my $sth = $dbh->prepare($query);
1392 $sth->execute($biblionumber);
1394 while ( my $data = $sth->fetchrow_hashref ) {
1395 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1396 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1397 push @results, $data;
1402 =head2 GetHostItemsInfo
1404 $hostiteminfo = GetHostItemsInfo($hostfield);
1405 Returns the iteminfo for items linked to records via a host field
1409 sub GetHostItemsInfo {
1411 my @returnitemsInfo;
1413 if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1414 C4::Context->preference('marcflavour') eq 'NORMARC'){
1415 foreach my $hostfield ( $record->field('773') ) {
1416 my $hostbiblionumber = $hostfield->subfield("0");
1417 my $linkeditemnumber = $hostfield->subfield("9");
1418 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1419 foreach my $hostitemInfo (@hostitemInfos){
1420 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1421 push (@returnitemsInfo,$hostitemInfo);
1426 } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1427 foreach my $hostfield ( $record->field('461') ) {
1428 my $hostbiblionumber = $hostfield->subfield("0");
1429 my $linkeditemnumber = $hostfield->subfield("9");
1430 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1431 foreach my $hostitemInfo (@hostitemInfos){
1432 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1433 push (@returnitemsInfo,$hostitemInfo);
1439 return @returnitemsInfo;
1443 =head2 GetLastAcquisitions
1445 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1446 'itemtypes' => ('BK','BD')}, 10);
1450 sub GetLastAcquisitions {
1451 my ($data,$max) = @_;
1453 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1455 my $number_of_branches = @{$data->{branches}};
1456 my $number_of_itemtypes = @{$data->{itemtypes}};
1459 my @where = ('WHERE 1 ');
1460 $number_of_branches and push @where
1461 , 'AND holdingbranch IN ('
1462 , join(',', ('?') x $number_of_branches )
1466 $number_of_itemtypes and push @where
1467 , "AND $itemtype IN ("
1468 , join(',', ('?') x $number_of_itemtypes )
1472 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1473 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1474 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1476 GROUP BY biblio.biblionumber
1477 ORDER BY dateaccessioned DESC LIMIT $max";
1479 my $dbh = C4::Context->dbh;
1480 my $sth = $dbh->prepare($query);
1482 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1485 while( my $row = $sth->fetchrow_hashref){
1486 push @results, {date => $row->{dateaccessioned}
1487 , biblionumber => $row->{biblionumber}
1488 , title => $row->{title}};
1494 =head2 get_itemnumbers_of
1496 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1498 Given a list of biblionumbers, return the list of corresponding itemnumbers
1499 for each biblionumber.
1501 Return a reference on a hash where keys are biblionumbers and values are
1502 references on array of itemnumbers.
1506 sub get_itemnumbers_of {
1507 my @biblionumbers = @_;
1509 my $dbh = C4::Context->dbh;
1515 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1517 my $sth = $dbh->prepare($query);
1518 $sth->execute(@biblionumbers);
1522 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1523 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1526 return \%itemnumbers_of;
1529 =head2 get_hostitemnumbers_of
1531 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1533 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1535 Return a reference on a hash where key is a biblionumber and values are
1536 references on array of itemnumbers.
1541 sub get_hostitemnumbers_of {
1542 my ($biblionumber) = @_;
1543 my $marcrecord = GetMarcBiblio($biblionumber);
1544 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1546 my $marcflavor = C4::Context->preference('marcflavour');
1547 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1551 } elsif ($marcflavor eq 'UNIMARC') {
1557 foreach my $hostfield ( $marcrecord->field($tag) ) {
1558 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1559 my $linkeditemnumber = $hostfield->subfield($item_s);
1561 if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1563 @itemnumbers = @$itemnumbers;
1565 foreach my $itemnumber (@itemnumbers){
1566 if ($itemnumber eq $linkeditemnumber){
1567 push (@returnhostitemnumbers,$itemnumber);
1572 return @returnhostitemnumbers;
1576 =head2 GetItemnumberFromBarcode
1578 $result = GetItemnumberFromBarcode($barcode);
1582 sub GetItemnumberFromBarcode {
1584 my $dbh = C4::Context->dbh;
1587 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1588 $rq->execute($barcode);
1589 my ($result) = $rq->fetchrow;
1593 =head2 GetBarcodeFromItemnumber
1595 $result = GetBarcodeFromItemnumber($itemnumber);
1599 sub GetBarcodeFromItemnumber {
1600 my ($itemnumber) = @_;
1601 my $dbh = C4::Context->dbh;
1604 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1605 $rq->execute($itemnumber);
1606 my ($result) = $rq->fetchrow;
1610 =head2 GetHiddenItemnumbers
1614 $result = GetHiddenItemnumbers(@items);
1620 sub GetHiddenItemnumbers {
1624 my $yaml = C4::Context->preference('OpacHiddenItems');
1625 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1628 $hidingrules = YAML::Load($yaml);
1631 warn "Unable to parse OpacHiddenItems syspref : $@";
1634 my $dbh = C4::Context->dbh;
1637 foreach my $item (@items) {
1639 # We check each rule
1640 foreach my $field (keys %$hidingrules) {
1642 if (exists $item->{$field}) {
1643 $val = $item->{$field};
1646 my $query = "SELECT $field from items where itemnumber = ?";
1647 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1649 $val = '' unless defined $val;
1651 # If the results matches the values in the yaml file
1652 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1654 # We add the itemnumber to the list
1655 push @resultitems, $item->{'itemnumber'};
1657 # If at least one rule matched for an item, no need to test the others
1662 return @resultitems;
1665 =head3 get_item_authorised_values
1667 find the types and values for all authorised values assigned to this item.
1669 parameters: itemnumber
1671 returns: a hashref malling the authorised value to the value set for this itemnumber
1673 $authorised_values = {
1679 'RESTRICTED' => undef,
1682 'branches' => 'CPL',
1683 'cn_source' => undef,
1684 'itemtypes' => 'SER',
1687 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1691 sub get_item_authorised_values {
1692 my $itemnumber = shift;
1694 # assume that these entries in the authorised_value table are item level.
1695 my $query = q(SELECT distinct authorised_value, kohafield
1696 FROM marc_subfield_structure
1697 WHERE kohafield like 'item%'
1698 AND authorised_value != '' );
1700 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1701 my $iteminfo = GetItem( $itemnumber );
1702 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1704 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1705 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1706 $field =~ s/^items\.//;
1707 if ( exists $iteminfo->{ $field } ) {
1708 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1711 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1715 =head3 get_authorised_value_images
1717 find a list of icons that are appropriate for display based on the
1718 authorised values for a biblio.
1720 parameters: listref of authorised values, such as comes from
1721 get_item_authorised_values or
1722 from C4::Biblio::get_biblio_authorised_values
1724 returns: listref of hashrefs for each image. Each hashref looks like this:
1726 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1731 Notes: Currently, I put on the full path to the images on the staff
1732 side. This should either be configurable or not done at all. Since I
1733 have to deal with 'intranet' or 'opac' in
1734 get_biblio_authorised_values, perhaps I should be passing it in.
1738 sub get_authorised_value_images {
1739 my $authorised_values = shift;
1743 my $authorised_value_list = GetAuthorisedValues();
1744 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1745 foreach my $this_authorised_value ( @$authorised_value_list ) {
1746 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1747 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1748 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1749 if ( defined $this_authorised_value->{'imageurl'} ) {
1750 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1751 label => $this_authorised_value->{'lib'},
1752 category => $this_authorised_value->{'category'},
1753 value => $this_authorised_value->{'authorised_value'}, };
1758 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1763 =head1 LIMITED USE FUNCTIONS
1765 The following functions, while part of the public API,
1766 are not exported. This is generally because they are
1767 meant to be used by only one script for a specific
1768 purpose, and should not be used in any other context
1769 without careful thought.
1775 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1777 Returns MARC::Record of the item passed in parameter.
1778 This function is meant for use only in C<cataloguing/additem.pl>,
1779 where it is needed to support that script's MARC-like
1785 my ( $biblionumber, $itemnumber ) = @_;
1787 # GetMarcItem has been revised so that it does the following:
1788 # 1. Gets the item information from the items table.
1789 # 2. Converts it to a MARC field for storage in the bib record.
1791 # The previous behavior was:
1792 # 1. Get the bib record.
1793 # 2. Return the MARC tag corresponding to the item record.
1795 # The difference is that one treats the items row as authoritative,
1796 # while the other treats the MARC representation as authoritative
1797 # under certain circumstances.
1799 my $itemrecord = GetItem($itemnumber);
1801 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1802 # Also, don't emit a subfield if the underlying field is blank.
1805 return Item2Marc($itemrecord,$biblionumber);
1809 my ($itemrecord,$biblionumber)=@_;
1812 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1813 } keys %{ $itemrecord }
1815 my $itemmarc = TransformKohaToMarc($mungeditem);
1816 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1818 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1819 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1820 foreach my $field ($itemmarc->field($itemtag)){
1821 $field->add_subfields(@$unlinked_item_subfields);
1827 =head1 PRIVATE FUNCTIONS AND VARIABLES
1829 The following functions are not meant to be called
1830 directly, but are documented in order to explain
1831 the inner workings of C<C4::Items>.
1835 =head2 %derived_columns
1837 This hash keeps track of item columns that
1838 are strictly derived from other columns in
1839 the item record and are not meant to be set
1842 Each key in the hash should be the name of a
1843 column (as named by TransformMarcToKoha). Each
1844 value should be hashref whose keys are the
1845 columns on which the derived column depends. The
1846 hashref should also contain a 'BUILDER' key
1847 that is a reference to a sub that calculates
1852 my %derived_columns = (
1853 'items.cn_sort' => {
1854 'itemcallnumber' => 1,
1855 'items.cn_source' => 1,
1856 'BUILDER' => \&_calc_items_cn_sort,
1860 =head2 _set_derived_columns_for_add
1862 _set_derived_column_for_add($item);
1864 Given an item hash representing a new item to be added,
1865 calculate any derived columns. Currently the only
1866 such column is C<items.cn_sort>.
1870 sub _set_derived_columns_for_add {
1873 foreach my $column (keys %derived_columns) {
1874 my $builder = $derived_columns{$column}->{'BUILDER'};
1875 my $source_values = {};
1876 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1877 next if $source_column eq 'BUILDER';
1878 $source_values->{$source_column} = $item->{$source_column};
1880 $builder->($item, $source_values);
1884 =head2 _set_derived_columns_for_mod
1886 _set_derived_column_for_mod($item);
1888 Given an item hash representing a new item to be modified.
1889 calculate any derived columns. Currently the only
1890 such column is C<items.cn_sort>.
1892 This routine differs from C<_set_derived_columns_for_add>
1893 in that it needs to handle partial item records. In other
1894 words, the caller of C<ModItem> may have supplied only one
1895 or two columns to be changed, so this function needs to
1896 determine whether any of the columns to be changed affect
1897 any of the derived columns. Also, if a derived column
1898 depends on more than one column, but the caller is not
1899 changing all of then, this routine retrieves the unchanged
1900 values from the database in order to ensure a correct
1905 sub _set_derived_columns_for_mod {
1908 foreach my $column (keys %derived_columns) {
1909 my $builder = $derived_columns{$column}->{'BUILDER'};
1910 my $source_values = {};
1911 my %missing_sources = ();
1912 my $must_recalc = 0;
1913 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1914 next if $source_column eq 'BUILDER';
1915 if (exists $item->{$source_column}) {
1917 $source_values->{$source_column} = $item->{$source_column};
1919 $missing_sources{$source_column} = 1;
1923 foreach my $source_column (keys %missing_sources) {
1924 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1926 $builder->($item, $source_values);
1931 =head2 _do_column_fixes_for_mod
1933 _do_column_fixes_for_mod($item);
1935 Given an item hashref containing one or more
1936 columns to modify, fix up certain values.
1937 Specifically, set to 0 any passed value
1938 of C<notforloan>, C<damaged>, C<itemlost>, or
1939 C<wthdrawn> that is either undefined or
1940 contains the empty string.
1944 sub _do_column_fixes_for_mod {
1947 if (exists $item->{'notforloan'} and
1948 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1949 $item->{'notforloan'} = 0;
1951 if (exists $item->{'damaged'} and
1952 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1953 $item->{'damaged'} = 0;
1955 if (exists $item->{'itemlost'} and
1956 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1957 $item->{'itemlost'} = 0;
1959 if (exists $item->{'wthdrawn'} and
1960 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1961 $item->{'wthdrawn'} = 0;
1963 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1964 $item->{'permanent_location'} = $item->{'location'};
1966 if (exists $item->{'timestamp'}) {
1967 delete $item->{'timestamp'};
1971 =head2 _get_single_item_column
1973 _get_single_item_column($column, $itemnumber);
1975 Retrieves the value of a single column from an C<items>
1976 row specified by C<$itemnumber>.
1980 sub _get_single_item_column {
1982 my $itemnumber = shift;
1984 my $dbh = C4::Context->dbh;
1985 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1986 $sth->execute($itemnumber);
1987 my ($value) = $sth->fetchrow();
1991 =head2 _calc_items_cn_sort
1993 _calc_items_cn_sort($item, $source_values);
1995 Helper routine to calculate C<items.cn_sort>.
1999 sub _calc_items_cn_sort {
2001 my $source_values = shift;
2003 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2006 =head2 _set_defaults_for_add
2008 _set_defaults_for_add($item_hash);
2010 Given an item hash representing an item to be added, set
2011 correct default values for columns whose default value
2012 is not handled by the DBMS. This includes the following
2019 C<items.dateaccessioned>
2041 sub _set_defaults_for_add {
2043 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2044 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2047 =head2 _koha_new_item
2049 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2051 Perform the actual insert into the C<items> table.
2055 sub _koha_new_item {
2056 my ( $item, $barcode ) = @_;
2057 my $dbh=C4::Context->dbh;
2060 "INSERT INTO items SET
2062 biblioitemnumber = ?,
2064 dateaccessioned = ?,
2068 replacementprice = ?,
2069 replacementpricedate = ?,
2070 datelastborrowed = ?,
2083 permanent_location = ?,
2095 more_subfields_xml = ?,
2099 my $sth = $dbh->prepare($query);
2100 my $today = C4::Dates->today('iso');
2102 $item->{'biblionumber'},
2103 $item->{'biblioitemnumber'},
2105 $item->{'dateaccessioned'},
2106 $item->{'booksellerid'},
2107 $item->{'homebranch'},
2109 $item->{'replacementprice'},
2110 $item->{'replacementpricedate'} || $today,
2111 $item->{datelastborrowed},
2112 $item->{datelastseen} || $today,
2114 $item->{'notforloan'},
2116 $item->{'itemlost'},
2117 $item->{'wthdrawn'},
2118 $item->{'itemcallnumber'},
2119 $item->{'restricted'},
2120 $item->{'itemnotes'},
2121 $item->{'holdingbranch'},
2123 $item->{'location'},
2124 $item->{'permanent_location'},
2127 $item->{'renewals'},
2128 $item->{'reserves'},
2129 $item->{'items.cn_source'},
2130 $item->{'items.cn_sort'},
2133 $item->{'materials'},
2135 $item->{'enumchron'},
2136 $item->{'more_subfields_xml'},
2137 $item->{'copynumber'},
2138 $item->{'stocknumber'},
2142 if ( defined $sth->errstr ) {
2143 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2146 $itemnumber = $dbh->{'mysql_insertid'};
2149 return ( $itemnumber, $error );
2152 =head2 MoveItemFromBiblio
2154 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2156 Moves an item from a biblio to another
2158 Returns undef if the move failed or the biblionumber of the destination record otherwise
2162 sub MoveItemFromBiblio {
2163 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2164 my $dbh = C4::Context->dbh;
2165 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2166 $sth->execute( $tobiblio );
2167 my ( $tobiblioitem ) = $sth->fetchrow();
2168 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2169 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2171 ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2172 ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2173 # Checking if the item we want to move is in an order
2174 require C4::Acquisition;
2175 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2177 # Replacing the biblionumber within the order if necessary
2178 $order->{'biblionumber'} = $tobiblio;
2179 C4::Acquisition::ModOrder($order);
2188 DelItemCheck($dbh, $biblionumber, $itemnumber);
2190 Exported function (core API) for deleting an item record in Koha if there no current issue.
2195 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2198 my $countanalytics=GetAnalyticsCount($itemnumber);
2201 # check that there is no issue on this item before deletion.
2202 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2203 $sth->execute($itemnumber);
2205 my $item = GetItem($itemnumber);
2206 my $onloan=$sth->fetchrow;
2209 $error = "book_on_loan"
2211 elsif ( !(C4::Context->userenv->{flags} & 1) and
2212 C4::Context->preference("IndependantBranches") and
2213 (C4::Context->userenv->{branch} ne
2214 $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2216 $error = "not_same_branch";
2219 # check it doesnt have a waiting reserve
2220 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2221 $sth->execute($itemnumber);
2222 my $reserve=$sth->fetchrow;
2224 $error = "book_reserved";
2225 } elsif ($countanalytics > 0){
2226 $error = "linked_analytics";
2228 DelItem($dbh, $biblionumber, $itemnumber);
2235 =head2 _koha_modify_item
2237 my ($itemnumber,$error) =_koha_modify_item( $item );
2239 Perform the actual update of the C<items> row. Note that this
2240 routine accepts a hashref specifying the columns to update.
2244 sub _koha_modify_item {
2246 my $dbh=C4::Context->dbh;
2249 my $query = "UPDATE items SET ";
2251 for my $key ( keys %$item ) {
2253 push @bind, $item->{$key};
2256 $query .= " WHERE itemnumber=?";
2257 push @bind, $item->{'itemnumber'};
2258 my $sth = C4::Context->dbh->prepare($query);
2259 $sth->execute(@bind);
2260 if ( C4::Context->dbh->errstr ) {
2261 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2264 return ($item->{'itemnumber'},$error);
2267 =head2 _koha_delete_item
2269 _koha_delete_item( $dbh, $itemnum );
2271 Internal function to delete an item record from the koha tables
2275 sub _koha_delete_item {
2276 my ( $dbh, $itemnum ) = @_;
2278 # save the deleted item to deleteditems table
2279 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2280 $sth->execute($itemnum);
2281 my $data = $sth->fetchrow_hashref();
2282 my $query = "INSERT INTO deleteditems SET ";
2284 foreach my $key ( keys %$data ) {
2285 $query .= "$key = ?,";
2286 push( @bind, $data->{$key} );
2289 $sth = $dbh->prepare($query);
2290 $sth->execute(@bind);
2292 # delete from items table
2293 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2294 $sth->execute($itemnum);
2298 =head2 _marc_from_item_hash
2300 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2302 Given an item hash representing a complete item record,
2303 create a C<MARC::Record> object containing an embedded
2304 tag representing that item.
2306 The third, optional parameter C<$unlinked_item_subfields> is
2307 an arrayref of subfields (not mapped to C<items> fields per the
2308 framework) to be added to the MARC representation
2313 sub _marc_from_item_hash {
2315 my $frameworkcode = shift;
2316 my $unlinked_item_subfields;
2318 $unlinked_item_subfields = shift;
2321 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2322 # Also, don't emit a subfield if the underlying field is blank.
2323 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2324 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2325 : () } keys %{ $item } };
2327 my $item_marc = MARC::Record->new();
2328 foreach my $item_field ( keys %{$mungeditem} ) {
2329 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2330 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2331 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2332 foreach my $value (@values){
2333 if ( my $field = $item_marc->field($tag) ) {
2334 $field->add_subfields( $subfield => $value );
2336 my $add_subfields = [];
2337 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2338 $add_subfields = $unlinked_item_subfields;
2340 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2348 =head2 _repack_item_errors
2350 Add an error message hash generated by C<CheckItemPreSave>
2351 to a list of errors.
2355 sub _repack_item_errors {
2356 my $item_sequence_num = shift;
2357 my $item_ref = shift;
2358 my $error_ref = shift;
2360 my @repacked_errors = ();
2362 foreach my $error_code (sort keys %{ $error_ref }) {
2363 my $repacked_error = {};
2364 $repacked_error->{'item_sequence'} = $item_sequence_num;
2365 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2366 $repacked_error->{'error_code'} = $error_code;
2367 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2368 push @repacked_errors, $repacked_error;
2371 return @repacked_errors;
2374 =head2 _get_unlinked_item_subfields
2376 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2380 sub _get_unlinked_item_subfields {
2381 my $original_item_marc = shift;
2382 my $frameworkcode = shift;
2384 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2386 # assume that this record has only one field, and that that
2387 # field contains only the item information
2389 my @fields = $original_item_marc->fields();
2390 if ($#fields > -1) {
2391 my $field = $fields[0];
2392 my $tag = $field->tag();
2393 foreach my $subfield ($field->subfields()) {
2394 if (defined $subfield->[1] and
2395 $subfield->[1] ne '' and
2396 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2397 push @$subfields, $subfield->[0] => $subfield->[1];
2404 =head2 _get_unlinked_subfields_xml
2406 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2410 sub _get_unlinked_subfields_xml {
2411 my $unlinked_item_subfields = shift;
2414 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2415 my $marc = MARC::Record->new();
2416 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2417 # used in the framework
2418 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2419 $marc->encoding("UTF-8");
2420 $xml = $marc->as_xml("USMARC");
2426 =head2 _parse_unlinked_item_subfields_from_xml
2428 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2432 sub _parse_unlinked_item_subfields_from_xml {
2434 require C4::Charset;
2435 return unless defined $xml and $xml ne "";
2436 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2437 my $unlinked_subfields = [];
2438 my @fields = $marc->fields();
2439 if ($#fields > -1) {
2440 foreach my $subfield ($fields[0]->subfields()) {
2441 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2444 return $unlinked_subfields;
2447 =head2 GetAnalyticsCount
2449 $count= &GetAnalyticsCount($itemnumber)
2451 counts Usage of itemnumber in Analytical bibliorecords.
2455 sub GetAnalyticsCount {
2456 my ($itemnumber) = @_;
2457 if (C4::Context->preference('NoZebra')) {
2458 # Read the index Koha-Auth-Number for this authid and count the lines
2459 my $result = C4::Search::NZanalyse("hi=$itemnumber");
2460 my @tab = split /;/,$result;
2463 ### ZOOM search here
2465 $query= "hi=".$itemnumber;
2466 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2474 $holds = &GetItemHolds($biblionumber, $itemnumber);
2478 This function return the count of holds with $biblionumber and $itemnumber
2483 my ($biblionumber, $itemnumber) = @_;
2485 my $dbh = C4::Context->dbh;
2486 my $query = "SELECT count(*)
2488 WHERE biblionumber=? AND itemnumber=?";
2489 my $sth = $dbh->prepare($query);
2490 $sth->execute($biblionumber, $itemnumber);
2491 $holds = $sth->fetchrow;
2494 =head1 OTHER FUNCTIONS
2498 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2500 Find the given $subfield in the given $tag in the given
2501 MARC::Record $record. If the subfield is found, returns
2502 the (indicators, value) pair; otherwise, (undef, undef) is
2506 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2507 I suggest we export it from this module.
2512 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2515 if ( $tagfield < 10 ) {
2516 if ( $record->field($tagfield) ) {
2517 push @result, $record->field($tagfield)->data();
2522 foreach my $field ( $record->field($tagfield) ) {
2523 my @subfields = $field->subfields();
2524 foreach my $subfield (@subfields) {
2525 if ( @$subfield[0] eq $insubfield ) {
2526 push @result, @$subfield[1];
2527 $indicator = $field->indicator(1) . $field->indicator(2);
2532 return ( $indicator, @result );
2536 =head2 PrepareItemrecordDisplay
2538 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2540 Returns a hash with all the fields for Display a given item data in a template
2542 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2546 sub PrepareItemrecordDisplay {
2548 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2550 my $dbh = C4::Context->dbh;
2551 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2552 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2553 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2555 # return nothing if we don't have found an existing framework.
2556 return q{} unless $tagslib;
2559 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2562 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2563 foreach my $tag ( sort keys %{$tagslib} ) {
2564 my $previous_tag = '';
2567 # loop through each subfield
2569 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2570 next if ( subfield_is_koha_internal_p($subfield) );
2571 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2573 $subfield_data{tag} = $tag;
2574 $subfield_data{subfield} = $subfield;
2575 $subfield_data{countsubfield} = $cntsubf++;
2576 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2578 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2579 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2580 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2581 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2582 $subfield_data{hidden} = "display:none"
2583 if $tagslib->{$tag}->{$subfield}->{hidden};
2584 my ( $x, $defaultvalue );
2586 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2588 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2589 if ( !defined $defaultvalue ) {
2590 $defaultvalue = q||;
2592 $defaultvalue =~ s/"/"/g;
2594 # search for itemcallnumber if applicable
2595 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2596 && C4::Context->preference('itemcallnumber') ) {
2597 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2598 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2600 my $temp = $itemrecord->field($CNtag);
2602 $defaultvalue = $temp->subfield($CNsubfield);
2606 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2608 && $defaultvalues->{'callnumber'} ) {
2611 $temp = $itemrecord->field($subfield);
2614 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2617 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2619 && $defaultvalues->{'branchcode'} ) {
2622 $temp = $itemrecord->field($subfield);
2625 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2628 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2630 && $defaultvalues->{'location'} ) {
2631 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2633 $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2636 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2637 my @authorised_values;
2640 # builds list, depending on authorised value...
2642 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2643 if ( ( C4::Context->preference("IndependantBranches") )
2644 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2645 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2646 $sth->execute( C4::Context->userenv->{branch} );
2647 push @authorised_values, ""
2648 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2649 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2650 push @authorised_values, $branchcode;
2651 $authorised_lib{$branchcode} = $branchname;
2654 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2656 push @authorised_values, ""
2657 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2658 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2659 push @authorised_values, $branchcode;
2660 $authorised_lib{$branchcode} = $branchname;
2665 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2666 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2668 push @authorised_values, ""
2669 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2670 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2671 push @authorised_values, $itemtype;
2672 $authorised_lib{$itemtype} = $description;
2675 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2676 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2678 my $class_sources = GetClassSources();
2679 my $default_source = C4::Context->preference("DefaultClassificationSource");
2681 foreach my $class_source (sort keys %$class_sources) {
2682 next unless $class_sources->{$class_source}->{'used'} or
2683 ($class_source eq $default_source);
2684 push @authorised_values, $class_source;
2685 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2688 #---- "true" authorised value
2690 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2691 push @authorised_values, ""
2692 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2693 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2694 push @authorised_values, $value;
2695 $authorised_lib{$value} = $lib;
2698 $subfield_data{marc_value} = CGI::scrolling_list(
2699 -name => 'field_value',
2700 -values => \@authorised_values,
2701 -default => "$defaultvalue",
2702 -labels => \%authorised_lib,
2707 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2709 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2712 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2713 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2714 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2715 my $index_subfield = int(rand(1000000));
2716 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
2717 $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
2718 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2719 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2720 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2723 warn "Plugin Failed: $plugin";
2724 $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
2727 elsif ( $tag eq '' ) { # it's an hidden field
2728 $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" />);
2730 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2731 $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" />);
2733 elsif ( length($defaultvalue) > 100
2734 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2735 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2736 or (C4::Context->preference("marcflavour") eq "MARC21" and
2737 500 <= $tag && $tag < 600 )
2739 # oversize field (textarea)
2740 $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");
2742 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2744 push( @loop_data, \%subfield_data );
2749 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2750 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2753 'itemtagfield' => $itemtagfield,
2754 'itemtagsubfield' => $itemtagsubfield,
2755 'itemnumber' => $itemnumber,
2756 'iteminformation' => \@loop_data