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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use vars qw(@ISA @EXPORT);
42 get_hostitemnumbers_of
50 PrepareItemrecordDisplay
63 use List::MoreUtils qw(any);
65 use DateTime::Format::MySQL;
66 use Data::Dumper; # used as part of logging item record changes, not just for
67 # debugging; so please don't remove this
69 use Koha::AuthorisedValues;
70 use Koha::DateUtils qw(dt_from_string);
73 use Koha::Biblioitems;
76 use Koha::SearchEngine;
77 use Koha::SearchEngine::Search;
82 C4::Items - item management functions
86 This module contains an API for manipulating item
87 records in Koha, and is used by cataloguing, circulation,
88 acquisitions, and serials management.
90 # FIXME This POD is not up-to-date
91 A Koha item record is stored in two places: the
92 items table and embedded in a MARC tag in the XML
93 version of the associated bib record in C<biblioitems.marcxml>.
94 This is done to allow the item information to be readily
95 indexed (e.g., by Zebra), but means that each item
96 modification transaction must keep the items table
97 and the MARC XML in sync at all times.
99 The items table will be considered authoritative. In other
100 words, if there is ever a discrepancy between the items
101 table and the MARC XML, the items table should be considered
104 =head1 HISTORICAL NOTE
106 Most of the functions in C<C4::Items> were originally in
107 the C<C4::Biblio> module.
109 =head1 CORE EXPORTED FUNCTIONS
111 The following functions are meant for use by users
118 CartToShelf($itemnumber);
120 Set the current shelving location of the item record
121 to its stored permanent shelving location. This is
122 primarily used to indicate when an item whose current
123 location is a special processing ('PROC') or shelving cart
124 ('CART') location is back in the stacks.
129 my ( $itemnumber ) = @_;
131 unless ( $itemnumber ) {
132 croak "FAILED CartToShelf() - no itemnumber supplied";
135 my $item = Koha::Items->find($itemnumber);
136 if ( $item->location eq 'CART' ) {
137 $item->location($item->permanent_location)->store;
141 =head2 AddItemFromMarc
143 my ($biblionumber, $biblioitemnumber, $itemnumber)
144 = AddItemFromMarc($source_item_marc, $biblionumber);
146 Given a MARC::Record object containing an embedded item
147 record and a biblionumber, create a new item record.
151 sub AddItemFromMarc {
152 my ( $source_item_marc, $biblionumber ) = @_;
153 my $dbh = C4::Context->dbh;
155 # parse item hash from MARC
156 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
157 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
159 my $localitemmarc = MARC::Record->new;
160 $localitemmarc->append_fields( $source_item_marc->field($itemtag) );
162 my $item_values = C4::Biblio::TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
163 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
164 $item_values->{more_subfields_xml} = _get_unlinked_subfields_xml($unlinked_item_subfields);
165 $item_values->{biblionumber} = $biblionumber;
166 my $item = Koha::Item->new( $item_values )->store;
167 return ( $item->biblionumber, $item->biblioitemnumber, $item->itemnumber );
170 =head2 AddItemBatchFromMarc
172 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
173 $biblionumber, $biblioitemnumber, $frameworkcode);
175 Efficiently create item records from a MARC biblio record with
176 embedded item fields. This routine is suitable for batch jobs.
178 This API assumes that the bib record has already been
179 saved to the C<biblio> and C<biblioitems> tables. It does
180 not expect that C<biblio_metadata.metadata> is populated, but it
181 will do so via a call to ModBibiloMarc.
183 The goal of this API is to have a similar effect to using AddBiblio
184 and AddItems in succession, but without inefficient repeated
185 parsing of the MARC XML bib record.
187 This function returns an arrayref of new itemsnumbers and an arrayref of item
188 errors encountered during the processing. Each entry in the errors
189 list is a hashref containing the following keys:
195 Sequence number of original item tag in the MARC record.
199 Item barcode, provide to assist in the construction of
200 useful error messages.
204 Code representing the error condition. Can be 'duplicate_barcode',
205 'invalid_homebranch', or 'invalid_holdingbranch'.
207 =item error_information
209 Additional information appropriate to the error condition.
215 sub AddItemBatchFromMarc {
216 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
218 my @itemnumbers = ();
220 my $dbh = C4::Context->dbh;
222 # We modify the record, so lets work on a clone so we don't change the
224 $record = $record->clone();
225 # loop through the item tags and start creating items
226 my @bad_item_fields = ();
227 my ($itemtag, $itemsubfield) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
228 my $item_sequence_num = 0;
229 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
230 $item_sequence_num++;
231 # we take the item field and stick it into a new
232 # MARC record -- this is required so far because (FIXME)
233 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
234 # and there is no TransformMarcFieldToKoha
235 my $temp_item_marc = MARC::Record->new();
236 $temp_item_marc->append_fields($item_field);
238 # add biblionumber and biblioitemnumber
239 my $item = TransformMarcToKoha( $temp_item_marc, $frameworkcode, 'items' );
240 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
241 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
242 $item->{'biblionumber'} = $biblionumber;
243 $item->{'biblioitemnumber'} = $biblioitemnumber;
245 # check for duplicate barcode
246 my %item_errors = CheckItemPreSave($item);
248 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
249 push @bad_item_fields, $item_field;
253 _set_derived_columns_for_add($item);
254 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
255 warn $error if $error;
256 push @itemnumbers, $itemnumber; # FIXME not checking error
257 $item->{'itemnumber'} = $itemnumber;
259 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
261 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
262 $item_field->replace_with($new_item_marc->field($itemtag));
265 # remove any MARC item fields for rejected items
266 foreach my $item_field (@bad_item_fields) {
267 $record->delete_field($item_field);
270 # update the MARC biblio
271 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
273 return (\@itemnumbers, \@errors);
276 =head2 ModItemFromMarc
278 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
280 This function updates an item record based on a supplied
281 C<MARC::Record> object containing an embedded item field.
282 This API is meant for the use of C<additem.pl>; for
283 other purposes, C<ModItem> should be used.
285 This function uses the hash %default_values_for_mod_from_marc,
286 which contains default values for item fields to
287 apply when modifying an item. This is needed because
288 if an item field's value is cleared, TransformMarcToKoha
289 does not include the column in the
290 hash that's passed to ModItem, which without
291 use of this hash makes it impossible to clear
292 an item field's value. See bug 2466.
294 Note that only columns that can be directly
295 changed from the cataloging and serials
296 item editors are included in this hash.
302 sub _build_default_values_for_mod_marc {
303 # Has no framework parameter anymore, since Default is authoritative
304 # for Koha to MARC mappings.
306 my $cache = Koha::Caches->get_instance();
307 my $cache_key = "default_value_for_mod_marc-";
308 my $cached = $cache->get_from_cache($cache_key);
309 return $cached if $cached;
311 my $default_values = {
313 booksellerid => undef,
315 'items.cn_source' => undef,
316 coded_location_qualifier => undef,
320 holdingbranch => undef,
322 itemcallnumber => undef,
325 itemnotes_nonpublic => undef,
328 permanent_location => undef,
333 replacementprice => undef,
334 replacementpricedate => undef,
337 stocknumber => undef,
341 my %default_values_for_mod_from_marc;
342 while ( my ( $field, $default_value ) = each %$default_values ) {
343 my $kohafield = $field;
344 $kohafield =~ s|^([^\.]+)$|items.$1|;
345 $default_values_for_mod_from_marc{$field} = $default_value
346 if C4::Biblio::GetMarcFromKohaField( $kohafield );
349 $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
350 return \%default_values_for_mod_from_marc;
353 sub ModItemFromMarc {
354 my $item_marc = shift;
355 my $biblionumber = shift;
356 my $itemnumber = shift;
358 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
359 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
361 my $localitemmarc = MARC::Record->new;
362 $localitemmarc->append_fields( $item_marc->field($itemtag) );
363 my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
364 my $default_values = _build_default_values_for_mod_marc();
365 foreach my $item_field ( keys %$default_values ) {
366 $item->{$item_field} = $default_values->{$item_field}
367 unless exists $item->{$item_field};
369 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
371 my $item_object = Koha::Items->find($itemnumber);
372 $item_object->more_subfields_xml(_get_unlinked_subfields_xml($unlinked_item_subfields))->store;
374 return $item_object->get_from_storage->unblessed;
380 { column => $newvalue },
384 [ unlinked_item_subfields => $unlinked_item_subfields, ]
389 Change one or more columns in an item record.
391 The first argument is a hashref mapping from item column
392 names to the new values. The second and third arguments
393 are the biblionumber and itemnumber, respectively.
394 The fourth, optional parameter (additional_params) may contain the keys
395 unlinked_item_subfields and log_action.
397 C<$unlinked_item_subfields> contains an arrayref containing
398 subfields present in the original MARC
399 representation of the item (e.g., from the item editor) that are
400 not mapped to C<items> columns directly but should instead
401 be stored in C<items.more_subfields_xml> and included in
402 the biblio items tag for display and indexing.
404 If one of the changed columns is used to calculate
405 the derived value of a column such as C<items.cn_sort>,
406 this routine will perform the necessary calculation
409 If log_action is set to false, the action will not be logged.
410 If log_action is true or undefined, the action will be logged.
415 my ( $item, $biblionumber, $itemnumber, $additional_params ) = @_;
416 my $log_action = $additional_params->{log_action} // 1;
418 _set_derived_columns_for_mod($item);
419 _do_column_fixes_for_mod($item);
422 # attempt to change itemnumber
423 # attempt to change biblionumber (if we want
424 # an API to relink an item to a different bib,
425 # it should be a separate function)
428 _koha_modify_item($item);
430 # request that bib be reindexed so that searching on current
431 # item status is possible
432 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
434 _after_item_action_hooks({ action => 'modify', item_id => $itemnumber });
436 logaction( "CATALOGUING", "MODIFY", $itemnumber, "item " . Dumper($item) )
437 if $log_action && C4::Context->preference("CataloguingLog");
440 =head2 ModItemTransfer
442 ModItemTransfer($itemnumber, $frombranch, $tobranch, $trigger);
444 Marks an item as being transferred from one branch to another and records the trigger.
448 sub ModItemTransfer {
449 my ( $itemnumber, $frombranch, $tobranch, $trigger ) = @_;
451 my $dbh = C4::Context->dbh;
452 my $item = Koha::Items->find( $itemnumber );
454 # Remove the 'shelving cart' location status if it is being used.
455 CartToShelf( $itemnumber ) if $item->location && $item->location eq 'CART' && ( !$item->permanent_location || $item->permanent_location ne 'CART' );
457 $dbh->do("UPDATE branchtransfers SET datearrived = NOW(), comments = ? WHERE itemnumber = ? AND datearrived IS NULL", undef, "Canceled, new transfer from $frombranch to $tobranch created", $itemnumber);
459 #new entry in branchtransfers....
460 my $sth = $dbh->prepare(
461 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch, reason)
462 VALUES (?, ?, NOW(), ?, ?)");
463 $sth->execute($itemnumber, $frombranch, $tobranch, $trigger);
465 # FIXME we are fetching the item twice in the 2 next statements!
466 Koha::Items->find($itemnumber)->holdingbranch($frombranch)->store({ log_action => 0 });
467 ModDateLastSeen($itemnumber);
471 =head2 ModDateLastSeen
473 ModDateLastSeen( $itemnumber, $leave_item_lost );
475 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
476 C<$itemnumber> is the item number
477 C<$leave_item_lost> determines if a lost item will be found or remain lost
481 sub ModDateLastSeen {
482 my ( $itemnumber, $leave_item_lost ) = @_;
484 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
486 my $item = Koha::Items->find($itemnumber);
487 $item->datelastseen($today);
488 $item->itemlost(0) unless $leave_item_lost;
489 $item->store({ log_action => 0 });
494 DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
496 Exported function (core API) for deleting an item record in Koha.
503 my $itemnumber = $params->{itemnumber};
504 my $biblionumber = $params->{biblionumber};
506 unless ($biblionumber) {
507 my $item = Koha::Items->find( $itemnumber );
508 $biblionumber = $item ? $item->biblio->biblionumber : undef;
511 # If there is no biblionumber for the given itemnumber, there is nothing to delete
512 return 0 unless $biblionumber;
514 # FIXME check the item has no current issues
515 my $deleted = _koha_delete_item( $itemnumber );
517 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
519 _after_item_action_hooks({ action => 'delete', item_id => $itemnumber });
521 #search item field code
522 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
526 =head2 CheckItemPreSave
528 my $item_ref = TransformMarcToKoha($marc, 'items');
530 my %errors = CheckItemPreSave($item_ref);
531 if (exists $errors{'duplicate_barcode'}) {
532 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
533 } elsif (exists $errors{'invalid_homebranch'}) {
534 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
535 } elsif (exists $errors{'invalid_holdingbranch'}) {
536 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
541 Given a hashref containing item fields, determine if it can be
542 inserted or updated in the database. Specifically, checks for
543 database integrity issues, and returns a hash containing any
544 of the following keys, if applicable.
548 =item duplicate_barcode
550 Barcode, if it duplicates one already found in the database.
552 =item invalid_homebranch
554 Home branch, if not defined in branches table.
556 =item invalid_holdingbranch
558 Holding branch, if not defined in branches table.
562 This function does NOT implement any policy-related checks,
563 e.g., whether current operator is allowed to save an
564 item that has a given branch code.
568 sub CheckItemPreSave {
569 my $item_ref = shift;
573 # check for duplicate barcode
574 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
575 my $existing_item= Koha::Items->find({barcode => $item_ref->{'barcode'}});
576 if ($existing_item) {
577 if (!exists $item_ref->{'itemnumber'} # new item
578 or $item_ref->{'itemnumber'} != $existing_item->itemnumber) { # existing item
579 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
584 # check for valid home branch
585 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
586 my $home_library = Koha::Libraries->find( $item_ref->{homebranch} );
587 unless (defined $home_library) {
588 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
592 # check for valid holding branch
593 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
594 my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} );
595 unless (defined $holding_library) {
596 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
604 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
606 The following functions provide various ways of
607 getting an item record, a set of item records, or
608 lists of authorized values for certain item fields.
612 =head2 GetItemsForInventory
614 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
615 minlocation => $minlocation,
616 maxlocation => $maxlocation,
617 location => $location,
618 itemtype => $itemtype,
619 ignoreissued => $ignoreissued,
620 datelastseen => $datelastseen,
621 branchcode => $branchcode,
625 statushash => $statushash,
628 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
630 The sub returns a reference to a list of hashes, each containing
631 itemnumber, author, title, barcode, item callnumber, and date last
632 seen. It is ordered by callnumber then title.
634 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
635 the datelastseen can be used to specify that you want to see items not seen since a past date only.
636 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
637 $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.
639 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
643 sub GetItemsForInventory {
644 my ( $parameters ) = @_;
645 my $minlocation = $parameters->{'minlocation'} // '';
646 my $maxlocation = $parameters->{'maxlocation'} // '';
647 my $class_source = $parameters->{'class_source'} // C4::Context->preference('DefaultClassificationSource');
648 my $location = $parameters->{'location'} // '';
649 my $itemtype = $parameters->{'itemtype'} // '';
650 my $ignoreissued = $parameters->{'ignoreissued'} // '';
651 my $datelastseen = $parameters->{'datelastseen'} // '';
652 my $branchcode = $parameters->{'branchcode'} // '';
653 my $branch = $parameters->{'branch'} // '';
654 my $offset = $parameters->{'offset'} // '';
655 my $size = $parameters->{'size'} // '';
656 my $statushash = $parameters->{'statushash'} // '';
657 my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // '';
659 my $dbh = C4::Context->dbh;
660 my ( @bind_params, @where_strings );
662 my $min_cnsort = GetClassSort($class_source,undef,$minlocation);
663 my $max_cnsort = GetClassSort($class_source,undef,$maxlocation);
665 my $select_columns = q{
666 SELECT DISTINCT(items.itemnumber), barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber, items.cn_sort
668 my $select_count = q{SELECT COUNT(DISTINCT(items.itemnumber))};
671 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
672 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
675 for my $authvfield (keys %$statushash){
676 if ( scalar @{$statushash->{$authvfield}} > 0 ){
677 my $joinedvals = join ',', @{$statushash->{$authvfield}};
678 push @where_strings, "$authvfield in (" . $joinedvals . ")";
684 push @where_strings, 'items.cn_sort >= ?';
685 push @bind_params, $min_cnsort;
689 push @where_strings, 'items.cn_sort <= ?';
690 push @bind_params, $max_cnsort;
694 $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
695 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
696 push @bind_params, $datelastseen;
700 push @where_strings, 'items.location = ?';
701 push @bind_params, $location;
705 if($branch eq "homebranch"){
706 push @where_strings, 'items.homebranch = ?';
708 push @where_strings, 'items.holdingbranch = ?';
710 push @bind_params, $branchcode;
714 push @where_strings, 'biblioitems.itemtype = ?';
715 push @bind_params, $itemtype;
718 if ( $ignoreissued) {
719 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
720 push @where_strings, 'issues.date_due IS NULL';
723 if ( $ignore_waiting_holds ) {
724 $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber ";
725 push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} );
728 if ( @where_strings ) {
730 $query .= join ' AND ', @where_strings;
732 my $count_query = $select_count . $query;
733 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
734 $query .= " LIMIT $offset, $size" if ($offset and $size);
735 $query = $select_columns . $query;
736 my $sth = $dbh->prepare($query);
737 $sth->execute( @bind_params );
740 my $tmpresults = $sth->fetchall_arrayref({});
741 $sth = $dbh->prepare( $count_query );
742 $sth->execute( @bind_params );
743 my ($iTotalRecords) = $sth->fetchrow_array();
745 my @avs = Koha::AuthorisedValues->search(
746 { 'marc_subfield_structures.kohafield' => { '>' => '' },
747 'me.authorised_value' => { '>' => '' },
749 { join => { category => 'marc_subfield_structures' },
750 distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'],
751 '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ],
752 '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ],
756 my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
758 foreach my $row (@$tmpresults) {
761 foreach (keys %$row) {
764 $avmapping->{ "items.$_," . $row->{'frameworkcode'} . "," . ( $row->{$_} // q{} ) }
767 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
773 return (\@results, $iTotalRecords);
778 @results = GetItemsInfo($biblionumber);
780 Returns information about items with the given biblionumber.
782 C<GetItemsInfo> returns a list of references-to-hash. Each element
783 contains a number of keys. Most of them are attributes from the
784 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
785 Koha database. Other keys include:
789 =item C<$data-E<gt>{branchname}>
791 The name (not the code) of the branch to which the book belongs.
793 =item C<$data-E<gt>{datelastseen}>
795 This is simply C<items.datelastseen>, except that while the date is
796 stored in YYYY-MM-DD format in the database, here it is converted to
797 DD/MM/YYYY format. A NULL date is returned as C<//>.
799 =item C<$data-E<gt>{datedue}>
801 =item C<$data-E<gt>{class}>
803 This is the concatenation of C<biblioitems.classification>, the book's
804 Dewey code, and C<biblioitems.subclass>.
806 =item C<$data-E<gt>{ocount}>
808 I think this is the number of copies of the book available.
810 =item C<$data-E<gt>{order}>
812 If this is set, it is set to C<One Order>.
819 my ( $biblionumber ) = @_;
820 my $dbh = C4::Context->dbh;
821 require C4::Languages;
822 my $language = C4::Languages::getlanguage();
828 biblioitems.itemtype,
831 biblioitems.publicationyear,
832 biblioitems.publishercode,
833 biblioitems.volumedate,
834 biblioitems.volumedesc,
837 items.notforloan as itemnotforloan,
838 issues.borrowernumber,
839 issues.date_due as datedue,
840 issues.onsite_checkout,
841 borrowers.cardnumber,
844 borrowers.branchcode as bcode,
846 serial.publisheddate,
847 itemtypes.description,
848 COALESCE( localization.translation, itemtypes.description ) AS translated_description,
849 itemtypes.notforloan as notforloan_per_itemtype,
853 holding.opac_info as holding_branch_opac_info,
854 home.opac_info as home_branch_opac_info,
855 IF(tmp_holdsqueue.itemnumber,1,0) AS has_pending_hold
857 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
858 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
859 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
860 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
861 LEFT JOIN issues USING (itemnumber)
862 LEFT JOIN borrowers USING (borrowernumber)
863 LEFT JOIN serialitems USING (itemnumber)
864 LEFT JOIN serial USING (serialid)
865 LEFT JOIN itemtypes ON itemtypes.itemtype = "
866 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
868 LEFT JOIN tmp_holdsqueue USING (itemnumber)
869 LEFT JOIN localization ON itemtypes.itemtype = localization.code
870 AND localization.entity = 'itemtypes'
871 AND localization.lang = ?
874 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
875 my $sth = $dbh->prepare($query);
876 $sth->execute($language, $biblionumber);
881 my $userenv = C4::Context->userenv;
882 my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
883 while ( my $data = $sth->fetchrow_hashref ) {
884 if ( $data->{borrowernumber} && $want_not_same_branch) {
885 $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
888 $serial ||= $data->{'serial'};
891 # get notforloan complete status if applicable
892 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.notforloan', authorised_value => $data->{itemnotforloan} });
893 $data->{notforloanvalue} = $descriptions->{lib} // '';
894 $data->{notforloanvalueopac} = $descriptions->{opac_description} // '';
896 # get restricted status and description if applicable
897 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
898 $data->{restrictedvalue} = $descriptions->{lib} // '';
899 $data->{restrictedvalueopac} = $descriptions->{opac_description} // '';
901 # my stack procedures
902 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
903 $data->{stack} = $descriptions->{lib} // '';
905 # Find the last 3 people who borrowed this item.
906 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
908 AND old_issues.borrowernumber = borrowers.borrowernumber
909 ORDER BY returndate DESC
911 $sth2->execute($data->{'itemnumber'});
913 while (my $data2 = $sth2->fetchrow_hashref()) {
914 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
915 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
916 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
920 $results[$i] = $data;
925 ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
929 =head2 GetItemsLocationInfo
931 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
933 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
935 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
939 =item C<$data-E<gt>{homebranch}>
941 Branch Name of the item's homebranch
943 =item C<$data-E<gt>{holdingbranch}>
945 Branch Name of the item's holdingbranch
947 =item C<$data-E<gt>{location}>
949 Item's shelving location code
951 =item C<$data-E<gt>{location_intranet}>
953 The intranet description for the Shelving Location as set in authorised_values 'LOC'
955 =item C<$data-E<gt>{location_opac}>
957 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
960 =item C<$data-E<gt>{itemcallnumber}>
962 Item's itemcallnumber
964 =item C<$data-E<gt>{cn_sort}>
966 Item's call number normalized for sorting
972 sub GetItemsLocationInfo {
973 my $biblionumber = shift;
976 my $dbh = C4::Context->dbh;
977 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
978 location, itemcallnumber, cn_sort
979 FROM items, branches as a, branches as b
980 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
982 ORDER BY cn_sort ASC";
983 my $sth = $dbh->prepare($query);
984 $sth->execute($biblionumber);
986 while ( my $data = $sth->fetchrow_hashref ) {
987 my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $data->{location} });
988 $av = $av->count ? $av->next : undef;
989 $data->{location_intranet} = $av ? $av->lib : '';
990 $data->{location_opac} = $av ? $av->opac_description : '';
991 push @results, $data;
996 =head2 GetHostItemsInfo
998 $hostiteminfo = GetHostItemsInfo($hostfield);
999 Returns the iteminfo for items linked to records via a host field
1003 sub GetHostItemsInfo {
1005 my @returnitemsInfo;
1007 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1008 return @returnitemsInfo;
1012 if( C4::Context->preference('marcflavour') eq 'MARC21' ||
1013 C4::Context->preference('marcflavour') eq 'NORMARC') {
1014 @fields = $record->field('773');
1015 } elsif( C4::Context->preference('marcflavour') eq 'UNIMARC') {
1016 @fields = $record->field('461');
1019 foreach my $hostfield ( @fields ) {
1020 my $hostbiblionumber = $hostfield->subfield("0");
1021 my $linkeditemnumber = $hostfield->subfield("9");
1022 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1023 foreach my $hostitemInfo (@hostitemInfos) {
1024 if( $hostitemInfo->{itemnumber} eq $linkeditemnumber ) {
1025 push @returnitemsInfo, $hostitemInfo;
1030 return @returnitemsInfo;
1033 =head2 get_hostitemnumbers_of
1035 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1037 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1039 Return a reference on a hash where key is a biblionumber and values are
1040 references on array of itemnumbers.
1045 sub get_hostitemnumbers_of {
1046 my ($biblionumber) = @_;
1048 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1052 my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
1053 return unless $marcrecord;
1055 my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
1057 my $marcflavor = C4::Context->preference('marcflavour');
1058 if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
1063 elsif ( $marcflavor eq 'UNIMARC' ) {
1069 foreach my $hostfield ( $marcrecord->field($tag) ) {
1070 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1071 next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield
1072 my $linkeditemnumber = $hostfield->subfield($item_s);
1073 if ( ! $linkeditemnumber ) {
1074 warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9";
1077 my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber });
1078 push @returnhostitemnumbers, $linkeditemnumber
1082 return @returnhostitemnumbers;
1085 =head2 GetHiddenItemnumbers
1087 my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
1089 Given a list of items it checks which should be hidden from the OPAC given
1090 the current configuration. Returns a list of itemnumbers corresponding to
1091 those that should be hidden. Optionally takes a borcat parameter for certain borrower types
1096 sub GetHiddenItemnumbers {
1098 my $items = $params->{items};
1099 if (my $exceptions = C4::Context->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
1100 foreach my $except (split(/\|/, $exceptions)){
1101 if ($params->{'borcat'} eq $except){
1102 return; # we don't hide anything for this borrower category
1108 my $yaml = C4::Context->preference('OpacHiddenItems');
1109 return () if (! $yaml =~ /\S/ );
1110 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1113 $hidingrules = YAML::Load($yaml);
1116 warn "Unable to parse OpacHiddenItems syspref : $@";
1119 my $dbh = C4::Context->dbh;
1122 foreach my $item (@$items) {
1124 # We check each rule
1125 foreach my $field (keys %$hidingrules) {
1127 if (exists $item->{$field}) {
1128 $val = $item->{$field};
1131 my $query = "SELECT $field from items where itemnumber = ?";
1132 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1134 $val = '' unless defined $val;
1136 # If the results matches the values in the yaml file
1137 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1139 # We add the itemnumber to the list
1140 push @resultitems, $item->{'itemnumber'};
1142 # If at least one rule matched for an item, no need to test the others
1147 return @resultitems;
1150 =head1 LIMITED USE FUNCTIONS
1152 The following functions, while part of the public API,
1153 are not exported. This is generally because they are
1154 meant to be used by only one script for a specific
1155 purpose, and should not be used in any other context
1156 without careful thought.
1162 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1164 Returns MARC::Record of the item passed in parameter.
1165 This function is meant for use only in C<cataloguing/additem.pl>,
1166 where it is needed to support that script's MARC-like
1172 my ( $biblionumber, $itemnumber ) = @_;
1174 # GetMarcItem has been revised so that it does the following:
1175 # 1. Gets the item information from the items table.
1176 # 2. Converts it to a MARC field for storage in the bib record.
1178 # The previous behavior was:
1179 # 1. Get the bib record.
1180 # 2. Return the MARC tag corresponding to the item record.
1182 # The difference is that one treats the items row as authoritative,
1183 # while the other treats the MARC representation as authoritative
1184 # under certain circumstances.
1186 my $item = Koha::Items->find($itemnumber) or return;
1188 # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
1189 # Also, don't emit a subfield if the underlying field is blank.
1191 return Item2Marc($item->unblessed, $biblionumber);
1195 my ($itemrecord,$biblionumber)=@_;
1198 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1199 } keys %{ $itemrecord }
1201 my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
1202 my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem ); # Bug 21774: no_split parameter removed to allow cloned subfields
1203 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
1204 "items.itemnumber", $framework,
1207 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1208 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1209 foreach my $field ($itemmarc->field($itemtag)){
1210 $field->add_subfields(@$unlinked_item_subfields);
1216 =head1 PRIVATE FUNCTIONS AND VARIABLES
1218 The following functions are not meant to be called
1219 directly, but are documented in order to explain
1220 the inner workings of C<C4::Items>.
1224 =head2 %derived_columns
1226 This hash keeps track of item columns that
1227 are strictly derived from other columns in
1228 the item record and are not meant to be set
1231 Each key in the hash should be the name of a
1232 column (as named by TransformMarcToKoha). Each
1233 value should be hashref whose keys are the
1234 columns on which the derived column depends. The
1235 hashref should also contain a 'BUILDER' key
1236 that is a reference to a sub that calculates
1241 my %derived_columns = (
1242 'items.cn_sort' => {
1243 'itemcallnumber' => 1,
1244 'items.cn_source' => 1,
1245 'BUILDER' => \&_calc_items_cn_sort,
1249 =head2 _set_derived_columns_for_add
1251 _set_derived_column_for_add($item);
1253 Given an item hash representing a new item to be added,
1254 calculate any derived columns. Currently the only
1255 such column is C<items.cn_sort>.
1259 sub _set_derived_columns_for_add {
1262 foreach my $column (keys %derived_columns) {
1263 my $builder = $derived_columns{$column}->{'BUILDER'};
1264 my $source_values = {};
1265 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1266 next if $source_column eq 'BUILDER';
1267 $source_values->{$source_column} = $item->{$source_column};
1269 $builder->($item, $source_values);
1273 =head2 _do_column_fixes_for_mod
1275 _do_column_fixes_for_mod($item);
1277 Given an item hashref containing one or more
1278 columns to modify, fix up certain values.
1279 Specifically, set to 0 any passed value
1280 of C<notforloan>, C<damaged>, C<itemlost>, or
1281 C<withdrawn> that is either undefined or
1282 contains the empty string.
1286 sub _do_column_fixes_for_mod {
1289 if (exists $item->{'notforloan'} and
1290 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1291 $item->{'notforloan'} = 0;
1293 if (exists $item->{'damaged'} and
1294 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1295 $item->{'damaged'} = 0;
1297 if (exists $item->{'itemlost'} and
1298 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1299 $item->{'itemlost'} = 0;
1301 if (exists $item->{'withdrawn'} and
1302 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1303 $item->{'withdrawn'} = 0;
1306 exists $item->{location}
1307 and ( !defined $item->{location}
1308 || ( $item->{location} ne 'CART' and $item->{location} ne 'PROC' ) )
1309 and not $item->{permanent_location}
1312 $item->{'permanent_location'} = $item->{'location'};
1314 if (exists $item->{'timestamp'}) {
1315 delete $item->{'timestamp'};
1319 =head2 _get_single_item_column
1321 _get_single_item_column($column, $itemnumber);
1323 Retrieves the value of a single column from an C<items>
1324 row specified by C<$itemnumber>.
1328 sub _get_single_item_column {
1330 my $itemnumber = shift;
1332 my $dbh = C4::Context->dbh;
1333 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1334 $sth->execute($itemnumber);
1335 my ($value) = $sth->fetchrow();
1339 =head2 _calc_items_cn_sort
1341 _calc_items_cn_sort($item, $source_values);
1343 Helper routine to calculate C<items.cn_sort>.
1347 sub _calc_items_cn_sort {
1349 my $source_values = shift;
1351 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1354 =head2 _koha_new_item
1356 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1358 Perform the actual insert into the C<items> table.
1362 sub _koha_new_item {
1363 my ( $item, $barcode ) = @_;
1364 my $dbh=C4::Context->dbh;
1366 $item->{permanent_location} //= $item->{location};
1367 _mod_item_dates( $item );
1369 "INSERT INTO items SET
1371 biblioitemnumber = ?,
1373 dateaccessioned = ?,
1377 replacementprice = ?,
1378 replacementpricedate = ?,
1379 datelastborrowed = ?,
1387 coded_location_qualifier = ?,
1390 itemnotes_nonpublic = ?,
1393 permanent_location = ?,
1405 more_subfields_xml = ?,
1410 my $sth = $dbh->prepare($query);
1411 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1413 $item->{'biblionumber'},
1414 $item->{'biblioitemnumber'},
1416 $item->{'dateaccessioned'},
1417 $item->{'booksellerid'},
1418 $item->{'homebranch'},
1420 $item->{'replacementprice'},
1421 $item->{'replacementpricedate'} || $today,
1422 $item->{datelastborrowed},
1423 $item->{datelastseen} || $today,
1425 $item->{'notforloan'},
1427 $item->{'itemlost'},
1428 $item->{'withdrawn'},
1429 $item->{'itemcallnumber'},
1430 $item->{'coded_location_qualifier'},
1431 $item->{'restricted'},
1432 $item->{'itemnotes'},
1433 $item->{'itemnotes_nonpublic'},
1434 $item->{'holdingbranch'},
1435 $item->{'location'},
1436 $item->{'permanent_location'},
1439 $item->{'renewals'},
1440 $item->{'reserves'},
1441 $item->{'items.cn_source'},
1442 $item->{'items.cn_sort'},
1445 $item->{'materials'},
1447 $item->{'enumchron'},
1448 $item->{'more_subfields_xml'},
1449 $item->{'copynumber'},
1450 $item->{'stocknumber'},
1451 $item->{'new_status'},
1455 if ( defined $sth->errstr ) {
1456 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1459 $itemnumber = $dbh->{'mysql_insertid'};
1462 return ( $itemnumber, $error );
1465 =head2 MoveItemFromBiblio
1467 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1469 Moves an item from a biblio to another
1471 Returns undef if the move failed or the biblionumber of the destination record otherwise
1475 sub MoveItemFromBiblio {
1476 my ($itemnumber, $frombiblio, $tobiblio) = @_;
1477 my $dbh = C4::Context->dbh;
1478 my ( $tobiblioitem ) = $dbh->selectrow_array(q|
1479 SELECT biblioitemnumber
1481 WHERE biblionumber = ?
1482 |, undef, $tobiblio );
1483 my $return = $dbh->do(q|
1485 SET biblioitemnumber = ?,
1487 WHERE itemnumber = ?
1488 AND biblionumber = ?
1489 |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
1491 ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
1492 ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
1493 # Checking if the item we want to move is in an order
1494 require C4::Acquisition;
1495 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
1497 # Replacing the biblionumber within the order if necessary
1498 $order->{'biblionumber'} = $tobiblio;
1499 C4::Acquisition::ModOrder($order);
1502 # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
1503 for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
1506 SET biblionumber = ?
1507 WHERE itemnumber = ?
1508 |, undef, $tobiblio, $itemnumber );
1515 =head2 ItemSafeToDelete
1517 ItemSafeToDelete( $biblionumber, $itemnumber);
1519 Exported function (core API) for checking whether an item record is safe to delete.
1521 returns 1 if the item is safe to delete,
1523 "book_on_loan" if the item is checked out,
1525 "not_same_branch" if the item is blocked by independent branches,
1527 "book_reserved" if the there are holds aganst the item, or
1529 "linked_analytics" if the item has linked analytic records.
1533 sub ItemSafeToDelete {
1534 my ( $biblionumber, $itemnumber ) = @_;
1536 my $dbh = C4::Context->dbh;
1540 my $countanalytics = GetAnalyticsCount($itemnumber);
1542 my $item = Koha::Items->find($itemnumber) or return;
1544 if ($item->checkout) {
1545 $status = "book_on_loan";
1547 elsif ( defined C4::Context->userenv
1548 and !C4::Context->IsSuperLibrarian()
1549 and C4::Context->preference("IndependentBranches")
1550 and ( C4::Context->userenv->{branch} ne $item->homebranch ) )
1552 $status = "not_same_branch";
1555 # check it doesn't have a waiting reserve
1556 my $sth = $dbh->prepare(
1558 SELECT COUNT(*) FROM reserves
1559 WHERE (found = 'W' OR found = 'T')
1563 $sth->execute($itemnumber);
1564 my ($reserve) = $sth->fetchrow;
1566 $status = "book_reserved";
1568 elsif ( $countanalytics > 0 ) {
1569 $status = "linked_analytics";
1580 DelItemCheck( $biblionumber, $itemnumber);
1582 Exported function (core API) for deleting an item record in Koha if there no current issue.
1584 DelItemCheck wraps ItemSafeToDelete around DelItem.
1589 my ( $biblionumber, $itemnumber ) = @_;
1590 my $status = ItemSafeToDelete( $biblionumber, $itemnumber );
1592 if ( $status == 1 ) {
1595 biblionumber => $biblionumber,
1596 itemnumber => $itemnumber
1603 =head2 _koha_modify_item
1605 my ($itemnumber,$error) =_koha_modify_item( $item );
1607 Perform the actual update of the C<items> row. Note that this
1608 routine accepts a hashref specifying the columns to update.
1612 sub _koha_modify_item {
1614 my $dbh=C4::Context->dbh;
1617 my $query = "UPDATE items SET ";
1619 _mod_item_dates( $item );
1620 for my $key ( keys %$item ) {
1621 next if ( $key eq 'itemnumber' );
1623 push @bind, $item->{$key};
1626 $query .= " WHERE itemnumber=?";
1627 push @bind, $item->{'itemnumber'};
1628 my $sth = $dbh->prepare($query);
1629 $sth->execute(@bind);
1631 $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
1634 return ($item->{'itemnumber'},$error);
1637 sub _mod_item_dates { # date formatting for date fields in item hash
1639 return if !$item || ref($item) ne 'HASH';
1642 { $_ =~ /^onloan$|^date|date$|datetime$/ }
1644 # Incl. dateaccessioned,replacementpricedate,datelastborrowed,datelastseen
1645 # NOTE: We do not (yet) have items fields ending with datetime
1646 # Fields with _on$ have been handled already
1648 foreach my $key ( @keys ) {
1649 next if !defined $item->{$key}; # skip undefs
1650 my $dt = eval { dt_from_string( $item->{$key} ) };
1651 # eval: dt_from_string will die on us if we pass illegal dates
1654 if( defined $dt && ref($dt) eq 'DateTime' ) {
1655 if( $key =~ /datetime/ ) {
1656 $newstr = DateTime::Format::MySQL->format_datetime($dt);
1658 $newstr = DateTime::Format::MySQL->format_date($dt);
1661 $item->{$key} = $newstr; # might be undef to clear garbage
1665 =head2 _koha_delete_item
1667 _koha_delete_item( $itemnum );
1669 Internal function to delete an item record from the koha tables
1673 sub _koha_delete_item {
1674 my ( $itemnum ) = @_;
1676 my $dbh = C4::Context->dbh;
1677 # save the deleted item to deleteditems table
1678 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1679 $sth->execute($itemnum);
1680 my $data = $sth->fetchrow_hashref();
1682 # There is no item to delete
1683 return 0 unless $data;
1685 my $query = "INSERT INTO deleteditems SET ";
1687 foreach my $key ( keys %$data ) {
1688 next if ( $key eq 'timestamp' ); # timestamp will be set by db
1689 $query .= "$key = ?,";
1690 push( @bind, $data->{$key} );
1693 $sth = $dbh->prepare($query);
1694 $sth->execute(@bind);
1696 # delete from items table
1697 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1698 my $deleted = $sth->execute($itemnum);
1699 return ( $deleted == 1 ) ? 1 : 0;
1702 =head2 _marc_from_item_hash
1704 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1706 Given an item hash representing a complete item record,
1707 create a C<MARC::Record> object containing an embedded
1708 tag representing that item.
1710 The third, optional parameter C<$unlinked_item_subfields> is
1711 an arrayref of subfields (not mapped to C<items> fields per the
1712 framework) to be added to the MARC representation
1717 sub _marc_from_item_hash {
1719 my $frameworkcode = shift;
1720 my $unlinked_item_subfields;
1722 $unlinked_item_subfields = shift;
1725 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1726 # Also, don't emit a subfield if the underlying field is blank.
1727 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1728 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1729 : () } keys %{ $item } };
1731 my $item_marc = MARC::Record->new();
1732 foreach my $item_field ( keys %{$mungeditem} ) {
1733 my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField( $item_field );
1734 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1735 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
1736 foreach my $value (@values){
1737 if ( my $field = $item_marc->field($tag) ) {
1738 $field->add_subfields( $subfield => $value );
1740 my $add_subfields = [];
1741 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1742 $add_subfields = $unlinked_item_subfields;
1744 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
1752 =head2 _repack_item_errors
1754 Add an error message hash generated by C<CheckItemPreSave>
1755 to a list of errors.
1759 sub _repack_item_errors {
1760 my $item_sequence_num = shift;
1761 my $item_ref = shift;
1762 my $error_ref = shift;
1764 my @repacked_errors = ();
1766 foreach my $error_code (sort keys %{ $error_ref }) {
1767 my $repacked_error = {};
1768 $repacked_error->{'item_sequence'} = $item_sequence_num;
1769 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
1770 $repacked_error->{'error_code'} = $error_code;
1771 $repacked_error->{'error_information'} = $error_ref->{$error_code};
1772 push @repacked_errors, $repacked_error;
1775 return @repacked_errors;
1778 =head2 _get_unlinked_item_subfields
1780 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
1784 sub _get_unlinked_item_subfields {
1785 my $original_item_marc = shift;
1786 my $frameworkcode = shift;
1788 my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
1790 # assume that this record has only one field, and that that
1791 # field contains only the item information
1793 my @fields = $original_item_marc->fields();
1794 if ($#fields > -1) {
1795 my $field = $fields[0];
1796 my $tag = $field->tag();
1797 foreach my $subfield ($field->subfields()) {
1798 if (defined $subfield->[1] and
1799 $subfield->[1] ne '' and
1800 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
1801 push @$subfields, $subfield->[0] => $subfield->[1];
1808 =head2 _get_unlinked_subfields_xml
1810 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
1814 sub _get_unlinked_subfields_xml {
1815 my $unlinked_item_subfields = shift;
1818 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1819 my $marc = MARC::Record->new();
1820 # use of tag 999 is arbitrary, and doesn't need to match the item tag
1821 # used in the framework
1822 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
1823 $marc->encoding("UTF-8");
1824 $xml = $marc->as_xml("USMARC");
1830 =head2 _parse_unlinked_item_subfields_from_xml
1832 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
1836 sub _parse_unlinked_item_subfields_from_xml {
1838 require C4::Charset;
1839 return unless defined $xml and $xml ne "";
1840 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
1841 my $unlinked_subfields = [];
1842 my @fields = $marc->fields();
1843 if ($#fields > -1) {
1844 foreach my $subfield ($fields[0]->subfields()) {
1845 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
1848 return $unlinked_subfields;
1851 =head2 GetAnalyticsCount
1853 $count= &GetAnalyticsCount($itemnumber)
1855 counts Usage of itemnumber in Analytical bibliorecords.
1859 sub GetAnalyticsCount {
1860 my ($itemnumber) = @_;
1862 ### ZOOM search here
1864 $query= "hi=".$itemnumber;
1865 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
1866 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
1870 sub _SearchItems_build_where_fragment {
1873 my $dbh = C4::Context->dbh;
1876 if (exists($filter->{conjunction})) {
1877 my (@where_strs, @where_args);
1878 foreach my $f (@{ $filter->{filters} }) {
1879 my $fragment = _SearchItems_build_where_fragment($f);
1881 push @where_strs, $fragment->{str};
1882 push @where_args, @{ $fragment->{args} };
1887 $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
1890 args => \@where_args,
1894 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
1895 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
1896 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
1897 my @operators = qw(= != > < >= <= like);
1898 my $field = $filter->{field} // q{};
1899 if ( (0 < grep { $_ eq $field } @columns) or (substr($field, 0, 5) eq 'marc:') ) {
1900 my $op = $filter->{operator};
1901 my $query = $filter->{query};
1903 if (!$op or (0 == grep { $_ eq $op } @operators)) {
1904 $op = '='; # default operator
1908 if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
1910 my $marcsubfield = $2;
1911 my ($kohafield) = $dbh->selectrow_array(q|
1912 SELECT kohafield FROM marc_subfield_structure
1913 WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
1914 |, undef, $marcfield, $marcsubfield);
1917 $column = $kohafield;
1919 # MARC field is not linked to a DB field so we need to use
1920 # ExtractValue on marcxml from biblio_metadata or
1921 # items.more_subfields_xml, depending on the MARC field.
1924 my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber');
1925 if ($marcfield eq $itemfield) {
1926 $sqlfield = 'more_subfields_xml';
1927 $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
1929 $sqlfield = 'metadata'; # From biblio_metadata
1930 if ($marcfield < 10) {
1931 $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
1933 $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
1936 $column = "ExtractValue($sqlfield, '$xpath')";
1938 } elsif ($field eq 'issues') {
1939 # Consider NULL as 0 for issues count
1940 $column = 'COALESCE(issues,0)';
1945 if (ref $query eq 'ARRAY') {
1948 } elsif ($op eq '!=') {
1952 str => "$column $op (" . join (',', ('?') x @$query) . ")",
1957 str => "$column $op ?",
1964 return $where_fragment;
1969 my ($items, $total) = SearchItems($filter, $params);
1971 Perform a search among items
1973 $filter is a reference to a hash which can be a filter, or a combination of filters.
1975 A filter has the following keys:
1979 =item * field: the name of a SQL column in table items
1981 =item * query: the value to search in this column
1983 =item * operator: comparison operator. Can be one of = != > < >= <= like
1987 A combination of filters hash the following keys:
1991 =item * conjunction: 'AND' or 'OR'
1993 =item * filters: array ref of filters
1997 $params is a reference to a hash that can contain the following parameters:
2001 =item * rows: Number of items to return. 0 returns everything (default: 0)
2003 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2006 =item * sortby: A SQL column name in items table to sort on
2008 =item * sortorder: 'ASC' or 'DESC'
2015 my ($filter, $params) = @_;
2019 return unless ref $filter eq 'HASH';
2020 return unless ref $params eq 'HASH';
2022 # Default parameters
2023 $params->{rows} ||= 0;
2024 $params->{page} ||= 1;
2025 $params->{sortby} ||= 'itemnumber';
2026 $params->{sortorder} ||= 'ASC';
2028 my ($where_str, @where_args);
2029 my $where_fragment = _SearchItems_build_where_fragment($filter);
2030 if ($where_fragment) {
2031 $where_str = $where_fragment->{str};
2032 @where_args = @{ $where_fragment->{args} };
2035 my $dbh = C4::Context->dbh;
2037 SELECT SQL_CALC_FOUND_ROWS items.*
2039 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2040 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2041 LEFT JOIN biblio_metadata ON biblio_metadata.biblionumber = biblio.biblionumber
2044 if (defined $where_str and $where_str ne '') {
2045 $query .= qq{ AND $where_str };
2048 $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.schema = ? };
2049 push @where_args, C4::Context->preference('marcflavour');
2051 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2052 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2053 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2054 my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
2055 ? $params->{sortby} : 'itemnumber';
2056 my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
2057 $query .= qq{ ORDER BY $sortby $sortorder };
2059 my $rows = $params->{rows};
2062 my $offset = $rows * ($params->{page}-1);
2063 $query .= qq { LIMIT ?, ? };
2064 push @limit_args, $offset, $rows;
2067 my $sth = $dbh->prepare($query);
2068 my $rv = $sth->execute(@where_args, @limit_args);
2070 return unless ($rv);
2071 my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2073 return ($sth->fetchall_arrayref({}), $total_rows);
2077 =head1 OTHER FUNCTIONS
2081 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2083 Find the given $subfield in the given $tag in the given
2084 MARC::Record $record. If the subfield is found, returns
2085 the (indicators, value) pair; otherwise, (undef, undef) is
2089 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2090 I suggest we export it from this module.
2095 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2098 if ( $tagfield < 10 ) {
2099 if ( $record->field($tagfield) ) {
2100 push @result, $record->field($tagfield)->data();
2105 foreach my $field ( $record->field($tagfield) ) {
2106 my @subfields = $field->subfields();
2107 foreach my $subfield (@subfields) {
2108 if ( @$subfield[0] eq $insubfield ) {
2109 push @result, @$subfield[1];
2110 $indicator = $field->indicator(1) . $field->indicator(2);
2115 return ( $indicator, @result );
2119 =head2 PrepareItemrecordDisplay
2121 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2123 Returns a hash with all the fields for Display a given item data in a template
2125 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2129 sub PrepareItemrecordDisplay {
2131 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2133 my $dbh = C4::Context->dbh;
2134 $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum;
2135 my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
2137 # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
2138 # a shared data structure. No plugin (including custom ones) should change
2139 # its contents. See also GetMarcStructure.
2140 my $tagslib = GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
2142 # return nothing if we don't have found an existing framework.
2143 return q{} unless $tagslib;
2146 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2150 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2152 SELECT authorised_value,lib FROM authorised_values
2155 LEFT JOIN authorised_values_branches ON ( id = av_id )
2160 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2161 $query .= qq{ ORDER BY lib};
2162 my $authorised_values_sth = $dbh->prepare( $query );
2163 foreach my $tag ( sort keys %{$tagslib} ) {
2166 # loop through each subfield
2168 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2169 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
2170 next unless ( $tagslib->{$tag}->{$subfield}->{'tab'} );
2171 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2173 $subfield_data{tag} = $tag;
2174 $subfield_data{subfield} = $subfield;
2175 $subfield_data{countsubfield} = $cntsubf++;
2176 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2177 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2179 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2180 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2181 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2182 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2183 $subfield_data{hidden} = "display:none"
2184 if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
2185 || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
2186 my ( $x, $defaultvalue );
2188 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2190 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2191 if ( !defined $defaultvalue ) {
2192 $defaultvalue = q||;
2194 $defaultvalue =~ s/"/"/g;
2197 my $maxlength = $tagslib->{$tag}->{$subfield}->{maxlength};
2199 # search for itemcallnumber if applicable
2200 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2201 && C4::Context->preference('itemcallnumber') && $itemrecord) {
2202 foreach my $itemcn_pref (split(/,/,C4::Context->preference('itemcallnumber'))){
2203 my $CNtag = substr( $itemcn_pref, 0, 3 );
2204 next unless my $field = $itemrecord->field($CNtag);
2205 my $CNsubfields = substr( $itemcn_pref, 3 );
2206 $defaultvalue = $field->as_string( $CNsubfields, ' ');
2207 last if $defaultvalue;
2210 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2212 && $defaultvalues->{'callnumber'} ) {
2213 if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ){
2214 # if the item record exists, only use default value if the item has no callnumber
2215 $defaultvalue = $defaultvalues->{callnumber};
2216 } elsif ( !$itemrecord and $defaultvalues ) {
2217 # if the item record *doesn't* exists, always use the default value
2218 $defaultvalue = $defaultvalues->{callnumber};
2221 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2223 && $defaultvalues->{'branchcode'} ) {
2224 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2225 $defaultvalue = $defaultvalues->{branchcode};
2228 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2230 && $defaultvalues->{'location'} ) {
2232 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2233 # if the item record exists, only use default value if the item has no locationr
2234 $defaultvalue = $defaultvalues->{location};
2235 } elsif ( !$itemrecord and $defaultvalues ) {
2236 # if the item record *doesn't* exists, always use the default value
2237 $defaultvalue = $defaultvalues->{location};
2240 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2241 my @authorised_values;
2244 # builds list, depending on authorised value...
2246 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2247 if ( ( C4::Context->preference("IndependentBranches") )
2248 && !C4::Context->IsSuperLibrarian() ) {
2249 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2250 $sth->execute( C4::Context->userenv->{branch} );
2251 push @authorised_values, ""
2252 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2253 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2254 push @authorised_values, $branchcode;
2255 $authorised_lib{$branchcode} = $branchname;
2258 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2260 push @authorised_values, ""
2261 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2262 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2263 push @authorised_values, $branchcode;
2264 $authorised_lib{$branchcode} = $branchname;
2268 $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2269 if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2270 $defaultvalue = $defaultvalues->{branchcode};
2274 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2275 my $itemtypes = Koha::ItemTypes->search_with_localization;
2276 push @authorised_values, ""
2277 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2278 while ( my $itemtype = $itemtypes->next ) {
2279 push @authorised_values, $itemtype->itemtype;
2280 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
2282 if ($defaultvalues && $defaultvalues->{'itemtype'}) {
2283 $defaultvalue = $defaultvalues->{'itemtype'};
2287 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2288 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2290 my $class_sources = GetClassSources();
2291 my $default_source = $defaultvalue || C4::Context->preference("DefaultClassificationSource");
2293 foreach my $class_source (sort keys %$class_sources) {
2294 next unless $class_sources->{$class_source}->{'used'} or
2295 ($class_source eq $default_source);
2296 push @authorised_values, $class_source;
2297 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2300 $defaultvalue = $default_source;
2302 #---- "true" authorised value
2304 $authorised_values_sth->execute(
2305 $tagslib->{$tag}->{$subfield}->{authorised_value},
2306 $branch_limit ? $branch_limit : ()
2308 push @authorised_values, ""
2309 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2310 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2311 push @authorised_values, $value;
2312 $authorised_lib{$value} = $lib;
2315 $subfield_data{marc_value} = {
2317 values => \@authorised_values,
2318 default => $defaultvalue // q{},
2319 labels => \%authorised_lib,
2321 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2323 require Koha::FrameworkPlugin;
2324 my $plugin = Koha::FrameworkPlugin->new({
2325 name => $tagslib->{$tag}->{$subfield}->{value_builder},
2328 my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
2329 $plugin->build( $pars );
2330 if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
2331 $defaultvalue = $field->subfield($subfield) || q{};
2333 if( !$plugin->errstr ) {
2334 #TODO Move html to template; see report 12176/13397
2335 my $tab= $plugin->noclick? '-1': '';
2336 my $class= $plugin->noclick? ' disabled': '';
2337 my $title= $plugin->noclick? 'No popup': 'Tag editor';
2338 $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" /><a href="#" id="buttonDot_$subfield_data{id}" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
2340 warn $plugin->errstr;
2341 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />); # supply default input form
2344 elsif ( $tag eq '' ) { # it's an hidden field
2345 $subfield_data{marc_value} = qq(<input type="hidden" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
2347 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2348 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
2350 elsif ( length($defaultvalue) > 100
2351 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2352 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2353 or (C4::Context->preference("marcflavour") eq "MARC21" and
2354 500 <= $tag && $tag < 600 )
2356 # oversize field (textarea)
2357 $subfield_data{marc_value} = qq(<textarea id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength">$defaultvalue</textarea>\n");
2359 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
2361 push( @loop_data, \%subfield_data );
2366 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2367 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2370 'itemtagfield' => $itemtagfield,
2371 'itemtagsubfield' => $itemtagsubfield,
2372 'itemnumber' => $itemnumber,
2373 'iteminformation' => \@loop_data
2377 sub ToggleNewStatus {
2378 my ( $params ) = @_;
2379 my @rules = @{ $params->{rules} };
2380 my $report_only = $params->{report_only};
2382 my $dbh = C4::Context->dbh;
2384 my @item_columns = map { "items.$_" } Koha::Items->columns;
2385 my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
2387 for my $rule ( @rules ) {
2388 my $age = $rule->{age};
2389 my $conditions = $rule->{conditions};
2390 my $substitutions = $rule->{substitutions};
2391 foreach ( @$substitutions ) {
2392 ( $_->{item_field} ) = ( $_->{field} =~ /items\.(.*)/ );
2399 LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
2402 for my $condition ( @$conditions ) {
2404 grep { $_ eq $condition->{field} } @item_columns
2405 or grep { $_ eq $condition->{field} } @biblioitem_columns
2407 if ( $condition->{value} =~ /\|/ ) {
2408 my @values = split /\|/, $condition->{value};
2409 $query .= qq| AND $condition->{field} IN (|
2410 . join( ',', ('?') x scalar @values )
2412 push @params, @values;
2414 $query .= qq| AND $condition->{field} = ?|;
2415 push @params, $condition->{value};
2419 if ( defined $age ) {
2420 $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
2423 my $sth = $dbh->prepare($query);
2424 $sth->execute( @params );
2425 while ( my $values = $sth->fetchrow_hashref ) {
2426 my $biblionumber = $values->{biblionumber};
2427 my $itemnumber = $values->{itemnumber};
2428 my $item = Koha::Items->find($itemnumber);
2429 for my $substitution ( @$substitutions ) {
2430 my $field = $substitution->{item_field};
2431 my $value = $substitution->{value};
2432 next unless $substitution->{field};
2433 next if ( defined $values->{ $substitution->{item_field} } and $values->{ $substitution->{item_field} } eq $substitution->{value} );
2434 $item->$field($value);
2435 push @{ $report->{$itemnumber} }, $substitution;
2437 $item->store unless $report_only;