Bug 23463: _set_derived_columns_for_mod was only used for cn_sort
[koha.git] / C4 / Items.pm
1 package C4::Items;
2
3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use Modern::Perl;
22
23 use vars qw(@ISA @EXPORT);
24 BEGIN {
25     require Exporter;
26     @ISA = qw(Exporter);
27
28     @EXPORT = qw(
29         AddItemFromMarc
30         AddItemBatchFromMarc
31         ModItemFromMarc
32         Item2Marc
33         ModItem
34         ModDateLastSeen
35         ModItemTransfer
36         DelItem
37         CheckItemPreSave
38         GetItemsForInventory
39         GetItemsInfo
40         GetItemsLocationInfo
41         GetHostItemsInfo
42         get_hostitemnumbers_of
43         GetHiddenItemnumbers
44         ItemSafeToDelete
45         DelItemCheck
46         MoveItemFromBiblio
47         CartToShelf
48         GetAnalyticsCount
49         SearchItems
50         PrepareItemrecordDisplay
51     );
52 }
53
54 use Carp;
55 use Try::Tiny;
56 use C4::Context;
57 use C4::Koha;
58 use C4::Biblio;
59 use Koha::DateUtils;
60 use MARC::Record;
61 use C4::ClassSource;
62 use C4::Log;
63 use List::MoreUtils qw(any);
64 use YAML qw(Load);
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
68
69 use Koha::AuthorisedValues;
70 use Koha::DateUtils qw(dt_from_string);
71 use Koha::Database;
72
73 use Koha::Biblioitems;
74 use Koha::Items;
75 use Koha::ItemTypes;
76 use Koha::SearchEngine;
77 use Koha::SearchEngine::Search;
78 use Koha::Libraries;
79
80 =head1 NAME
81
82 C4::Items - item management functions
83
84 =head1 DESCRIPTION
85
86 This module contains an API for manipulating item 
87 records in Koha, and is used by cataloguing, circulation,
88 acquisitions, and serials management.
89
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.
98
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
102 accurate.
103
104 =head1 HISTORICAL NOTE
105
106 Most of the functions in C<C4::Items> were originally in
107 the C<C4::Biblio> module.
108
109 =head1 CORE EXPORTED FUNCTIONS
110
111 The following functions are meant for use by users
112 of C<C4::Items>
113
114 =cut
115
116 =head2 CartToShelf
117
118   CartToShelf($itemnumber);
119
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.
125
126 =cut
127
128 sub CartToShelf {
129     my ( $itemnumber ) = @_;
130
131     unless ( $itemnumber ) {
132         croak "FAILED CartToShelf() - no itemnumber supplied";
133     }
134
135     my $item = Koha::Items->find($itemnumber);
136     if ( $item->location eq 'CART' ) {
137         $item->location($item->permanent_location)->store;
138     }
139 }
140
141 =head2 AddItemFromMarc
142
143   my ($biblionumber, $biblioitemnumber, $itemnumber) 
144       = AddItemFromMarc($source_item_marc, $biblionumber);
145
146 Given a MARC::Record object containing an embedded item
147 record and a biblionumber, create a new item record.
148
149 =cut
150
151 sub AddItemFromMarc {
152     my ( $source_item_marc, $biblionumber ) = @_;
153     my $dbh = C4::Context->dbh;
154
155     # parse item hash from MARC
156     my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
157     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
158
159     my $localitemmarc = MARC::Record->new;
160     $localitemmarc->append_fields( $source_item_marc->field($itemtag) );
161
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 );
168 }
169
170 =head2 AddItemBatchFromMarc
171
172   ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
173              $biblionumber, $biblioitemnumber, $frameworkcode);
174
175 Efficiently create item records from a MARC biblio record with
176 embedded item fields.  This routine is suitable for batch jobs.
177
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.
182
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.
186
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:
190
191 =over
192
193 =item item_sequence
194
195 Sequence number of original item tag in the MARC record.
196
197 =item item_barcode
198
199 Item barcode, provide to assist in the construction of
200 useful error messages.
201
202 =item error_code
203
204 Code representing the error condition.  Can be 'duplicate_barcode',
205 'invalid_homebranch', or 'invalid_holdingbranch'.
206
207 =item error_information
208
209 Additional information appropriate to the error condition.
210
211 =back
212
213 =cut
214
215 sub AddItemBatchFromMarc {
216     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
217     my $error;
218     my @itemnumbers = ();
219     my @errors = ();
220     my $dbh = C4::Context->dbh;
221
222     # We modify the record, so lets work on a clone so we don't change the
223     # original.
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);
237     
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;
244
245         # check for duplicate barcode
246         my %item_errors = CheckItemPreSave($item);
247         if (%item_errors) {
248             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
249             push @bad_item_fields, $item_field;
250             next ITEMFIELD;
251         }
252
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;
258
259         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
260
261         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
262         $item_field->replace_with($new_item_marc->field($itemtag));
263     }
264
265     # remove any MARC item fields for rejected items
266     foreach my $item_field (@bad_item_fields) {
267         $record->delete_field($item_field);
268     }
269
270     # update the MARC biblio
271  #   $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
272
273     return (\@itemnumbers, \@errors);
274 }
275
276 =head2 ModItemFromMarc
277
278   ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
279
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.
284
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.
293
294 Note that only columns that can be directly
295 changed from the cataloging and serials
296 item editors are included in this hash.
297
298 Returns item record
299
300 =cut
301
302 sub _build_default_values_for_mod_marc {
303     # Has no framework parameter anymore, since Default is authoritative
304     # for Koha to MARC mappings.
305
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;
310
311     my $default_values = {
312         barcode                  => undef,
313         booksellerid             => undef,
314         ccode                    => undef,
315         'items.cn_source'        => undef,
316         coded_location_qualifier => undef,
317         copynumber               => undef,
318         damaged                  => 0,
319         enumchron                => undef,
320         holdingbranch            => undef,
321         homebranch               => undef,
322         itemcallnumber           => undef,
323         itemlost                 => 0,
324         itemnotes                => undef,
325         itemnotes_nonpublic      => undef,
326         itype                    => undef,
327         location                 => undef,
328         permanent_location       => undef,
329         materials                => undef,
330         new_status               => undef,
331         notforloan               => 0,
332         price                    => undef,
333         replacementprice         => undef,
334         replacementpricedate     => undef,
335         restricted               => undef,
336         stack                    => undef,
337         stocknumber              => undef,
338         uri                      => undef,
339         withdrawn                => 0,
340     };
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 );
347     }
348
349     $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
350     return \%default_values_for_mod_from_marc;
351 }
352
353 sub ModItemFromMarc {
354     my $item_marc = shift;
355     my $biblionumber = shift;
356     my $itemnumber = shift;
357
358     my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
359     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
360
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};
368     }
369     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
370
371     my $item_object = Koha::Items->find($itemnumber);
372     $item_object->more_subfields_xml(_get_unlinked_subfields_xml($unlinked_item_subfields))->store;
373
374     return $item_object->get_from_storage->unblessed;
375 }
376
377 =head2 ModItem
378
379 ModItem(
380     { column => $newvalue },
381     $biblionumber,
382     $itemnumber,
383     {
384         [ unlinked_item_subfields => $unlinked_item_subfields, ]
385         [ log_action => 1, ]
386     }
387 );
388
389 Change one or more columns in an item record.
390
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.
396
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.
403
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
407 and set the value.
408
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.
411
412 =cut
413
414 sub ModItem {
415     my ( $item, $biblionumber, $itemnumber, $additional_params ) = @_;
416     my $log_action = $additional_params->{log_action} // 1;
417
418     _set_derived_columns_for_mod($item);
419     _do_column_fixes_for_mod($item);
420     # FIXME add checks
421     # duplicate barcode
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)
426
427     # update items table
428     _koha_modify_item($item);
429
430     # request that bib be reindexed so that searching on current
431     # item status is possible
432     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
433
434     _after_item_action_hooks({ action => 'modify', item_id => $itemnumber });
435
436     logaction( "CATALOGUING", "MODIFY", $itemnumber, "item " . Dumper($item) )
437       if $log_action && C4::Context->preference("CataloguingLog");
438 }
439
440 =head2 ModItemTransfer
441
442   ModItemTransfer($itemnumber, $frombranch, $tobranch, $trigger);
443
444 Marks an item as being transferred from one branch to another and records the trigger.
445
446 =cut
447
448 sub ModItemTransfer {
449     my ( $itemnumber, $frombranch, $tobranch, $trigger ) = @_;
450
451     my $dbh = C4::Context->dbh;
452     my $item = Koha::Items->find( $itemnumber );
453
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' );
456
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);
458
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);
464
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);
468     return;
469 }
470
471 =head2 ModDateLastSeen
472
473 ModDateLastSeen( $itemnumber, $leave_item_lost );
474
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
478
479 =cut
480
481 sub ModDateLastSeen {
482     my ( $itemnumber, $leave_item_lost ) = @_;
483
484     my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
485
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 });
490 }
491
492 =head2 DelItem
493
494   DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
495
496 Exported function (core API) for deleting an item record in Koha.
497
498 =cut
499
500 sub DelItem {
501     my ( $params ) = @_;
502
503     my $itemnumber   = $params->{itemnumber};
504     my $biblionumber = $params->{biblionumber};
505
506     unless ($biblionumber) {
507         my $item = Koha::Items->find( $itemnumber );
508         $biblionumber = $item ? $item->biblio->biblionumber : undef;
509     }
510
511     # If there is no biblionumber for the given itemnumber, there is nothing to delete
512     return 0 unless $biblionumber;
513
514     # FIXME check the item has no current issues
515     my $deleted = _koha_delete_item( $itemnumber );
516
517     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
518
519     _after_item_action_hooks({ action => 'delete', item_id => $itemnumber });
520
521     #search item field code
522     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
523     return $deleted;
524 }
525
526 =head2 CheckItemPreSave
527
528     my $item_ref = TransformMarcToKoha($marc, 'items');
529     # do stuff
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";
537     } else {
538         print "item is OK";
539     }
540
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.
545
546 =over 2
547
548 =item duplicate_barcode
549
550 Barcode, if it duplicates one already found in the database.
551
552 =item invalid_homebranch
553
554 Home branch, if not defined in branches table.
555
556 =item invalid_holdingbranch
557
558 Holding branch, if not defined in branches table.
559
560 =back
561
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.
565
566 =cut
567
568 sub CheckItemPreSave {
569     my $item_ref = shift;
570
571     my %errors = ();
572
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'};
580             }
581         }
582     }
583
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'};
589         }
590     }
591
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'};
597         }
598     }
599
600     return %errors;
601
602 }
603
604 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
605
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.
609
610 =cut
611
612 =head2 GetItemsForInventory
613
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,
622   branch       => $branch,
623   offset       => $offset,
624   size         => $size,
625   statushash   => $statushash,
626 } );
627
628 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
629
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.
633
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.
638
639 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
640
641 =cut
642
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'} // '';
658
659     my $dbh = C4::Context->dbh;
660     my ( @bind_params, @where_strings );
661
662     my $min_cnsort = GetClassSort($class_source,undef,$minlocation);
663     my $max_cnsort = GetClassSort($class_source,undef,$maxlocation);
664
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
667     };
668     my $select_count = q{SELECT COUNT(DISTINCT(items.itemnumber))};
669     my $query = q{
670         FROM items
671         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
672         LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
673     };
674     if ($statushash){
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 . ")";
679             }
680         }
681     }
682
683     if ($minlocation) {
684         push @where_strings, 'items.cn_sort >= ?';
685         push @bind_params, $min_cnsort;
686     }
687
688     if ($maxlocation) {
689         push @where_strings, 'items.cn_sort <= ?';
690         push @bind_params, $max_cnsort;
691     }
692
693     if ($datelastseen) {
694         $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
695         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
696         push @bind_params, $datelastseen;
697     }
698
699     if ( $location ) {
700         push @where_strings, 'items.location = ?';
701         push @bind_params, $location;
702     }
703
704     if ( $branchcode ) {
705         if($branch eq "homebranch"){
706         push @where_strings, 'items.homebranch = ?';
707         }else{
708             push @where_strings, 'items.holdingbranch = ?';
709         }
710         push @bind_params, $branchcode;
711     }
712
713     if ( $itemtype ) {
714         push @where_strings, 'biblioitems.itemtype = ?';
715         push @bind_params, $itemtype;
716     }
717
718     if ( $ignoreissued) {
719         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
720         push @where_strings, 'issues.date_due IS NULL';
721     }
722
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)} );
726     }
727
728     if ( @where_strings ) {
729         $query .= 'WHERE ';
730         $query .= join ' AND ', @where_strings;
731     }
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 );
738
739     my @results = ();
740     my $tmpresults = $sth->fetchall_arrayref({});
741     $sth = $dbh->prepare( $count_query );
742     $sth->execute( @bind_params );
743     my ($iTotalRecords) = $sth->fetchrow_array();
744
745     my @avs = Koha::AuthorisedValues->search(
746         {   'marc_subfield_structures.kohafield' => { '>' => '' },
747             'me.authorised_value'                => { '>' => '' },
748         },
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' ],
753         }
754     );
755
756     my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
757
758     foreach my $row (@$tmpresults) {
759
760         # Auth values
761         foreach (keys %$row) {
762             if (
763                 defined(
764                     $avmapping->{ "items.$_," . $row->{'frameworkcode'} . "," . ( $row->{$_} // q{} ) }
765                 )
766             ) {
767                 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
768             }
769         }
770         push @results, $row;
771     }
772
773     return (\@results, $iTotalRecords);
774 }
775
776 =head2 GetItemsInfo
777
778   @results = GetItemsInfo($biblionumber);
779
780 Returns information about items with the given biblionumber.
781
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:
786
787 =over 2
788
789 =item C<$data-E<gt>{branchname}>
790
791 The name (not the code) of the branch to which the book belongs.
792
793 =item C<$data-E<gt>{datelastseen}>
794
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<//>.
798
799 =item C<$data-E<gt>{datedue}>
800
801 =item C<$data-E<gt>{class}>
802
803 This is the concatenation of C<biblioitems.classification>, the book's
804 Dewey code, and C<biblioitems.subclass>.
805
806 =item C<$data-E<gt>{ocount}>
807
808 I think this is the number of copies of the book available.
809
810 =item C<$data-E<gt>{order}>
811
812 If this is set, it is set to C<One Order>.
813
814 =back
815
816 =cut
817
818 sub GetItemsInfo {
819     my ( $biblionumber ) = @_;
820     my $dbh   = C4::Context->dbh;
821     require C4::Languages;
822     my $language = C4::Languages::getlanguage();
823     my $query = "
824     SELECT items.*,
825            biblio.*,
826            biblioitems.volume,
827            biblioitems.number,
828            biblioitems.itemtype,
829            biblioitems.isbn,
830            biblioitems.issn,
831            biblioitems.publicationyear,
832            biblioitems.publishercode,
833            biblioitems.volumedate,
834            biblioitems.volumedesc,
835            biblioitems.lccn,
836            biblioitems.url,
837            items.notforloan as itemnotforloan,
838            issues.borrowernumber,
839            issues.date_due as datedue,
840            issues.onsite_checkout,
841            borrowers.cardnumber,
842            borrowers.surname,
843            borrowers.firstname,
844            borrowers.branchcode as bcode,
845            serial.serialseq,
846            serial.publisheddate,
847            itemtypes.description,
848            COALESCE( localization.translation, itemtypes.description ) AS translated_description,
849            itemtypes.notforloan as notforloan_per_itemtype,
850            holding.branchurl,
851            holding.branchcode,
852            holding.branchname,
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
856      FROM items
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');
867     $query .= q|
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 = ?
872     |;
873
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);
877     my $i = 0;
878     my @results;
879     my $serial;
880
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};
886         }
887
888         $serial ||= $data->{'serial'};
889
890         my $descriptions;
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} // '';
895
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} // '';
900
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} // '';
904
905         # Find the last 3 people who borrowed this item.
906         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
907                                     WHERE itemnumber = ?
908                                     AND old_issues.borrowernumber = borrowers.borrowernumber
909                                     ORDER BY returndate DESC
910                                     LIMIT 3");
911         $sth2->execute($data->{'itemnumber'});
912         my $ii = 0;
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'};
917             $ii++;
918         }
919
920         $results[$i] = $data;
921         $i++;
922     }
923
924     return $serial
925         ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
926         : @results;
927 }
928
929 =head2 GetItemsLocationInfo
930
931   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
932
933 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
934
935 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
936
937 =over 2
938
939 =item C<$data-E<gt>{homebranch}>
940
941 Branch Name of the item's homebranch
942
943 =item C<$data-E<gt>{holdingbranch}>
944
945 Branch Name of the item's holdingbranch
946
947 =item C<$data-E<gt>{location}>
948
949 Item's shelving location code
950
951 =item C<$data-E<gt>{location_intranet}>
952
953 The intranet description for the Shelving Location as set in authorised_values 'LOC'
954
955 =item C<$data-E<gt>{location_opac}>
956
957 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
958 description is set.
959
960 =item C<$data-E<gt>{itemcallnumber}>
961
962 Item's itemcallnumber
963
964 =item C<$data-E<gt>{cn_sort}>
965
966 Item's call number normalized for sorting
967
968 =back
969   
970 =cut
971
972 sub GetItemsLocationInfo {
973         my $biblionumber = shift;
974         my @results;
975
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 
981                      AND biblionumber = ?
982                      ORDER BY cn_sort ASC";
983         my $sth = $dbh->prepare($query);
984         $sth->execute($biblionumber);
985
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;
992         }
993         return @results;
994 }
995
996 =head2 GetHostItemsInfo
997
998     $hostiteminfo = GetHostItemsInfo($hostfield);
999     Returns the iteminfo for items linked to records via a host field
1000
1001 =cut
1002
1003 sub GetHostItemsInfo {
1004     my ($record) = @_;
1005     my @returnitemsInfo;
1006
1007     if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1008         return @returnitemsInfo;
1009     }
1010
1011     my @fields;
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');
1017     }
1018
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;
1026                 last;
1027             }
1028         }
1029     }
1030     return @returnitemsInfo;
1031 }
1032
1033 =head2 get_hostitemnumbers_of
1034
1035   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1036
1037 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1038
1039 Return a reference on a hash where key is a biblionumber and values are
1040 references on array of itemnumbers.
1041
1042 =cut
1043
1044
1045 sub get_hostitemnumbers_of {
1046     my ($biblionumber) = @_;
1047
1048     if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1049         return ();
1050     }
1051
1052     my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
1053     return unless $marcrecord;
1054
1055     my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
1056
1057     my $marcflavor = C4::Context->preference('marcflavour');
1058     if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
1059         $tag      = '773';
1060         $biblio_s = '0';
1061         $item_s   = '9';
1062     }
1063     elsif ( $marcflavor eq 'UNIMARC' ) {
1064         $tag      = '461';
1065         $biblio_s = '0';
1066         $item_s   = '9';
1067     }
1068
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";
1075             next;
1076         }
1077         my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber });
1078         push @returnhostitemnumbers, $linkeditemnumber
1079           if $is_from_biblio;
1080     }
1081
1082     return @returnhostitemnumbers;
1083 }
1084
1085 =head2 GetHiddenItemnumbers
1086
1087     my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
1088
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
1092 to be excluded
1093
1094 =cut
1095
1096 sub GetHiddenItemnumbers {
1097     my $params = shift;
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
1103             }
1104         }
1105     }
1106     my @resultitems;
1107
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
1111     my $hidingrules;
1112     eval {
1113         $hidingrules = YAML::Load($yaml);
1114     };
1115     if ($@) {
1116         warn "Unable to parse OpacHiddenItems syspref : $@";
1117         return ();
1118     }
1119     my $dbh = C4::Context->dbh;
1120
1121     # For each item
1122     foreach my $item (@$items) {
1123
1124         # We check each rule
1125         foreach my $field (keys %$hidingrules) {
1126             my $val;
1127             if (exists $item->{$field}) {
1128                 $val = $item->{$field};
1129             }
1130             else {
1131                 my $query = "SELECT $field from items where itemnumber = ?";
1132                 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1133             }
1134             $val = '' unless defined $val;
1135
1136             # If the results matches the values in the yaml file
1137             if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1138
1139                 # We add the itemnumber to the list
1140                 push @resultitems, $item->{'itemnumber'};
1141
1142                 # If at least one rule matched for an item, no need to test the others
1143                 last;
1144             }
1145         }
1146     }
1147     return @resultitems;
1148 }
1149
1150 =head1 LIMITED USE FUNCTIONS
1151
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.
1157
1158 =cut
1159
1160 =head2 GetMarcItem
1161
1162   my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1163
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
1167 editor.
1168
1169 =cut
1170
1171 sub GetMarcItem {
1172     my ( $biblionumber, $itemnumber ) = @_;
1173
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.
1177     #
1178     # The previous behavior was:
1179     #  1. Get the bib record.
1180     #  2. Return the MARC tag corresponding to the item record.
1181     #
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.
1185
1186     my $item = Koha::Items->find($itemnumber) or return;
1187
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.
1190
1191     return Item2Marc($item->unblessed, $biblionumber);
1192
1193 }
1194 sub Item2Marc {
1195         my ($itemrecord,$biblionumber)=@_;
1196     my $mungeditem = { 
1197         map {  
1198             defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  
1199         } keys %{ $itemrecord } 
1200     };
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,
1205     );
1206
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);
1211         }
1212     }
1213         return $itemmarc;
1214 }
1215
1216 =head1 PRIVATE FUNCTIONS AND VARIABLES
1217
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>.
1221
1222 =cut
1223
1224 =head2 %derived_columns
1225
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
1229 independently.
1230
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
1237 the derived value.
1238
1239 =cut
1240
1241 my %derived_columns = (
1242     'items.cn_sort' => {
1243         'itemcallnumber' => 1,
1244         'items.cn_source' => 1,
1245         'BUILDER' => \&_calc_items_cn_sort,
1246     }
1247 );
1248
1249 =head2 _set_derived_columns_for_add 
1250
1251   _set_derived_column_for_add($item);
1252
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>.
1256
1257 =cut
1258
1259 sub _set_derived_columns_for_add {
1260     my $item = shift;
1261
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};
1268         }
1269         $builder->($item, $source_values);
1270     }
1271 }
1272
1273 =head2 _do_column_fixes_for_mod
1274
1275   _do_column_fixes_for_mod($item);
1276
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.
1283
1284 =cut
1285
1286 sub _do_column_fixes_for_mod {
1287     my $item = shift;
1288
1289     if (exists $item->{'notforloan'} and
1290         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1291         $item->{'notforloan'} = 0;
1292     }
1293     if (exists $item->{'damaged'} and
1294         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1295         $item->{'damaged'} = 0;
1296     }
1297     if (exists $item->{'itemlost'} and
1298         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1299         $item->{'itemlost'} = 0;
1300     }
1301     if (exists $item->{'withdrawn'} and
1302         (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1303         $item->{'withdrawn'} = 0;
1304     }
1305     if (
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}
1310       )
1311     {
1312         $item->{'permanent_location'} = $item->{'location'};
1313     }
1314     if (exists $item->{'timestamp'}) {
1315         delete $item->{'timestamp'};
1316     }
1317 }
1318
1319 =head2 _get_single_item_column
1320
1321   _get_single_item_column($column, $itemnumber);
1322
1323 Retrieves the value of a single column from an C<items>
1324 row specified by C<$itemnumber>.
1325
1326 =cut
1327
1328 sub _get_single_item_column {
1329     my $column = shift;
1330     my $itemnumber = shift;
1331     
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();
1336     return $value; 
1337 }
1338
1339 =head2 _calc_items_cn_sort
1340
1341   _calc_items_cn_sort($item, $source_values);
1342
1343 Helper routine to calculate C<items.cn_sort>.
1344
1345 =cut
1346
1347 sub _calc_items_cn_sort {
1348     my $item = shift;
1349     my $source_values = shift;
1350
1351     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1352 }
1353
1354 =head2 _koha_new_item
1355
1356   my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1357
1358 Perform the actual insert into the C<items> table.
1359
1360 =cut
1361
1362 sub _koha_new_item {
1363     my ( $item, $barcode ) = @_;
1364     my $dbh=C4::Context->dbh;  
1365     my $error;
1366     $item->{permanent_location} //= $item->{location};
1367     _mod_item_dates( $item );
1368     my $query =
1369            "INSERT INTO items SET
1370             biblionumber        = ?,
1371             biblioitemnumber    = ?,
1372             barcode             = ?,
1373             dateaccessioned     = ?,
1374             booksellerid        = ?,
1375             homebranch          = ?,
1376             price               = ?,
1377             replacementprice    = ?,
1378             replacementpricedate = ?,
1379             datelastborrowed    = ?,
1380             datelastseen        = ?,
1381             stack               = ?,
1382             notforloan          = ?,
1383             damaged             = ?,
1384             itemlost            = ?,
1385             withdrawn           = ?,
1386             itemcallnumber      = ?,
1387             coded_location_qualifier = ?,
1388             restricted          = ?,
1389             itemnotes           = ?,
1390             itemnotes_nonpublic = ?,
1391             holdingbranch       = ?,
1392             location            = ?,
1393             permanent_location  = ?,
1394             onloan              = ?,
1395             issues              = ?,
1396             renewals            = ?,
1397             reserves            = ?,
1398             cn_source           = ?,
1399             cn_sort             = ?,
1400             ccode               = ?,
1401             itype               = ?,
1402             materials           = ?,
1403             uri                 = ?,
1404             enumchron           = ?,
1405             more_subfields_xml  = ?,
1406             copynumber          = ?,
1407             stocknumber         = ?,
1408             new_status          = ?
1409           ";
1410     my $sth = $dbh->prepare($query);
1411     my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1412    $sth->execute(
1413             $item->{'biblionumber'},
1414             $item->{'biblioitemnumber'},
1415             $barcode,
1416             $item->{'dateaccessioned'},
1417             $item->{'booksellerid'},
1418             $item->{'homebranch'},
1419             $item->{'price'},
1420             $item->{'replacementprice'},
1421             $item->{'replacementpricedate'} || $today,
1422             $item->{datelastborrowed},
1423             $item->{datelastseen} || $today,
1424             $item->{stack},
1425             $item->{'notforloan'},
1426             $item->{'damaged'},
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'},
1437             $item->{'onloan'},
1438             $item->{'issues'},
1439             $item->{'renewals'},
1440             $item->{'reserves'},
1441             $item->{'items.cn_source'},
1442             $item->{'items.cn_sort'},
1443             $item->{'ccode'},
1444             $item->{'itype'},
1445             $item->{'materials'},
1446             $item->{'uri'},
1447             $item->{'enumchron'},
1448             $item->{'more_subfields_xml'},
1449             $item->{'copynumber'},
1450             $item->{'stocknumber'},
1451             $item->{'new_status'},
1452     );
1453
1454     my $itemnumber;
1455     if ( defined $sth->errstr ) {
1456         $error.="ERROR in _koha_new_item $query".$sth->errstr;
1457     }
1458     else {
1459         $itemnumber = $dbh->{'mysql_insertid'};
1460     }
1461
1462     return ( $itemnumber, $error );
1463 }
1464
1465 =head2 MoveItemFromBiblio
1466
1467   MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1468
1469 Moves an item from a biblio to another
1470
1471 Returns undef if the move failed or the biblionumber of the destination record otherwise
1472
1473 =cut
1474
1475 sub MoveItemFromBiblio {
1476     my ($itemnumber, $frombiblio, $tobiblio) = @_;
1477     my $dbh = C4::Context->dbh;
1478     my ( $tobiblioitem ) = $dbh->selectrow_array(q|
1479         SELECT biblioitemnumber
1480         FROM biblioitems
1481         WHERE biblionumber = ?
1482     |, undef, $tobiblio );
1483     my $return = $dbh->do(q|
1484         UPDATE items
1485         SET biblioitemnumber = ?,
1486             biblionumber = ?
1487         WHERE itemnumber = ?
1488             AND biblionumber = ?
1489     |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
1490     if ($return == 1) {
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);
1496             if ($order) {
1497                     # Replacing the biblionumber within the order if necessary
1498                     $order->{'biblionumber'} = $tobiblio;
1499                 C4::Acquisition::ModOrder($order);
1500             }
1501
1502         # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
1503         for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
1504             $dbh->do( qq|
1505                 UPDATE $table_name
1506                 SET biblionumber = ?
1507                 WHERE itemnumber = ?
1508             |, undef, $tobiblio, $itemnumber );
1509         }
1510         return $tobiblio;
1511         }
1512     return;
1513 }
1514
1515 =head2 ItemSafeToDelete
1516
1517    ItemSafeToDelete( $biblionumber, $itemnumber);
1518
1519 Exported function (core API) for checking whether an item record is safe to delete.
1520
1521 returns 1 if the item is safe to delete,
1522
1523 "book_on_loan" if the item is checked out,
1524
1525 "not_same_branch" if the item is blocked by independent branches,
1526
1527 "book_reserved" if the there are holds aganst the item, or
1528
1529 "linked_analytics" if the item has linked analytic records.
1530
1531 =cut
1532
1533 sub ItemSafeToDelete {
1534     my ( $biblionumber, $itemnumber ) = @_;
1535     my $status;
1536     my $dbh = C4::Context->dbh;
1537
1538     my $error;
1539
1540     my $countanalytics = GetAnalyticsCount($itemnumber);
1541
1542     my $item = Koha::Items->find($itemnumber) or return;
1543
1544     if ($item->checkout) {
1545         $status = "book_on_loan";
1546     }
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 ) )
1551     {
1552         $status = "not_same_branch";
1553     }
1554     else {
1555         # check it doesn't have a waiting reserve
1556         my $sth = $dbh->prepare(
1557             q{
1558             SELECT COUNT(*) FROM reserves
1559             WHERE (found = 'W' OR found = 'T')
1560             AND itemnumber = ?
1561         }
1562         );
1563         $sth->execute($itemnumber);
1564         my ($reserve) = $sth->fetchrow;
1565         if ($reserve) {
1566             $status = "book_reserved";
1567         }
1568         elsif ( $countanalytics > 0 ) {
1569             $status = "linked_analytics";
1570         }
1571         else {
1572             $status = 1;
1573         }
1574     }
1575     return $status;
1576 }
1577
1578 =head2 DelItemCheck
1579
1580    DelItemCheck( $biblionumber, $itemnumber);
1581
1582 Exported function (core API) for deleting an item record in Koha if there no current issue.
1583
1584 DelItemCheck wraps ItemSafeToDelete around DelItem.
1585
1586 =cut
1587
1588 sub DelItemCheck {
1589     my ( $biblionumber, $itemnumber ) = @_;
1590     my $status = ItemSafeToDelete( $biblionumber, $itemnumber );
1591
1592     if ( $status == 1 ) {
1593         DelItem(
1594             {
1595                 biblionumber => $biblionumber,
1596                 itemnumber   => $itemnumber
1597             }
1598         );
1599     }
1600     return $status;
1601 }
1602
1603 =head2 _koha_modify_item
1604
1605   my ($itemnumber,$error) =_koha_modify_item( $item );
1606
1607 Perform the actual update of the C<items> row.  Note that this
1608 routine accepts a hashref specifying the columns to update.
1609
1610 =cut
1611
1612 sub _koha_modify_item {
1613     my ( $item ) = @_;
1614     my $dbh=C4::Context->dbh;  
1615     my $error;
1616
1617     my $query = "UPDATE items SET ";
1618     my @bind;
1619     _mod_item_dates( $item );
1620     for my $key ( keys %$item ) {
1621         next if ( $key eq 'itemnumber' );
1622         $query.="$key=?,";
1623         push @bind, $item->{$key};
1624     }
1625     $query =~ s/,$//;
1626     $query .= " WHERE itemnumber=?";
1627     push @bind, $item->{'itemnumber'};
1628     my $sth = $dbh->prepare($query);
1629     $sth->execute(@bind);
1630     if ( $sth->err ) {
1631         $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
1632         warn $error;
1633     }
1634     return ($item->{'itemnumber'},$error);
1635 }
1636
1637 sub _mod_item_dates { # date formatting for date fields in item hash
1638     my ( $item ) = @_;
1639     return if !$item || ref($item) ne 'HASH';
1640
1641     my @keys = grep
1642         { $_ =~ /^onloan$|^date|date$|datetime$/ }
1643         keys %$item;
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
1647
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
1652
1653         my $newstr;
1654         if( defined $dt  && ref($dt) eq 'DateTime' ) {
1655             if( $key =~ /datetime/ ) {
1656                 $newstr = DateTime::Format::MySQL->format_datetime($dt);
1657             } else {
1658                 $newstr = DateTime::Format::MySQL->format_date($dt);
1659             }
1660         }
1661         $item->{$key} = $newstr; # might be undef to clear garbage
1662     }
1663 }
1664
1665 =head2 _koha_delete_item
1666
1667   _koha_delete_item( $itemnum );
1668
1669 Internal function to delete an item record from the koha tables
1670
1671 =cut
1672
1673 sub _koha_delete_item {
1674     my ( $itemnum ) = @_;
1675
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();
1681
1682     # There is no item to delete
1683     return 0 unless $data;
1684
1685     my $query = "INSERT INTO deleteditems SET ";
1686     my @bind  = ();
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} );
1691     }
1692     $query =~ s/\,$//;
1693     $sth = $dbh->prepare($query);
1694     $sth->execute(@bind);
1695
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;
1700 }
1701
1702 =head2 _marc_from_item_hash
1703
1704   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1705
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.
1709
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
1713 of the item.
1714
1715 =cut
1716
1717 sub _marc_from_item_hash {
1718     my $item = shift;
1719     my $frameworkcode = shift;
1720     my $unlinked_item_subfields;
1721     if (@_) {
1722         $unlinked_item_subfields = shift;
1723     }
1724    
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 } }; 
1730
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 );
1739             } else {
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;
1743             }
1744             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
1745             }
1746         }
1747     }
1748
1749     return $item_marc;
1750 }
1751
1752 =head2 _repack_item_errors
1753
1754 Add an error message hash generated by C<CheckItemPreSave>
1755 to a list of errors.
1756
1757 =cut
1758
1759 sub _repack_item_errors {
1760     my $item_sequence_num = shift;
1761     my $item_ref = shift;
1762     my $error_ref = shift;
1763
1764     my @repacked_errors = ();
1765
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;
1773     } 
1774
1775     return @repacked_errors;
1776 }
1777
1778 =head2 _get_unlinked_item_subfields
1779
1780   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
1781
1782 =cut
1783
1784 sub _get_unlinked_item_subfields {
1785     my $original_item_marc = shift;
1786     my $frameworkcode = shift;
1787
1788     my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
1789
1790     # assume that this record has only one field, and that that
1791     # field contains only the item information
1792     my $subfields = [];
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];
1802             }
1803         }
1804     }
1805     return $subfields;
1806 }
1807
1808 =head2 _get_unlinked_subfields_xml
1809
1810   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
1811
1812 =cut
1813
1814 sub _get_unlinked_subfields_xml {
1815     my $unlinked_item_subfields = shift;
1816
1817     my $xml;
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");
1825     }
1826
1827     return $xml;
1828 }
1829
1830 =head2 _parse_unlinked_item_subfields_from_xml
1831
1832   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
1833
1834 =cut
1835
1836 sub  _parse_unlinked_item_subfields_from_xml {
1837     my $xml = shift;
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];
1846         }
1847     }
1848     return $unlinked_subfields;
1849 }
1850
1851 =head2 GetAnalyticsCount
1852
1853   $count= &GetAnalyticsCount($itemnumber)
1854
1855 counts Usage of itemnumber in Analytical bibliorecords. 
1856
1857 =cut
1858
1859 sub GetAnalyticsCount {
1860     my ($itemnumber) = @_;
1861
1862     ### ZOOM search here
1863     my $query;
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);
1867     return ($result);
1868 }
1869
1870 sub _SearchItems_build_where_fragment {
1871     my ($filter) = @_;
1872
1873     my $dbh = C4::Context->dbh;
1874
1875     my $where_fragment;
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);
1880             if ($fragment) {
1881                 push @where_strs, $fragment->{str};
1882                 push @where_args, @{ $fragment->{args} };
1883             }
1884         }
1885         my $where_str = '';
1886         if (@where_strs) {
1887             $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
1888             $where_fragment = {
1889                 str => $where_str,
1890                 args => \@where_args,
1891             };
1892         }
1893     } else {
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};
1902
1903             if (!$op or (0 == grep { $_ eq $op } @operators)) {
1904                 $op = '='; # default operator
1905             }
1906
1907             my $column;
1908             if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
1909                 my $marcfield = $1;
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);
1915
1916                 if ($kohafield) {
1917                     $column = $kohafield;
1918                 } else {
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.
1922                     my $xpath;
1923                     my $sqlfield;
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 . '"]';
1928                     } else {
1929                         $sqlfield = 'metadata'; # From biblio_metadata
1930                         if ($marcfield < 10) {
1931                             $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
1932                         } else {
1933                             $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
1934                         }
1935                     }
1936                     $column = "ExtractValue($sqlfield, '$xpath')";
1937                 }
1938             } elsif ($field eq 'issues') {
1939                 # Consider NULL as 0 for issues count
1940                 $column = 'COALESCE(issues,0)';
1941             } else {
1942                 $column = $field;
1943             }
1944
1945             if (ref $query eq 'ARRAY') {
1946                 if ($op eq '=') {
1947                     $op = 'IN';
1948                 } elsif ($op eq '!=') {
1949                     $op = 'NOT IN';
1950                 }
1951                 $where_fragment = {
1952                     str => "$column $op (" . join (',', ('?') x @$query) . ")",
1953                     args => $query,
1954                 };
1955             } else {
1956                 $where_fragment = {
1957                     str => "$column $op ?",
1958                     args => [ $query ],
1959                 };
1960             }
1961         }
1962     }
1963
1964     return $where_fragment;
1965 }
1966
1967 =head2 SearchItems
1968
1969     my ($items, $total) = SearchItems($filter, $params);
1970
1971 Perform a search among items
1972
1973 $filter is a reference to a hash which can be a filter, or a combination of filters.
1974
1975 A filter has the following keys:
1976
1977 =over 2
1978
1979 =item * field: the name of a SQL column in table items
1980
1981 =item * query: the value to search in this column
1982
1983 =item * operator: comparison operator. Can be one of = != > < >= <= like
1984
1985 =back
1986
1987 A combination of filters hash the following keys:
1988
1989 =over 2
1990
1991 =item * conjunction: 'AND' or 'OR'
1992
1993 =item * filters: array ref of filters
1994
1995 =back
1996
1997 $params is a reference to a hash that can contain the following parameters:
1998
1999 =over 2
2000
2001 =item * rows: Number of items to return. 0 returns everything (default: 0)
2002
2003 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2004                (default: 1)
2005
2006 =item * sortby: A SQL column name in items table to sort on
2007
2008 =item * sortorder: 'ASC' or 'DESC'
2009
2010 =back
2011
2012 =cut
2013
2014 sub SearchItems {
2015     my ($filter, $params) = @_;
2016
2017     $filter //= {};
2018     $params //= {};
2019     return unless ref $filter eq 'HASH';
2020     return unless ref $params eq 'HASH';
2021
2022     # Default parameters
2023     $params->{rows} ||= 0;
2024     $params->{page} ||= 1;
2025     $params->{sortby} ||= 'itemnumber';
2026     $params->{sortorder} ||= 'ASC';
2027
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} };
2033     }
2034
2035     my $dbh = C4::Context->dbh;
2036     my $query = q{
2037         SELECT SQL_CALC_FOUND_ROWS items.*
2038         FROM 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
2042           WHERE 1
2043     };
2044     if (defined $where_str and $where_str ne '') {
2045         $query .= qq{ AND $where_str };
2046     }
2047
2048     $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.schema = ? };
2049     push @where_args, C4::Context->preference('marcflavour');
2050
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 };
2058
2059     my $rows = $params->{rows};
2060     my @limit_args;
2061     if ($rows > 0) {
2062         my $offset = $rows * ($params->{page}-1);
2063         $query .= qq { LIMIT ?, ? };
2064         push @limit_args, $offset, $rows;
2065     }
2066
2067     my $sth = $dbh->prepare($query);
2068     my $rv = $sth->execute(@where_args, @limit_args);
2069
2070     return unless ($rv);
2071     my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2072
2073     return ($sth->fetchall_arrayref({}), $total_rows);
2074 }
2075
2076
2077 =head1  OTHER FUNCTIONS
2078
2079 =head2 _find_value
2080
2081   ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2082
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
2086 returned.
2087
2088 PROPOSITION :
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.
2091
2092 =cut
2093
2094 sub _find_value {
2095     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2096     my @result;
2097     my $indicator;
2098     if ( $tagfield < 10 ) {
2099         if ( $record->field($tagfield) ) {
2100             push @result, $record->field($tagfield)->data();
2101         } else {
2102             push @result, "";
2103         }
2104     } else {
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);
2111                 }
2112             }
2113         }
2114     }
2115     return ( $indicator, @result );
2116 }
2117
2118
2119 =head2 PrepareItemrecordDisplay
2120
2121   PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2122
2123 Returns a hash with all the fields for Display a given item data in a template
2124
2125 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2126
2127 =cut
2128
2129 sub PrepareItemrecordDisplay {
2130
2131     my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2132
2133     my $dbh = C4::Context->dbh;
2134     $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum;
2135     my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
2136
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 } );
2141
2142     # return nothing if we don't have found an existing framework.
2143     return q{} unless $tagslib;
2144     my $itemrecord;
2145     if ($itemnum) {
2146         $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2147     }
2148     my @loop_data;
2149
2150     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2151     my $query = qq{
2152         SELECT authorised_value,lib FROM authorised_values
2153     };
2154     $query .= qq{
2155         LEFT JOIN authorised_values_branches ON ( id = av_id )
2156     } if $branch_limit;
2157     $query .= qq{
2158         WHERE category = ?
2159     };
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} ) {
2164         if ( $tag ne '' ) {
2165
2166             # loop through each subfield
2167             my $cntsubf;
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" );
2172                 my %subfield_data;
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));
2178
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 );
2187                 if ($itemrecord) {
2188                     ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2189                 }
2190                 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2191                 if ( !defined $defaultvalue ) {
2192                     $defaultvalue = q||;
2193                 } else {
2194                     $defaultvalue =~ s/"/&quot;/g;
2195                 }
2196
2197                 my $maxlength = $tagslib->{$tag}->{$subfield}->{maxlength};
2198
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;
2208                     }
2209                 }
2210                 if (   $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2211                     && $defaultvalues
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};
2219                     }
2220                 }
2221                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2222                     && $defaultvalues
2223                     && $defaultvalues->{'branchcode'} ) {
2224                     if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2225                         $defaultvalue = $defaultvalues->{branchcode};
2226                     }
2227                 }
2228                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2229                     && $defaultvalues
2230                     && $defaultvalues->{'location'} ) {
2231
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};
2238                     }
2239                 }
2240                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2241                     my @authorised_values;
2242                     my %authorised_lib;
2243
2244                     # builds list, depending on authorised value...
2245                     #---- branch
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;
2256                             }
2257                         } else {
2258                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2259                             $sth->execute;
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;
2265                             }
2266                         }
2267
2268                         $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2269                         if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2270                             $defaultvalue = $defaultvalues->{branchcode};
2271                         }
2272
2273                         #----- itemtypes
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;
2281                         }
2282                         if ($defaultvalues && $defaultvalues->{'itemtype'}) {
2283                             $defaultvalue = $defaultvalues->{'itemtype'};
2284                         }
2285
2286                         #---- class_sources
2287                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2288                         push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2289
2290                         my $class_sources = GetClassSources();
2291                         my $default_source = $defaultvalue || C4::Context->preference("DefaultClassificationSource");
2292
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'};
2298                         }
2299
2300                         $defaultvalue = $default_source;
2301
2302                         #---- "true" authorised value
2303                     } else {
2304                         $authorised_values_sth->execute(
2305                             $tagslib->{$tag}->{$subfield}->{authorised_value},
2306                             $branch_limit ? $branch_limit : ()
2307                         );
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;
2313                         }
2314                     }
2315                     $subfield_data{marc_value} = {
2316                         type    => 'select',
2317                         values  => \@authorised_values,
2318                         default => $defaultvalue // q{},
2319                         labels  => \%authorised_lib,
2320                     };
2321                 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2322                 # it is a plugin
2323                     require Koha::FrameworkPlugin;
2324                     my $plugin = Koha::FrameworkPlugin->new({
2325                         name => $tagslib->{$tag}->{$subfield}->{value_builder},
2326                         item_style => 1,
2327                     });
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{};
2332                     }
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;
2339                     } else {
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
2342                     }
2343                 }
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" />);
2346                 }
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" />);
2349                 }
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                     )
2355                           ) {
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");
2358                 } else {
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" />);
2360                 }
2361                 push( @loop_data, \%subfield_data );
2362             }
2363         }
2364     }
2365     my $itemnumber;
2366     if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2367         $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2368     }
2369     return {
2370         'itemtagfield'    => $itemtagfield,
2371         'itemtagsubfield' => $itemtagsubfield,
2372         'itemnumber'      => $itemnumber,
2373         'iteminformation' => \@loop_data
2374     };
2375 }
2376
2377 sub ToggleNewStatus {
2378     my ( $params ) = @_;
2379     my @rules = @{ $params->{rules} };
2380     my $report_only = $params->{report_only};
2381
2382     my $dbh = C4::Context->dbh;
2383     my @errors;
2384     my @item_columns = map { "items.$_" } Koha::Items->columns;
2385     my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
2386     my $report;
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\.(.*)/ );
2393         }
2394         my @params;
2395
2396         my $query = q|
2397             SELECT items.*
2398             FROM items
2399             LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
2400             WHERE 1
2401         |;
2402         for my $condition ( @$conditions ) {
2403             if (
2404                  grep { $_ eq $condition->{field} } @item_columns
2405               or grep { $_ eq $condition->{field} } @biblioitem_columns
2406             ) {
2407                 if ( $condition->{value} =~ /\|/ ) {
2408                     my @values = split /\|/, $condition->{value};
2409                     $query .= qq| AND $condition->{field} IN (|
2410                         . join( ',', ('?') x scalar @values )
2411                         . q|)|;
2412                     push @params, @values;
2413                 } else {
2414                     $query .= qq| AND $condition->{field} = ?|;
2415                     push @params, $condition->{value};
2416                 }
2417             }
2418         }
2419         if ( defined $age ) {
2420             $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
2421             push @params, $age;
2422         }
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;
2436             }
2437             $item->store unless $report_only;
2438         }
2439     }
2440
2441     return $report;
2442 }
2443
2444 1;