Bug 16716: Replaced wrong GROUP BY with DISTINCT
[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 strict;
22 #use warnings; FIXME - Bug 2505
23
24 use Carp;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Biblio;
28 use Koha::DateUtils;
29 use MARC::Record;
30 use C4::ClassSource;
31 use C4::Log;
32 use List::MoreUtils qw/any/;
33 use YAML qw/Load/;
34 use DateTime::Format::MySQL;
35 use Data::Dumper; # used as part of logging item record changes, not just for
36                   # debugging; so please don't remove this
37 use Koha::DateUtils qw/dt_from_string/;
38
39 use Koha::Database;
40
41 use vars qw($VERSION @ISA @EXPORT);
42
43 BEGIN {
44     $VERSION = 3.07.00.049;
45
46         require Exporter;
47     @ISA = qw( Exporter );
48
49     # function exports
50     @EXPORT = qw(
51         GetItem
52         AddItemFromMarc
53         AddItem
54         AddItemBatchFromMarc
55         ModItemFromMarc
56     Item2Marc
57         ModItem
58         ModDateLastSeen
59         ModItemTransfer
60         DelItem
61     
62         CheckItemPreSave
63     
64         GetItemStatus
65         GetItemLocation
66         GetLostItems
67         GetItemsForInventory
68         GetItemsCount
69         GetItemInfosOf
70         GetItemsByBiblioitemnumber
71         GetItemsInfo
72         GetItemsLocationInfo
73         GetHostItemsInfo
74         GetItemnumbersForBiblio
75         get_itemnumbers_of
76         get_hostitemnumbers_of
77         GetItemnumberFromBarcode
78         GetBarcodeFromItemnumber
79         GetHiddenItemnumbers
80         DelItemCheck
81     MoveItemFromBiblio
82     GetLatestAcquisitions
83
84         CartToShelf
85         ShelfToCart
86
87         GetAnalyticsCount
88         GetItemHolds
89
90         SearchItemsByField
91         SearchItems
92
93         PrepareItemrecordDisplay
94
95     );
96 }
97
98 =head1 NAME
99
100 C4::Items - item management functions
101
102 =head1 DESCRIPTION
103
104 This module contains an API for manipulating item 
105 records in Koha, and is used by cataloguing, circulation,
106 acquisitions, and serials management.
107
108 A Koha item record is stored in two places: the
109 items table and embedded in a MARC tag in the XML
110 version of the associated bib record in C<biblioitems.marcxml>.
111 This is done to allow the item information to be readily
112 indexed (e.g., by Zebra), but means that each item
113 modification transaction must keep the items table
114 and the MARC XML in sync at all times.
115
116 Consequently, all code that creates, modifies, or deletes
117 item records B<must> use an appropriate function from 
118 C<C4::Items>.  If no existing function is suitable, it is
119 better to add one to C<C4::Items> than to use add
120 one-off SQL statements to add or modify items.
121
122 The items table will be considered authoritative.  In other
123 words, if there is ever a discrepancy between the items
124 table and the MARC XML, the items table should be considered
125 accurate.
126
127 =head1 HISTORICAL NOTE
128
129 Most of the functions in C<C4::Items> were originally in
130 the C<C4::Biblio> module.
131
132 =head1 CORE EXPORTED FUNCTIONS
133
134 The following functions are meant for use by users
135 of C<C4::Items>
136
137 =cut
138
139 =head2 GetItem
140
141   $item = GetItem($itemnumber,$barcode,$serial);
142
143 Return item information, for a given itemnumber or barcode.
144 The return value is a hashref mapping item column
145 names to values.  If C<$serial> is true, include serial publication data.
146
147 =cut
148
149 sub GetItem {
150     my ($itemnumber,$barcode, $serial) = @_;
151     my $dbh = C4::Context->dbh;
152         my $data;
153
154     if ($itemnumber) {
155         my $sth = $dbh->prepare("
156             SELECT * FROM items 
157             WHERE itemnumber = ?");
158         $sth->execute($itemnumber);
159         $data = $sth->fetchrow_hashref;
160     } else {
161         my $sth = $dbh->prepare("
162             SELECT * FROM items 
163             WHERE barcode = ?"
164             );
165         $sth->execute($barcode);                
166         $data = $sth->fetchrow_hashref;
167     }
168
169     return unless ( $data );
170
171     if ( $serial) {      
172     my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
173         $ssth->execute($data->{'itemnumber'}) ;
174         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
175     }
176         #if we don't have an items.itype, use biblioitems.itemtype.
177     # FIXME this should respect the itypes systempreference
178     # if (C4::Context->preference('item-level_itypes')) {
179         if( ! $data->{'itype'} ) {
180                 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
181                 $sth->execute($data->{'biblionumber'});
182                 ($data->{'itype'}) = $sth->fetchrow_array;
183         }
184     return $data;
185 }    # sub GetItem
186
187 =head2 CartToShelf
188
189   CartToShelf($itemnumber);
190
191 Set the current shelving location of the item record
192 to its stored permanent shelving location.  This is
193 primarily used to indicate when an item whose current
194 location is a special processing ('PROC') or shelving cart
195 ('CART') location is back in the stacks.
196
197 =cut
198
199 sub CartToShelf {
200     my ( $itemnumber ) = @_;
201
202     unless ( $itemnumber ) {
203         croak "FAILED CartToShelf() - no itemnumber supplied";
204     }
205
206     my $item = GetItem($itemnumber);
207     if ( $item->{location} eq 'CART' ) {
208         $item->{location} = $item->{permanent_location};
209         ModItem($item, undef, $itemnumber);
210     }
211 }
212
213 =head2 ShelfToCart
214
215   ShelfToCart($itemnumber);
216
217 Set the current shelving location of the item
218 to shelving cart ('CART').
219
220 =cut
221
222 sub ShelfToCart {
223     my ( $itemnumber ) = @_;
224
225     unless ( $itemnumber ) {
226         croak "FAILED ShelfToCart() - no itemnumber supplied";
227     }
228
229     my $item = GetItem($itemnumber);
230     $item->{'location'} = 'CART';
231     ModItem($item, undef, $itemnumber);
232 }
233
234 =head2 AddItemFromMarc
235
236   my ($biblionumber, $biblioitemnumber, $itemnumber) 
237       = AddItemFromMarc($source_item_marc, $biblionumber);
238
239 Given a MARC::Record object containing an embedded item
240 record and a biblionumber, create a new item record.
241
242 =cut
243
244 sub AddItemFromMarc {
245     my ( $source_item_marc, $biblionumber ) = @_;
246     my $dbh = C4::Context->dbh;
247
248     # parse item hash from MARC
249     my $frameworkcode = GetFrameworkCode( $biblionumber );
250         my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
251         
252         my $localitemmarc=MARC::Record->new;
253         $localitemmarc->append_fields($source_item_marc->field($itemtag));
254     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
255     my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
256     return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
257 }
258
259 =head2 AddItem
260
261   my ($biblionumber, $biblioitemnumber, $itemnumber) 
262       = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
263
264 Given a hash containing item column names as keys,
265 create a new Koha item record.
266
267 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
268 do not need to be supplied for general use; they exist
269 simply to allow them to be picked up from AddItemFromMarc.
270
271 The final optional parameter, C<$unlinked_item_subfields>, contains
272 an arrayref containing subfields present in the original MARC
273 representation of the item (e.g., from the item editor) that are
274 not mapped to C<items> columns directly but should instead
275 be stored in C<items.more_subfields_xml> and included in 
276 the biblio items tag for display and indexing.
277
278 =cut
279
280 sub AddItem {
281     my $item = shift;
282     my $biblionumber = shift;
283
284     my $dbh           = @_ ? shift : C4::Context->dbh;
285     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
286     my $unlinked_item_subfields;  
287     if (@_) {
288         $unlinked_item_subfields = shift
289     };
290
291     # needs old biblionumber and biblioitemnumber
292     $item->{'biblionumber'} = $biblionumber;
293     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
294     $sth->execute( $item->{'biblionumber'} );
295     ($item->{'biblioitemnumber'}) = $sth->fetchrow;
296
297     _set_defaults_for_add($item);
298     _set_derived_columns_for_add($item);
299     $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
300     # FIXME - checks here
301     unless ( $item->{itype} ) {  # default to biblioitem.itemtype if no itype
302         my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
303         $itype_sth->execute( $item->{'biblionumber'} );
304         ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
305     }
306
307         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
308     $item->{'itemnumber'} = $itemnumber;
309
310     ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
311    
312     logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
313     
314     return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
315 }
316
317 =head2 AddItemBatchFromMarc
318
319   ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
320              $biblionumber, $biblioitemnumber, $frameworkcode);
321
322 Efficiently create item records from a MARC biblio record with
323 embedded item fields.  This routine is suitable for batch jobs.
324
325 This API assumes that the bib record has already been
326 saved to the C<biblio> and C<biblioitems> tables.  It does
327 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
328 are populated, but it will do so via a call to ModBibiloMarc.
329
330 The goal of this API is to have a similar effect to using AddBiblio
331 and AddItems in succession, but without inefficient repeated
332 parsing of the MARC XML bib record.
333
334 This function returns an arrayref of new itemsnumbers and an arrayref of item
335 errors encountered during the processing.  Each entry in the errors
336 list is a hashref containing the following keys:
337
338 =over
339
340 =item item_sequence
341
342 Sequence number of original item tag in the MARC record.
343
344 =item item_barcode
345
346 Item barcode, provide to assist in the construction of
347 useful error messages.
348
349 =item error_code
350
351 Code representing the error condition.  Can be 'duplicate_barcode',
352 'invalid_homebranch', or 'invalid_holdingbranch'.
353
354 =item error_information
355
356 Additional information appropriate to the error condition.
357
358 =back
359
360 =cut
361
362 sub AddItemBatchFromMarc {
363     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
364     my $error;
365     my @itemnumbers = ();
366     my @errors = ();
367     my $dbh = C4::Context->dbh;
368
369     # We modify the record, so lets work on a clone so we don't change the
370     # original.
371     $record = $record->clone();
372     # loop through the item tags and start creating items
373     my @bad_item_fields = ();
374     my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
375     my $item_sequence_num = 0;
376     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
377         $item_sequence_num++;
378         # we take the item field and stick it into a new
379         # MARC record -- this is required so far because (FIXME)
380         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
381         # and there is no TransformMarcFieldToKoha
382         my $temp_item_marc = MARC::Record->new();
383         $temp_item_marc->append_fields($item_field);
384     
385         # add biblionumber and biblioitemnumber
386         my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
387         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
388         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
389         $item->{'biblionumber'} = $biblionumber;
390         $item->{'biblioitemnumber'} = $biblioitemnumber;
391
392         # check for duplicate barcode
393         my %item_errors = CheckItemPreSave($item);
394         if (%item_errors) {
395             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
396             push @bad_item_fields, $item_field;
397             next ITEMFIELD;
398         }
399
400         _set_defaults_for_add($item);
401         _set_derived_columns_for_add($item);
402         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
403         warn $error if $error;
404         push @itemnumbers, $itemnumber; # FIXME not checking error
405         $item->{'itemnumber'} = $itemnumber;
406
407         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
408
409         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
410         $item_field->replace_with($new_item_marc->field($itemtag));
411     }
412
413     # remove any MARC item fields for rejected items
414     foreach my $item_field (@bad_item_fields) {
415         $record->delete_field($item_field);
416     }
417
418     # update the MARC biblio
419  #   $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
420
421     return (\@itemnumbers, \@errors);
422 }
423
424 =head2 ModItemFromMarc
425
426   ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
427
428 This function updates an item record based on a supplied
429 C<MARC::Record> object containing an embedded item field.
430 This API is meant for the use of C<additem.pl>; for 
431 other purposes, C<ModItem> should be used.
432
433 This function uses the hash %default_values_for_mod_from_marc,
434 which contains default values for item fields to
435 apply when modifying an item.  This is needed because
436 if an item field's value is cleared, TransformMarcToKoha
437 does not include the column in the
438 hash that's passed to ModItem, which without
439 use of this hash makes it impossible to clear
440 an item field's value.  See bug 2466.
441
442 Note that only columns that can be directly
443 changed from the cataloging and serials
444 item editors are included in this hash.
445
446 Returns item record
447
448 =cut
449
450 sub _build_default_values_for_mod_marc {
451     my ($frameworkcode) = @_;
452
453     my $cache     = Koha::Cache->get_instance();
454     my $cache_key = "default_value_for_mod_marc-$frameworkcode";
455     my $cached    = $cache->get_from_cache($cache_key);
456     return $cached if $cached;
457
458     my $default_values = {
459         barcode                  => undef,
460         booksellerid             => undef,
461         ccode                    => undef,
462         'items.cn_source'        => undef,
463         coded_location_qualifier => undef,
464         copynumber               => undef,
465         damaged                  => 0,
466         enumchron                => undef,
467         holdingbranch            => undef,
468         homebranch               => undef,
469         itemcallnumber           => undef,
470         itemlost                 => 0,
471         itemnotes                => undef,
472         itemnotes_nonpublic      => undef,
473         itype                    => undef,
474         location                 => undef,
475         permanent_location       => undef,
476         materials                => undef,
477         notforloan               => 0,
478         # paidfor => undef, # commented, see bug 12817
479         price                    => undef,
480         replacementprice         => undef,
481         replacementpricedate     => undef,
482         restricted               => undef,
483         stack                    => undef,
484         stocknumber              => undef,
485         uri                      => undef,
486         withdrawn                => 0,
487     };
488     my %default_values_for_mod_from_marc;
489     while ( my ( $field, $default_value ) = each %$default_values ) {
490         my $kohafield = $field;
491         $kohafield =~ s|^([^\.]+)$|items.$1|;
492         $default_values_for_mod_from_marc{$field} =
493           $default_value
494           if C4::Koha::IsKohaFieldLinked(
495             { kohafield => $kohafield, frameworkcode => $frameworkcode } );
496     }
497
498     $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
499     return \%default_values_for_mod_from_marc;
500 }
501
502 sub ModItemFromMarc {
503     my $item_marc = shift;
504     my $biblionumber = shift;
505     my $itemnumber = shift;
506
507     my $dbh           = C4::Context->dbh;
508     my $frameworkcode = GetFrameworkCode($biblionumber);
509     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
510
511     my $localitemmarc = MARC::Record->new;
512     $localitemmarc->append_fields( $item_marc->field($itemtag) );
513     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
514     my $default_values = _build_default_values_for_mod_marc($frameworkcode);
515     foreach my $item_field ( keys %$default_values ) {
516         $item->{$item_field} = $default_values->{$item_field}
517           unless exists $item->{$item_field};
518     }
519     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
520
521     ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields); 
522     return $item;
523 }
524
525 =head2 ModItem
526
527   ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
528
529 Change one or more columns in an item record and update
530 the MARC representation of the item.
531
532 The first argument is a hashref mapping from item column
533 names to the new values.  The second and third arguments
534 are the biblionumber and itemnumber, respectively.
535
536 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
537 an arrayref containing subfields present in the original MARC
538 representation of the item (e.g., from the item editor) that are
539 not mapped to C<items> columns directly but should instead
540 be stored in C<items.more_subfields_xml> and included in 
541 the biblio items tag for display and indexing.
542
543 If one of the changed columns is used to calculate
544 the derived value of a column such as C<items.cn_sort>, 
545 this routine will perform the necessary calculation
546 and set the value.
547
548 =cut
549
550 sub ModItem {
551     my $item = shift;
552     my $biblionumber = shift;
553     my $itemnumber = shift;
554
555     # if $biblionumber is undefined, get it from the current item
556     unless (defined $biblionumber) {
557         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
558     }
559
560     my $dbh           = @_ ? shift : C4::Context->dbh;
561     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
562     
563     my $unlinked_item_subfields;  
564     if (@_) {
565         $unlinked_item_subfields = shift;
566         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
567     };
568
569     $item->{'itemnumber'} = $itemnumber or return;
570
571     my @fields = qw( itemlost withdrawn );
572
573     # Only call GetItem if we need to set an "on" date field
574     if ( $item->{itemlost} || $item->{withdrawn} ) {
575         my $pre_mod_item = GetItem( $item->{'itemnumber'} );
576         for my $field (@fields) {
577             if (    defined( $item->{$field} )
578                 and not $pre_mod_item->{$field}
579                 and $item->{$field} )
580             {
581                 $item->{ $field . '_on' } =
582                   DateTime::Format::MySQL->format_datetime( dt_from_string() );
583             }
584         }
585     }
586
587     # If the field is defined but empty, we are removing and,
588     # and thus need to clear out the 'on' field as well
589     for my $field (@fields) {
590         if ( defined( $item->{$field} ) && !$item->{$field} ) {
591             $item->{ $field . '_on' } = undef;
592         }
593     }
594
595
596     _set_derived_columns_for_mod($item);
597     _do_column_fixes_for_mod($item);
598     # FIXME add checks
599     # duplicate barcode
600     # attempt to change itemnumber
601     # attempt to change biblionumber (if we want
602     # an API to relink an item to a different bib,
603     # it should be a separate function)
604
605     # update items table
606     _koha_modify_item($item);
607
608     # request that bib be reindexed so that searching on current
609     # item status is possible
610     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
611
612     logaction("CATALOGUING", "MODIFY", $itemnumber, "item ".Dumper($item)) if C4::Context->preference("CataloguingLog");
613 }
614
615 =head2 ModItemTransfer
616
617   ModItemTransfer($itenumber, $frombranch, $tobranch);
618
619 Marks an item as being transferred from one branch
620 to another.
621
622 =cut
623
624 sub ModItemTransfer {
625     my ( $itemnumber, $frombranch, $tobranch ) = @_;
626
627     my $dbh = C4::Context->dbh;
628
629     # Remove the 'shelving cart' location status if it is being used.
630     CartToShelf( $itemnumber ) if ( C4::Context->preference("ReturnToShelvingCart") );
631
632     #new entry in branchtransfers....
633     my $sth = $dbh->prepare(
634         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
635         VALUES (?, ?, NOW(), ?)");
636     $sth->execute($itemnumber, $frombranch, $tobranch);
637
638     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
639     ModDateLastSeen($itemnumber);
640     return;
641 }
642
643 =head2 ModDateLastSeen
644
645   ModDateLastSeen($itemnum);
646
647 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
648 C<$itemnum> is the item number
649
650 =cut
651
652 sub ModDateLastSeen {
653     my ($itemnumber) = @_;
654     
655     my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
656     ModItem({ itemlost => 0, datelastseen => $today }, undef, $itemnumber);
657 }
658
659 =head2 DelItem
660
661   DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
662
663 Exported function (core API) for deleting an item record in Koha.
664
665 =cut
666
667 sub DelItem {
668     my ( $params ) = @_;
669
670     my $itemnumber   = $params->{itemnumber};
671     my $biblionumber = $params->{biblionumber};
672
673     unless ($biblionumber) {
674         $biblionumber = C4::Biblio::GetBiblionumberFromItemnumber($itemnumber);
675     }
676
677     # If there is no biblionumber for the given itemnumber, there is nothing to delete
678     return 0 unless $biblionumber;
679
680     # FIXME check the item has no current issues
681     my $deleted = _koha_delete_item( $itemnumber );
682
683     # get the MARC record
684     my $record = GetMarcBiblio($biblionumber);
685     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
686
687     #search item field code
688     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
689     return $deleted;
690 }
691
692 =head2 CheckItemPreSave
693
694     my $item_ref = TransformMarcToKoha($marc, 'items');
695     # do stuff
696     my %errors = CheckItemPreSave($item_ref);
697     if (exists $errors{'duplicate_barcode'}) {
698         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
699     } elsif (exists $errors{'invalid_homebranch'}) {
700         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
701     } elsif (exists $errors{'invalid_holdingbranch'}) {
702         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
703     } else {
704         print "item is OK";
705     }
706
707 Given a hashref containing item fields, determine if it can be
708 inserted or updated in the database.  Specifically, checks for
709 database integrity issues, and returns a hash containing any
710 of the following keys, if applicable.
711
712 =over 2
713
714 =item duplicate_barcode
715
716 Barcode, if it duplicates one already found in the database.
717
718 =item invalid_homebranch
719
720 Home branch, if not defined in branches table.
721
722 =item invalid_holdingbranch
723
724 Holding branch, if not defined in branches table.
725
726 =back
727
728 This function does NOT implement any policy-related checks,
729 e.g., whether current operator is allowed to save an
730 item that has a given branch code.
731
732 =cut
733
734 sub CheckItemPreSave {
735     my $item_ref = shift;
736     require C4::Branch;
737
738     my %errors = ();
739
740     # check for duplicate barcode
741     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
742         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
743         if ($existing_itemnumber) {
744             if (!exists $item_ref->{'itemnumber'}                       # new item
745                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
746                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
747             }
748         }
749     }
750
751     # check for valid home branch
752     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
753         my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
754         unless (defined $branch_name) {
755             # relies on fact that branches.branchname is a non-NULL column,
756             # so GetBranchName returns undef only if branch does not exist
757             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
758         }
759     }
760
761     # check for valid holding branch
762     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
763         my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
764         unless (defined $branch_name) {
765             # relies on fact that branches.branchname is a non-NULL column,
766             # so GetBranchName returns undef only if branch does not exist
767             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
768         }
769     }
770
771     return %errors;
772
773 }
774
775 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
776
777 The following functions provide various ways of 
778 getting an item record, a set of item records, or
779 lists of authorized values for certain item fields.
780
781 Some of the functions in this group are candidates
782 for refactoring -- for example, some of the code
783 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
784 has copy-and-paste work.
785
786 =cut
787
788 =head2 GetItemStatus
789
790   $itemstatushash = GetItemStatus($fwkcode);
791
792 Returns a list of valid values for the
793 C<items.notforloan> field.
794
795 NOTE: does B<not> return an individual item's
796 status.
797
798 Can be MARC dependent.
799 fwkcode is optional.
800 But basically could be can be loan or not
801 Create a status selector with the following code
802
803 =head3 in PERL SCRIPT
804
805  my $itemstatushash = getitemstatus;
806  my @itemstatusloop;
807  foreach my $thisstatus (keys %$itemstatushash) {
808      my %row =(value => $thisstatus,
809                  statusname => $itemstatushash->{$thisstatus}->{'statusname'},
810              );
811      push @itemstatusloop, \%row;
812  }
813  $template->param(statusloop=>\@itemstatusloop);
814
815 =head3 in TEMPLATE
816
817 <select name="statusloop" id="statusloop">
818     <option value="">Default</option>
819     [% FOREACH statusloo IN statusloop %]
820         [% IF ( statusloo.selected ) %]
821             <option value="[% statusloo.value %]" selected="selected">[% statusloo.statusname %]</option>
822         [% ELSE %]
823             <option value="[% statusloo.value %]">[% statusloo.statusname %]</option>
824         [% END %]
825     [% END %]
826 </select>
827
828 =cut
829
830 sub GetItemStatus {
831
832     # returns a reference to a hash of references to status...
833     my ($fwk) = @_;
834     my %itemstatus;
835     my $dbh = C4::Context->dbh;
836     my $sth;
837     $fwk = '' unless ($fwk);
838     my ( $tag, $subfield ) =
839       GetMarcFromKohaField( "items.notforloan", $fwk );
840     if ( $tag and $subfield ) {
841         my $sth =
842           $dbh->prepare(
843             "SELECT authorised_value
844             FROM marc_subfield_structure
845             WHERE tagfield=?
846                 AND tagsubfield=?
847                 AND frameworkcode=?
848             "
849           );
850         $sth->execute( $tag, $subfield, $fwk );
851         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
852             my $authvalsth =
853               $dbh->prepare(
854                 "SELECT authorised_value,lib
855                 FROM authorised_values 
856                 WHERE category=? 
857                 ORDER BY lib
858                 "
859               );
860             $authvalsth->execute($authorisedvaluecat);
861             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
862                 $itemstatus{$authorisedvalue} = $lib;
863             }
864             return \%itemstatus;
865             exit 1;
866         }
867         else {
868
869             #No authvalue list
870             # build default
871         }
872     }
873
874     #No authvalue list
875     #build default
876     $itemstatus{"1"} = "Not For Loan";
877     return \%itemstatus;
878 }
879
880 =head2 GetItemLocation
881
882   $itemlochash = GetItemLocation($fwk);
883
884 Returns a list of valid values for the
885 C<items.location> field.
886
887 NOTE: does B<not> return an individual item's
888 location.
889
890 where fwk stands for an optional framework code.
891 Create a location selector with the following code
892
893 =head3 in PERL SCRIPT
894
895   my $itemlochash = getitemlocation;
896   my @itemlocloop;
897   foreach my $thisloc (keys %$itemlochash) {
898       my $selected = 1 if $thisbranch eq $branch;
899       my %row =(locval => $thisloc,
900                   selected => $selected,
901                   locname => $itemlochash->{$thisloc},
902                );
903       push @itemlocloop, \%row;
904   }
905   $template->param(itemlocationloop => \@itemlocloop);
906
907 =head3 in TEMPLATE
908
909   <select name="location">
910       <option value="">Default</option>
911   <!-- TMPL_LOOP name="itemlocationloop" -->
912       <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
913   <!-- /TMPL_LOOP -->
914   </select>
915
916 =cut
917
918 sub GetItemLocation {
919
920     # returns a reference to a hash of references to location...
921     my ($fwk) = @_;
922     my %itemlocation;
923     my $dbh = C4::Context->dbh;
924     my $sth;
925     $fwk = '' unless ($fwk);
926     my ( $tag, $subfield ) =
927       GetMarcFromKohaField( "items.location", $fwk );
928     if ( $tag and $subfield ) {
929         my $sth =
930           $dbh->prepare(
931             "SELECT authorised_value
932             FROM marc_subfield_structure 
933             WHERE tagfield=? 
934                 AND tagsubfield=? 
935                 AND frameworkcode=?"
936           );
937         $sth->execute( $tag, $subfield, $fwk );
938         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
939             my $authvalsth =
940               $dbh->prepare(
941                 "SELECT authorised_value,lib
942                 FROM authorised_values
943                 WHERE category=?
944                 ORDER BY lib"
945               );
946             $authvalsth->execute($authorisedvaluecat);
947             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
948                 $itemlocation{$authorisedvalue} = $lib;
949             }
950             return \%itemlocation;
951             exit 1;
952         }
953         else {
954
955             #No authvalue list
956             # build default
957         }
958     }
959
960     #No authvalue list
961     #build default
962     $itemlocation{"1"} = "Not For Loan";
963     return \%itemlocation;
964 }
965
966 =head2 GetLostItems
967
968   $items = GetLostItems( $where );
969
970 This function gets a list of lost items.
971
972 =over 2
973
974 =item input:
975
976 C<$where> is a hashref. it containts a field of the items table as key
977 and the value to match as value. For example:
978
979 { barcode    => 'abc123',
980   homebranch => 'CPL',    }
981
982 =item return:
983
984 C<$items> is a reference to an array full of hashrefs with columns
985 from the "items" table as keys.
986
987 =item usage in the perl script:
988
989   my $where = { barcode => '0001548' };
990   my $items = GetLostItems( $where );
991   $template->param( itemsloop => $items );
992
993 =back
994
995 =cut
996
997 sub GetLostItems {
998     # Getting input args.
999     my $where   = shift;
1000     my $dbh     = C4::Context->dbh;
1001
1002     my $query   = "
1003         SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
1004                itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber, itemcallnumber
1005         FROM   items
1006             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
1007             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
1008             LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
1009         WHERE
1010                 authorised_values.category = 'LOST'
1011                 AND itemlost IS NOT NULL
1012                 AND itemlost <> 0
1013     ";
1014     my @query_parameters;
1015     foreach my $key (keys %$where) {
1016         $query .= " AND $key LIKE ?";
1017         push @query_parameters, "%$where->{$key}%";
1018     }
1019
1020     my $sth = $dbh->prepare($query);
1021     $sth->execute( @query_parameters );
1022     my $items = [];
1023     while ( my $row = $sth->fetchrow_hashref ){
1024         push @$items, $row;
1025     }
1026     return $items;
1027 }
1028
1029 =head2 GetItemsForInventory
1030
1031 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
1032   minlocation  => $minlocation,
1033   maxlocation  => $maxlocation,
1034   location     => $location,
1035   itemtype     => $itemtype,
1036   ignoreissued => $ignoreissued,
1037   datelastseen => $datelastseen,
1038   branchcode   => $branchcode,
1039   branch       => $branch,
1040   offset       => $offset,
1041   size         => $size,
1042   statushash   => $statushash,
1043   interface    => $interface,
1044 } );
1045
1046 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1047
1048 The sub returns a reference to a list of hashes, each containing
1049 itemnumber, author, title, barcode, item callnumber, and date last
1050 seen. It is ordered by callnumber then title.
1051
1052 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1053 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1054 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1055 $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.
1056
1057 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
1058
1059 =cut
1060
1061 sub GetItemsForInventory {
1062     my ( $parameters ) = @_;
1063     my $minlocation  = $parameters->{'minlocation'}  // '';
1064     my $maxlocation  = $parameters->{'maxlocation'}  // '';
1065     my $location     = $parameters->{'location'}     // '';
1066     my $itemtype     = $parameters->{'itemtype'}     // '';
1067     my $ignoreissued = $parameters->{'ignoreissued'} // '';
1068     my $datelastseen = $parameters->{'datelastseen'} // '';
1069     my $branchcode   = $parameters->{'branchcode'}   // '';
1070     my $branch       = $parameters->{'branch'}       // '';
1071     my $offset       = $parameters->{'offset'}       // '';
1072     my $size         = $parameters->{'size'}         // '';
1073     my $statushash   = $parameters->{'statushash'}   // '';
1074     my $interface    = $parameters->{'interface'}    // '';
1075
1076     my $dbh = C4::Context->dbh;
1077     my ( @bind_params, @where_strings );
1078
1079     my $select_columns = q{
1080         SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
1081     };
1082     my $select_count = q{SELECT COUNT(*)};
1083     my $query = q{
1084         FROM items
1085         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1086         LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1087     };
1088     if ($statushash){
1089         for my $authvfield (keys %$statushash){
1090             if ( scalar @{$statushash->{$authvfield}} > 0 ){
1091                 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1092                 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1093             }
1094         }
1095     }
1096
1097     if ($minlocation) {
1098         push @where_strings, 'itemcallnumber >= ?';
1099         push @bind_params, $minlocation;
1100     }
1101
1102     if ($maxlocation) {
1103         push @where_strings, 'itemcallnumber <= ?';
1104         push @bind_params, $maxlocation;
1105     }
1106
1107     if ($datelastseen) {
1108         $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
1109         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1110         push @bind_params, $datelastseen;
1111     }
1112
1113     if ( $location ) {
1114         push @where_strings, 'items.location = ?';
1115         push @bind_params, $location;
1116     }
1117
1118     if ( $branchcode ) {
1119         if($branch eq "homebranch"){
1120         push @where_strings, 'items.homebranch = ?';
1121         }else{
1122             push @where_strings, 'items.holdingbranch = ?';
1123         }
1124         push @bind_params, $branchcode;
1125     }
1126
1127     if ( $itemtype ) {
1128         push @where_strings, 'biblioitems.itemtype = ?';
1129         push @bind_params, $itemtype;
1130     }
1131
1132     if ( $ignoreissued) {
1133         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1134         push @where_strings, 'issues.date_due IS NULL';
1135     }
1136
1137     if ( @where_strings ) {
1138         $query .= 'WHERE ';
1139         $query .= join ' AND ', @where_strings;
1140     }
1141     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1142     my $count_query = $select_count . $query;
1143     $query .= " LIMIT $offset, $size" if ($offset and $size);
1144     $query = $select_columns . $query;
1145     my $sth = $dbh->prepare($query);
1146     $sth->execute( @bind_params );
1147
1148     my @results = ();
1149     my $tmpresults = $sth->fetchall_arrayref({});
1150     $sth = $dbh->prepare( $count_query );
1151     $sth->execute( @bind_params );
1152     my ($iTotalRecords) = $sth->fetchrow_array();
1153
1154     my $avmapping = C4::Koha::GetKohaAuthorisedValuesMapping( {
1155                       interface => $interface
1156                     } );
1157     foreach my $row (@$tmpresults) {
1158
1159         # Auth values
1160         foreach (keys %$row) {
1161             if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
1162                 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
1163             }
1164         }
1165         push @results, $row;
1166     }
1167
1168     return (\@results, $iTotalRecords);
1169 }
1170
1171 =head2 GetItemsCount
1172
1173   $count = &GetItemsCount( $biblionumber);
1174
1175 This function return count of item with $biblionumber
1176
1177 =cut
1178
1179 sub GetItemsCount {
1180     my ( $biblionumber ) = @_;
1181     my $dbh = C4::Context->dbh;
1182     my $query = "SELECT count(*)
1183           FROM  items 
1184           WHERE biblionumber=?";
1185     my $sth = $dbh->prepare($query);
1186     $sth->execute($biblionumber);
1187     my $count = $sth->fetchrow;  
1188     return ($count);
1189 }
1190
1191 =head2 GetItemInfosOf
1192
1193   GetItemInfosOf(@itemnumbers);
1194
1195 =cut
1196
1197 sub GetItemInfosOf {
1198     my @itemnumbers = @_;
1199
1200     my $itemnumber_values = @itemnumbers ? join( ',', @itemnumbers ) : "''";
1201
1202     my $query = "
1203         SELECT *
1204         FROM items
1205         WHERE itemnumber IN ($itemnumber_values)
1206     ";
1207     return get_infos_of( $query, 'itemnumber' );
1208 }
1209
1210 =head2 GetItemsByBiblioitemnumber
1211
1212   GetItemsByBiblioitemnumber($biblioitemnumber);
1213
1214 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1215 Called by C<C4::XISBN>
1216
1217 =cut
1218
1219 sub GetItemsByBiblioitemnumber {
1220     my ( $bibitem ) = @_;
1221     my $dbh = C4::Context->dbh;
1222     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1223     # Get all items attached to a biblioitem
1224     my $i = 0;
1225     my @results; 
1226     $sth->execute($bibitem) || die $sth->errstr;
1227     while ( my $data = $sth->fetchrow_hashref ) {  
1228         # Foreach item, get circulation information
1229         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1230                                    WHERE itemnumber = ?
1231                                    AND issues.borrowernumber = borrowers.borrowernumber"
1232         );
1233         $sth2->execute( $data->{'itemnumber'} );
1234         if ( my $data2 = $sth2->fetchrow_hashref ) {
1235             # if item is out, set the due date and who it is out too
1236             $data->{'date_due'}   = $data2->{'date_due'};
1237             $data->{'cardnumber'} = $data2->{'cardnumber'};
1238             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1239         }
1240         else {
1241             # set date_due to blank, so in the template we check itemlost, and withdrawn
1242             $data->{'date_due'} = '';                                                                                                         
1243         }    # else         
1244         # Find the last 3 people who borrowed this item.                  
1245         my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1246                       AND old_issues.borrowernumber = borrowers.borrowernumber
1247                       ORDER BY returndate desc,timestamp desc LIMIT 3";
1248         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1249         $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1250         my $i2 = 0;
1251         while ( my $data2 = $sth2->fetchrow_hashref ) {
1252             $data->{"timestamp$i2"} = $data2->{'timestamp'};
1253             $data->{"card$i2"}      = $data2->{'cardnumber'};
1254             $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1255             $i2++;
1256         }
1257         push(@results,$data);
1258     } 
1259     return (\@results); 
1260 }
1261
1262 =head2 GetItemsInfo
1263
1264   @results = GetItemsInfo($biblionumber);
1265
1266 Returns information about items with the given biblionumber.
1267
1268 C<GetItemsInfo> returns a list of references-to-hash. Each element
1269 contains a number of keys. Most of them are attributes from the
1270 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1271 Koha database. Other keys include:
1272
1273 =over 2
1274
1275 =item C<$data-E<gt>{branchname}>
1276
1277 The name (not the code) of the branch to which the book belongs.
1278
1279 =item C<$data-E<gt>{datelastseen}>
1280
1281 This is simply C<items.datelastseen>, except that while the date is
1282 stored in YYYY-MM-DD format in the database, here it is converted to
1283 DD/MM/YYYY format. A NULL date is returned as C<//>.
1284
1285 =item C<$data-E<gt>{datedue}>
1286
1287 =item C<$data-E<gt>{class}>
1288
1289 This is the concatenation of C<biblioitems.classification>, the book's
1290 Dewey code, and C<biblioitems.subclass>.
1291
1292 =item C<$data-E<gt>{ocount}>
1293
1294 I think this is the number of copies of the book available.
1295
1296 =item C<$data-E<gt>{order}>
1297
1298 If this is set, it is set to C<One Order>.
1299
1300 =back
1301
1302 =cut
1303
1304 sub GetItemsInfo {
1305     my ( $biblionumber ) = @_;
1306     my $dbh   = C4::Context->dbh;
1307     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1308     require C4::Languages;
1309     my $language = C4::Languages::getlanguage();
1310     my $query = "
1311     SELECT items.*,
1312            biblio.*,
1313            biblioitems.volume,
1314            biblioitems.number,
1315            biblioitems.itemtype,
1316            biblioitems.isbn,
1317            biblioitems.issn,
1318            biblioitems.publicationyear,
1319            biblioitems.publishercode,
1320            biblioitems.volumedate,
1321            biblioitems.volumedesc,
1322            biblioitems.lccn,
1323            biblioitems.url,
1324            items.notforloan as itemnotforloan,
1325            issues.borrowernumber,
1326            issues.date_due as datedue,
1327            issues.onsite_checkout,
1328            borrowers.cardnumber,
1329            borrowers.surname,
1330            borrowers.firstname,
1331            borrowers.branchcode as bcode,
1332            serial.serialseq,
1333            serial.publisheddate,
1334            itemtypes.description,
1335            COALESCE( localization.translation, itemtypes.description ) AS translated_description,
1336            itemtypes.notforloan as notforloan_per_itemtype,
1337            holding.branchurl,
1338            holding.branchname,
1339            holding.opac_info as holding_branch_opac_info,
1340            home.opac_info as home_branch_opac_info
1341     ";
1342     $query .= "
1343      FROM items
1344      LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1345      LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1346      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
1347      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1348      LEFT JOIN issues USING (itemnumber)
1349      LEFT JOIN borrowers USING (borrowernumber)
1350      LEFT JOIN serialitems USING (itemnumber)
1351      LEFT JOIN serial USING (serialid)
1352      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
1353      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1354     $query .= q|
1355     LEFT JOIN localization ON itemtypes.itemtype = localization.code
1356         AND localization.entity = 'itemtypes'
1357         AND localization.lang = ?
1358     |;
1359
1360     $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1361     my $sth = $dbh->prepare($query);
1362     $sth->execute($language, $biblionumber);
1363     my $i = 0;
1364     my @results;
1365     my $serial;
1366
1367     my $userenv = C4::Context->userenv;
1368     my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
1369     while ( my $data = $sth->fetchrow_hashref ) {
1370         if ( $data->{borrowernumber} && $want_not_same_branch) {
1371             $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
1372         }
1373
1374         $serial ||= $data->{'serial'};
1375
1376         # get notforloan complete status if applicable
1377         if ( my $code = C4::Koha::GetAuthValCode( 'items.notforloan', $data->{frameworkcode} ) ) {
1378             $data->{notforloanvalue}     = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan} );
1379             $data->{notforloanvalueopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan}, 1 );
1380         }
1381
1382         # get restricted status and description if applicable
1383         if ( my $code = C4::Koha::GetAuthValCode( 'items.restricted', $data->{frameworkcode} ) ) {
1384             $data->{restrictedopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted}, 1 );
1385             $data->{restricted}     = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
1386         }
1387
1388         # my stack procedures
1389         if ( my $code = C4::Koha::GetAuthValCode( 'items.stack', $data->{frameworkcode} ) ) {
1390             $data->{stack}          = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{stack} );
1391         }
1392
1393         # Find the last 3 people who borrowed this item.
1394         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1395                                     WHERE itemnumber = ?
1396                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1397                                     ORDER BY returndate DESC
1398                                     LIMIT 3");
1399         $sth2->execute($data->{'itemnumber'});
1400         my $ii = 0;
1401         while (my $data2 = $sth2->fetchrow_hashref()) {
1402             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1403             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1404             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1405             $ii++;
1406         }
1407
1408         $results[$i] = $data;
1409         $i++;
1410     }
1411
1412     return $serial
1413         ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
1414         : @results;
1415 }
1416
1417 =head2 GetItemsLocationInfo
1418
1419   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1420
1421 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1422
1423 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1424
1425 =over 2
1426
1427 =item C<$data-E<gt>{homebranch}>
1428
1429 Branch Name of the item's homebranch
1430
1431 =item C<$data-E<gt>{holdingbranch}>
1432
1433 Branch Name of the item's holdingbranch
1434
1435 =item C<$data-E<gt>{location}>
1436
1437 Item's shelving location code
1438
1439 =item C<$data-E<gt>{location_intranet}>
1440
1441 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1442
1443 =item C<$data-E<gt>{location_opac}>
1444
1445 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
1446 description is set.
1447
1448 =item C<$data-E<gt>{itemcallnumber}>
1449
1450 Item's itemcallnumber
1451
1452 =item C<$data-E<gt>{cn_sort}>
1453
1454 Item's call number normalized for sorting
1455
1456 =back
1457   
1458 =cut
1459
1460 sub GetItemsLocationInfo {
1461         my $biblionumber = shift;
1462         my @results;
1463
1464         my $dbh = C4::Context->dbh;
1465         my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch, 
1466                             location, itemcallnumber, cn_sort
1467                      FROM items, branches as a, branches as b
1468                      WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode 
1469                      AND biblionumber = ?
1470                      ORDER BY cn_sort ASC";
1471         my $sth = $dbh->prepare($query);
1472         $sth->execute($biblionumber);
1473
1474         while ( my $data = $sth->fetchrow_hashref ) {
1475              $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1476              $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1477              push @results, $data;
1478         }
1479         return @results;
1480 }
1481
1482 =head2 GetHostItemsInfo
1483
1484         $hostiteminfo = GetHostItemsInfo($hostfield);
1485         Returns the iteminfo for items linked to records via a host field
1486
1487 =cut
1488
1489 sub GetHostItemsInfo {
1490         my ($record) = @_;
1491         my @returnitemsInfo;
1492
1493         if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1494         C4::Context->preference('marcflavour') eq 'NORMARC'){
1495             foreach my $hostfield ( $record->field('773') ) {
1496                 my $hostbiblionumber = $hostfield->subfield("0");
1497                 my $linkeditemnumber = $hostfield->subfield("9");
1498                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1499                 foreach my $hostitemInfo (@hostitemInfos){
1500                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1501                                 push (@returnitemsInfo,$hostitemInfo);
1502                                 last;
1503                         }
1504                 }
1505             }
1506         } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1507             foreach my $hostfield ( $record->field('461') ) {
1508                 my $hostbiblionumber = $hostfield->subfield("0");
1509                 my $linkeditemnumber = $hostfield->subfield("9");
1510                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1511                 foreach my $hostitemInfo (@hostitemInfos){
1512                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1513                                 push (@returnitemsInfo,$hostitemInfo);
1514                                 last;
1515                         }
1516                 }
1517             }
1518         }
1519         return @returnitemsInfo;
1520 }
1521
1522
1523 =head2 GetLastAcquisitions
1524
1525   my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
1526                                     'itemtypes' => ('BK','BD')}, 10);
1527
1528 =cut
1529
1530 sub  GetLastAcquisitions {
1531         my ($data,$max) = @_;
1532
1533         my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1534         
1535         my $number_of_branches = @{$data->{branches}};
1536         my $number_of_itemtypes   = @{$data->{itemtypes}};
1537         
1538         
1539         my @where = ('WHERE 1 '); 
1540         $number_of_branches and push @where
1541            , 'AND holdingbranch IN (' 
1542            , join(',', ('?') x $number_of_branches )
1543            , ')'
1544          ;
1545         
1546         $number_of_itemtypes and push @where
1547            , "AND $itemtype IN (" 
1548            , join(',', ('?') x $number_of_itemtypes )
1549            , ')'
1550          ;
1551
1552         my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1553                                  FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber) 
1554                                     RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1555                                     @where
1556                                     GROUP BY biblio.biblionumber 
1557                                     ORDER BY dateaccessioned DESC LIMIT $max";
1558
1559         my $dbh = C4::Context->dbh;
1560         my $sth = $dbh->prepare($query);
1561     
1562     $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1563         
1564         my @results;
1565         while( my $row = $sth->fetchrow_hashref){
1566                 push @results, {date => $row->{dateaccessioned} 
1567                                                 , biblionumber => $row->{biblionumber}
1568                                                 , title => $row->{title}};
1569         }
1570         
1571         return @results;
1572 }
1573
1574 =head2 GetItemnumbersForBiblio
1575
1576   my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1577
1578 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1579
1580 =cut
1581
1582 sub GetItemnumbersForBiblio {
1583     my $biblionumber = shift;
1584     my @items;
1585     my $dbh = C4::Context->dbh;
1586     my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1587     $sth->execute($biblionumber);
1588     while (my $result = $sth->fetchrow_hashref) {
1589         push @items, $result->{'itemnumber'};
1590     }
1591     return \@items;
1592 }
1593
1594 =head2 get_itemnumbers_of
1595
1596   my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1597
1598 Given a list of biblionumbers, return the list of corresponding itemnumbers
1599 for each biblionumber.
1600
1601 Return a reference on a hash where keys are biblionumbers and values are
1602 references on array of itemnumbers.
1603
1604 =cut
1605
1606 sub get_itemnumbers_of {
1607     my @biblionumbers = @_;
1608
1609     my $dbh = C4::Context->dbh;
1610
1611     my $query = '
1612         SELECT itemnumber,
1613             biblionumber
1614         FROM items
1615         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1616     ';
1617     my $sth = $dbh->prepare($query);
1618     $sth->execute(@biblionumbers);
1619
1620     my %itemnumbers_of;
1621
1622     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1623         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1624     }
1625
1626     return \%itemnumbers_of;
1627 }
1628
1629 =head2 get_hostitemnumbers_of
1630
1631   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1632
1633 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1634
1635 Return a reference on a hash where key is a biblionumber and values are
1636 references on array of itemnumbers.
1637
1638 =cut
1639
1640
1641 sub get_hostitemnumbers_of {
1642         my ($biblionumber) = @_;
1643         my $marcrecord = GetMarcBiblio($biblionumber);
1644         my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1645         
1646         my $marcflavor = C4::Context->preference('marcflavour');
1647         if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1648         $tag='773';
1649         $biblio_s='0';
1650         $item_s='9';
1651     } elsif ($marcflavor eq 'UNIMARC') {
1652         $tag='461';
1653         $biblio_s='0';
1654         $item_s='9';
1655     }
1656
1657     foreach my $hostfield ( $marcrecord->field($tag) ) {
1658         my $hostbiblionumber = $hostfield->subfield($biblio_s);
1659         my $linkeditemnumber = $hostfield->subfield($item_s);
1660         my @itemnumbers;
1661         if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1662         {
1663             @itemnumbers = @$itemnumbers;
1664         }
1665         foreach my $itemnumber (@itemnumbers){
1666             if ($itemnumber eq $linkeditemnumber){
1667                 push (@returnhostitemnumbers,$itemnumber);
1668                 last;
1669             }
1670         }
1671     }
1672     return @returnhostitemnumbers;
1673 }
1674
1675
1676 =head2 GetItemnumberFromBarcode
1677
1678   $result = GetItemnumberFromBarcode($barcode);
1679
1680 =cut
1681
1682 sub GetItemnumberFromBarcode {
1683     my ($barcode) = @_;
1684     my $dbh = C4::Context->dbh;
1685
1686     my $rq =
1687       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1688     $rq->execute($barcode);
1689     my ($result) = $rq->fetchrow;
1690     return ($result);
1691 }
1692
1693 =head2 GetBarcodeFromItemnumber
1694
1695   $result = GetBarcodeFromItemnumber($itemnumber);
1696
1697 =cut
1698
1699 sub GetBarcodeFromItemnumber {
1700     my ($itemnumber) = @_;
1701     my $dbh = C4::Context->dbh;
1702
1703     my $rq =
1704       $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1705     $rq->execute($itemnumber);
1706     my ($result) = $rq->fetchrow;
1707     return ($result);
1708 }
1709
1710 =head2 GetHiddenItemnumbers
1711
1712     my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
1713
1714 Given a list of items it checks which should be hidden from the OPAC given
1715 the current configuration. Returns a list of itemnumbers corresponding to
1716 those that should be hidden.
1717
1718 =cut
1719
1720 sub GetHiddenItemnumbers {
1721     my (@items) = @_;
1722     my @resultitems;
1723
1724     my $yaml = C4::Context->preference('OpacHiddenItems');
1725     return () if (! $yaml =~ /\S/ );
1726     $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1727     my $hidingrules;
1728     eval {
1729         $hidingrules = YAML::Load($yaml);
1730     };
1731     if ($@) {
1732         warn "Unable to parse OpacHiddenItems syspref : $@";
1733         return ();
1734     }
1735     my $dbh = C4::Context->dbh;
1736
1737     # For each item
1738     foreach my $item (@items) {
1739
1740         # We check each rule
1741         foreach my $field (keys %$hidingrules) {
1742             my $val;
1743             if (exists $item->{$field}) {
1744                 $val = $item->{$field};
1745             }
1746             else {
1747                 my $query = "SELECT $field from items where itemnumber = ?";
1748                 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1749             }
1750             $val = '' unless defined $val;
1751
1752             # If the results matches the values in the yaml file
1753             if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1754
1755                 # We add the itemnumber to the list
1756                 push @resultitems, $item->{'itemnumber'};
1757
1758                 # If at least one rule matched for an item, no need to test the others
1759                 last;
1760             }
1761         }
1762     }
1763     return @resultitems;
1764 }
1765
1766 =head3 get_item_authorised_values
1767
1768 find the types and values for all authorised values assigned to this item.
1769
1770 parameters: itemnumber
1771
1772 returns: a hashref malling the authorised value to the value set for this itemnumber
1773
1774     $authorised_values = {
1775              'CCODE'      => undef,
1776              'DAMAGED'    => '0',
1777              'LOC'        => '3',
1778              'LOST'       => '0'
1779              'NOT_LOAN'   => '0',
1780              'RESTRICTED' => undef,
1781              'STACK'      => undef,
1782              'WITHDRAWN'  => '0',
1783              'branches'   => 'CPL',
1784              'cn_source'  => undef,
1785              'itemtypes'  => 'SER',
1786            };
1787
1788 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1789
1790 =cut
1791
1792 sub get_item_authorised_values {
1793     my $itemnumber = shift;
1794
1795     # assume that these entries in the authorised_value table are item level.
1796     my $query = q(SELECT distinct authorised_value, kohafield
1797                     FROM marc_subfield_structure
1798                     WHERE kohafield like 'item%'
1799                       AND authorised_value != '' );
1800
1801     my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1802     my $iteminfo = GetItem( $itemnumber );
1803     # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1804     my $return;
1805     foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1806         my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1807         $field =~ s/^items\.//;
1808         if ( exists $iteminfo->{ $field } ) {
1809             $return->{ $this_authorised_value } = $iteminfo->{ $field };
1810         }
1811     }
1812     # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1813     return $return;
1814 }
1815
1816 =head3 get_authorised_value_images
1817
1818 find a list of icons that are appropriate for display based on the
1819 authorised values for a biblio.
1820
1821 parameters: listref of authorised values, such as comes from
1822 get_item_authorised_values or
1823 from C4::Biblio::get_biblio_authorised_values
1824
1825 returns: listref of hashrefs for each image. Each hashref looks like this:
1826
1827       { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1828         label    => '',
1829         category => '',
1830         value    => '', }
1831
1832 Notes: Currently, I put on the full path to the images on the staff
1833 side. This should either be configurable or not done at all. Since I
1834 have to deal with 'intranet' or 'opac' in
1835 get_biblio_authorised_values, perhaps I should be passing it in.
1836
1837 =cut
1838
1839 sub get_authorised_value_images {
1840     my $authorised_values = shift;
1841
1842     my @imagelist;
1843
1844     my $authorised_value_list = GetAuthorisedValues();
1845     # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1846     foreach my $this_authorised_value ( @$authorised_value_list ) {
1847         if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1848              && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1849             # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1850             if ( defined $this_authorised_value->{'imageurl'} ) {
1851                 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1852                                    label    => $this_authorised_value->{'lib'},
1853                                    category => $this_authorised_value->{'category'},
1854                                    value    => $this_authorised_value->{'authorised_value'}, };
1855             }
1856         }
1857     }
1858
1859     # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1860     return \@imagelist;
1861
1862 }
1863
1864 =head1 LIMITED USE FUNCTIONS
1865
1866 The following functions, while part of the public API,
1867 are not exported.  This is generally because they are
1868 meant to be used by only one script for a specific
1869 purpose, and should not be used in any other context
1870 without careful thought.
1871
1872 =cut
1873
1874 =head2 GetMarcItem
1875
1876   my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1877
1878 Returns MARC::Record of the item passed in parameter.
1879 This function is meant for use only in C<cataloguing/additem.pl>,
1880 where it is needed to support that script's MARC-like
1881 editor.
1882
1883 =cut
1884
1885 sub GetMarcItem {
1886     my ( $biblionumber, $itemnumber ) = @_;
1887
1888     # GetMarcItem has been revised so that it does the following:
1889     #  1. Gets the item information from the items table.
1890     #  2. Converts it to a MARC field for storage in the bib record.
1891     #
1892     # The previous behavior was:
1893     #  1. Get the bib record.
1894     #  2. Return the MARC tag corresponding to the item record.
1895     #
1896     # The difference is that one treats the items row as authoritative,
1897     # while the other treats the MARC representation as authoritative
1898     # under certain circumstances.
1899
1900     my $itemrecord = GetItem($itemnumber);
1901
1902     # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1903     # Also, don't emit a subfield if the underlying field is blank.
1904
1905     
1906     return Item2Marc($itemrecord,$biblionumber);
1907
1908 }
1909 sub Item2Marc {
1910         my ($itemrecord,$biblionumber)=@_;
1911     my $mungeditem = { 
1912         map {  
1913             defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  
1914         } keys %{ $itemrecord } 
1915     };
1916     my $itemmarc = TransformKohaToMarc($mungeditem);
1917     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1918
1919     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1920     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1921                 foreach my $field ($itemmarc->field($itemtag)){
1922             $field->add_subfields(@$unlinked_item_subfields);
1923         }
1924     }
1925         return $itemmarc;
1926 }
1927
1928 =head1 PRIVATE FUNCTIONS AND VARIABLES
1929
1930 The following functions are not meant to be called
1931 directly, but are documented in order to explain
1932 the inner workings of C<C4::Items>.
1933
1934 =cut
1935
1936 =head2 %derived_columns
1937
1938 This hash keeps track of item columns that
1939 are strictly derived from other columns in
1940 the item record and are not meant to be set
1941 independently.
1942
1943 Each key in the hash should be the name of a
1944 column (as named by TransformMarcToKoha).  Each
1945 value should be hashref whose keys are the
1946 columns on which the derived column depends.  The
1947 hashref should also contain a 'BUILDER' key
1948 that is a reference to a sub that calculates
1949 the derived value.
1950
1951 =cut
1952
1953 my %derived_columns = (
1954     'items.cn_sort' => {
1955         'itemcallnumber' => 1,
1956         'items.cn_source' => 1,
1957         'BUILDER' => \&_calc_items_cn_sort,
1958     }
1959 );
1960
1961 =head2 _set_derived_columns_for_add 
1962
1963   _set_derived_column_for_add($item);
1964
1965 Given an item hash representing a new item to be added,
1966 calculate any derived columns.  Currently the only
1967 such column is C<items.cn_sort>.
1968
1969 =cut
1970
1971 sub _set_derived_columns_for_add {
1972     my $item = shift;
1973
1974     foreach my $column (keys %derived_columns) {
1975         my $builder = $derived_columns{$column}->{'BUILDER'};
1976         my $source_values = {};
1977         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1978             next if $source_column eq 'BUILDER';
1979             $source_values->{$source_column} = $item->{$source_column};
1980         }
1981         $builder->($item, $source_values);
1982     }
1983 }
1984
1985 =head2 _set_derived_columns_for_mod 
1986
1987   _set_derived_column_for_mod($item);
1988
1989 Given an item hash representing a new item to be modified.
1990 calculate any derived columns.  Currently the only
1991 such column is C<items.cn_sort>.
1992
1993 This routine differs from C<_set_derived_columns_for_add>
1994 in that it needs to handle partial item records.  In other
1995 words, the caller of C<ModItem> may have supplied only one
1996 or two columns to be changed, so this function needs to
1997 determine whether any of the columns to be changed affect
1998 any of the derived columns.  Also, if a derived column
1999 depends on more than one column, but the caller is not
2000 changing all of then, this routine retrieves the unchanged
2001 values from the database in order to ensure a correct
2002 calculation.
2003
2004 =cut
2005
2006 sub _set_derived_columns_for_mod {
2007     my $item = shift;
2008
2009     foreach my $column (keys %derived_columns) {
2010         my $builder = $derived_columns{$column}->{'BUILDER'};
2011         my $source_values = {};
2012         my %missing_sources = ();
2013         my $must_recalc = 0;
2014         foreach my $source_column (keys %{ $derived_columns{$column} }) {
2015             next if $source_column eq 'BUILDER';
2016             if (exists $item->{$source_column}) {
2017                 $must_recalc = 1;
2018                 $source_values->{$source_column} = $item->{$source_column};
2019             } else {
2020                 $missing_sources{$source_column} = 1;
2021             }
2022         }
2023         if ($must_recalc) {
2024             foreach my $source_column (keys %missing_sources) {
2025                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
2026             }
2027             $builder->($item, $source_values);
2028         }
2029     }
2030 }
2031
2032 =head2 _do_column_fixes_for_mod
2033
2034   _do_column_fixes_for_mod($item);
2035
2036 Given an item hashref containing one or more
2037 columns to modify, fix up certain values.
2038 Specifically, set to 0 any passed value
2039 of C<notforloan>, C<damaged>, C<itemlost>, or
2040 C<withdrawn> that is either undefined or
2041 contains the empty string.
2042
2043 =cut
2044
2045 sub _do_column_fixes_for_mod {
2046     my $item = shift;
2047
2048     if (exists $item->{'notforloan'} and
2049         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
2050         $item->{'notforloan'} = 0;
2051     }
2052     if (exists $item->{'damaged'} and
2053         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
2054         $item->{'damaged'} = 0;
2055     }
2056     if (exists $item->{'itemlost'} and
2057         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
2058         $item->{'itemlost'} = 0;
2059     }
2060     if (exists $item->{'withdrawn'} and
2061         (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
2062         $item->{'withdrawn'} = 0;
2063     }
2064     if (exists $item->{location}
2065         and $item->{location} ne 'CART'
2066         and $item->{location} ne 'PROC'
2067         and not $item->{permanent_location}
2068     ) {
2069         $item->{'permanent_location'} = $item->{'location'};
2070     }
2071     if (exists $item->{'timestamp'}) {
2072         delete $item->{'timestamp'};
2073     }
2074 }
2075
2076 =head2 _get_single_item_column
2077
2078   _get_single_item_column($column, $itemnumber);
2079
2080 Retrieves the value of a single column from an C<items>
2081 row specified by C<$itemnumber>.
2082
2083 =cut
2084
2085 sub _get_single_item_column {
2086     my $column = shift;
2087     my $itemnumber = shift;
2088     
2089     my $dbh = C4::Context->dbh;
2090     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2091     $sth->execute($itemnumber);
2092     my ($value) = $sth->fetchrow();
2093     return $value; 
2094 }
2095
2096 =head2 _calc_items_cn_sort
2097
2098   _calc_items_cn_sort($item, $source_values);
2099
2100 Helper routine to calculate C<items.cn_sort>.
2101
2102 =cut
2103
2104 sub _calc_items_cn_sort {
2105     my $item = shift;
2106     my $source_values = shift;
2107
2108     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2109 }
2110
2111 =head2 _set_defaults_for_add 
2112
2113   _set_defaults_for_add($item_hash);
2114
2115 Given an item hash representing an item to be added, set
2116 correct default values for columns whose default value
2117 is not handled by the DBMS.  This includes the following
2118 columns:
2119
2120 =over 2
2121
2122 =item * 
2123
2124 C<items.dateaccessioned>
2125
2126 =item *
2127
2128 C<items.notforloan>
2129
2130 =item *
2131
2132 C<items.damaged>
2133
2134 =item *
2135
2136 C<items.itemlost>
2137
2138 =item *
2139
2140 C<items.withdrawn>
2141
2142 =back
2143
2144 =cut
2145
2146 sub _set_defaults_for_add {
2147     my $item = shift;
2148     $item->{dateaccessioned} ||= output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2149     $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
2150 }
2151
2152 =head2 _koha_new_item
2153
2154   my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2155
2156 Perform the actual insert into the C<items> table.
2157
2158 =cut
2159
2160 sub _koha_new_item {
2161     my ( $item, $barcode ) = @_;
2162     my $dbh=C4::Context->dbh;  
2163     my $error;
2164     $item->{permanent_location} //= $item->{location};
2165     my $query =
2166            "INSERT INTO items SET
2167             biblionumber        = ?,
2168             biblioitemnumber    = ?,
2169             barcode             = ?,
2170             dateaccessioned     = ?,
2171             booksellerid        = ?,
2172             homebranch          = ?,
2173             price               = ?,
2174             replacementprice    = ?,
2175             replacementpricedate = ?,
2176             datelastborrowed    = ?,
2177             datelastseen        = ?,
2178             stack               = ?,
2179             notforloan          = ?,
2180             damaged             = ?,
2181             itemlost            = ?,
2182             withdrawn           = ?,
2183             itemcallnumber      = ?,
2184             coded_location_qualifier = ?,
2185             restricted          = ?,
2186             itemnotes           = ?,
2187             itemnotes_nonpublic = ?,
2188             holdingbranch       = ?,
2189             paidfor             = ?,
2190             location            = ?,
2191             permanent_location  = ?,
2192             onloan              = ?,
2193             issues              = ?,
2194             renewals            = ?,
2195             reserves            = ?,
2196             cn_source           = ?,
2197             cn_sort             = ?,
2198             ccode               = ?,
2199             itype               = ?,
2200             materials           = ?,
2201             uri                 = ?,
2202             enumchron           = ?,
2203             more_subfields_xml  = ?,
2204             copynumber          = ?,
2205             stocknumber         = ?
2206           ";
2207     my $sth = $dbh->prepare($query);
2208     my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2209    $sth->execute(
2210             $item->{'biblionumber'},
2211             $item->{'biblioitemnumber'},
2212             $barcode,
2213             $item->{'dateaccessioned'},
2214             $item->{'booksellerid'},
2215             $item->{'homebranch'},
2216             $item->{'price'},
2217             $item->{'replacementprice'},
2218             $item->{'replacementpricedate'} || $today,
2219             $item->{datelastborrowed},
2220             $item->{datelastseen} || $today,
2221             $item->{stack},
2222             $item->{'notforloan'},
2223             $item->{'damaged'},
2224             $item->{'itemlost'},
2225             $item->{'withdrawn'},
2226             $item->{'itemcallnumber'},
2227             $item->{'coded_location_qualifier'},
2228             $item->{'restricted'},
2229             $item->{'itemnotes'},
2230             $item->{'itemnotes_nonpublic'},
2231             $item->{'holdingbranch'},
2232             $item->{'paidfor'},
2233             $item->{'location'},
2234             $item->{'permanent_location'},
2235             $item->{'onloan'},
2236             $item->{'issues'},
2237             $item->{'renewals'},
2238             $item->{'reserves'},
2239             $item->{'items.cn_source'},
2240             $item->{'items.cn_sort'},
2241             $item->{'ccode'},
2242             $item->{'itype'},
2243             $item->{'materials'},
2244             $item->{'uri'},
2245             $item->{'enumchron'},
2246             $item->{'more_subfields_xml'},
2247             $item->{'copynumber'},
2248             $item->{'stocknumber'},
2249     );
2250
2251     my $itemnumber;
2252     if ( defined $sth->errstr ) {
2253         $error.="ERROR in _koha_new_item $query".$sth->errstr;
2254     }
2255     else {
2256         $itemnumber = $dbh->{'mysql_insertid'};
2257     }
2258
2259     return ( $itemnumber, $error );
2260 }
2261
2262 =head2 MoveItemFromBiblio
2263
2264   MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2265
2266 Moves an item from a biblio to another
2267
2268 Returns undef if the move failed or the biblionumber of the destination record otherwise
2269
2270 =cut
2271
2272 sub MoveItemFromBiblio {
2273     my ($itemnumber, $frombiblio, $tobiblio) = @_;
2274     my $dbh = C4::Context->dbh;
2275     my ( $tobiblioitem ) = $dbh->selectrow_array(q|
2276         SELECT biblioitemnumber
2277         FROM biblioitems
2278         WHERE biblionumber = ?
2279     |, undef, $tobiblio );
2280     my $return = $dbh->do(q|
2281         UPDATE items
2282         SET biblioitemnumber = ?,
2283             biblionumber = ?
2284         WHERE itemnumber = ?
2285             AND biblionumber = ?
2286     |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
2287     if ($return == 1) {
2288         ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
2289         ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
2290             # Checking if the item we want to move is in an order 
2291         require C4::Acquisition;
2292         my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2293             if ($order) {
2294                     # Replacing the biblionumber within the order if necessary
2295                     $order->{'biblionumber'} = $tobiblio;
2296                 C4::Acquisition::ModOrder($order);
2297             }
2298
2299         # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
2300         for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
2301             $dbh->do( qq|
2302                 UPDATE $table_name
2303                 SET biblionumber = ?
2304                 WHERE itemnumber = ?
2305             |, undef, $tobiblio, $itemnumber );
2306         }
2307         return $tobiblio;
2308         }
2309     return;
2310 }
2311
2312 =head2 DelItemCheck
2313
2314    DelItemCheck($dbh, $biblionumber, $itemnumber);
2315
2316 Exported function (core API) for deleting an item record in Koha if there no current issue.
2317
2318 =cut
2319
2320 sub DelItemCheck {
2321     my ( $dbh, $biblionumber, $itemnumber ) = @_;
2322     my $error;
2323
2324         my $countanalytics=GetAnalyticsCount($itemnumber);
2325
2326
2327     # check that there is no issue on this item before deletion.
2328     my $sth = $dbh->prepare(q{
2329         SELECT COUNT(*) FROM issues
2330         WHERE itemnumber = ?
2331     });
2332     $sth->execute($itemnumber);
2333     my ($onloan) = $sth->fetchrow;
2334
2335     my $item = GetItem($itemnumber);
2336
2337     if ($onloan){
2338         $error = "book_on_loan" 
2339     }
2340     elsif ( !C4::Context->IsSuperLibrarian()
2341         and C4::Context->preference("IndependentBranches")
2342         and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
2343     {
2344         $error = "not_same_branch";
2345     }
2346         else{
2347         # check it doesn't have a waiting reserve
2348         $sth = $dbh->prepare(q{
2349             SELECT COUNT(*) FROM reserves
2350             WHERE (found = 'W' OR found = 'T')
2351             AND itemnumber = ?
2352         });
2353         $sth->execute($itemnumber);
2354         my ($reserve) = $sth->fetchrow;
2355         if ($reserve){
2356             $error = "book_reserved";
2357         } elsif ($countanalytics > 0){
2358                 $error = "linked_analytics";
2359         } else {
2360             DelItem(
2361                 {
2362                     biblionumber => $biblionumber,
2363                     itemnumber   => $itemnumber
2364                 }
2365             );
2366             return 1;
2367         }
2368     }
2369     return $error;
2370 }
2371
2372 =head2 _koha_modify_item
2373
2374   my ($itemnumber,$error) =_koha_modify_item( $item );
2375
2376 Perform the actual update of the C<items> row.  Note that this
2377 routine accepts a hashref specifying the columns to update.
2378
2379 =cut
2380
2381 sub _koha_modify_item {
2382     my ( $item ) = @_;
2383     my $dbh=C4::Context->dbh;  
2384     my $error;
2385
2386     my $query = "UPDATE items SET ";
2387     my @bind;
2388     for my $key ( keys %$item ) {
2389         next if ( $key eq 'itemnumber' );
2390         $query.="$key=?,";
2391         push @bind, $item->{$key};
2392     }
2393     $query =~ s/,$//;
2394     $query .= " WHERE itemnumber=?";
2395     push @bind, $item->{'itemnumber'};
2396     my $sth = $dbh->prepare($query);
2397     $sth->execute(@bind);
2398     if ( $sth->err ) {
2399         $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
2400         warn $error;
2401     }
2402     return ($item->{'itemnumber'},$error);
2403 }
2404
2405 =head2 _koha_delete_item
2406
2407   _koha_delete_item( $itemnum );
2408
2409 Internal function to delete an item record from the koha tables
2410
2411 =cut
2412
2413 sub _koha_delete_item {
2414     my ( $itemnum ) = @_;
2415
2416     my $dbh = C4::Context->dbh;
2417     # save the deleted item to deleteditems table
2418     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2419     $sth->execute($itemnum);
2420     my $data = $sth->fetchrow_hashref();
2421
2422     # There is no item to delete
2423     return 0 unless $data;
2424
2425     my $query = "INSERT INTO deleteditems SET ";
2426     my @bind  = ();
2427     foreach my $key ( keys %$data ) {
2428         next if ( $key eq 'timestamp' ); # timestamp will be set by db
2429         $query .= "$key = ?,";
2430         push( @bind, $data->{$key} );
2431     }
2432     $query =~ s/\,$//;
2433     $sth = $dbh->prepare($query);
2434     $sth->execute(@bind);
2435
2436     # delete from items table
2437     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2438     my $deleted = $sth->execute($itemnum);
2439     return ( $deleted == 1 ) ? 1 : 0;
2440 }
2441
2442 =head2 _marc_from_item_hash
2443
2444   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2445
2446 Given an item hash representing a complete item record,
2447 create a C<MARC::Record> object containing an embedded
2448 tag representing that item.
2449
2450 The third, optional parameter C<$unlinked_item_subfields> is
2451 an arrayref of subfields (not mapped to C<items> fields per the
2452 framework) to be added to the MARC representation
2453 of the item.
2454
2455 =cut
2456
2457 sub _marc_from_item_hash {
2458     my $item = shift;
2459     my $frameworkcode = shift;
2460     my $unlinked_item_subfields;
2461     if (@_) {
2462         $unlinked_item_subfields = shift;
2463     }
2464    
2465     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2466     # Also, don't emit a subfield if the underlying field is blank.
2467     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
2468                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
2469                                 : ()  } keys %{ $item } }; 
2470
2471     my $item_marc = MARC::Record->new();
2472     foreach my $item_field ( keys %{$mungeditem} ) {
2473         my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2474         next unless defined $tag and defined $subfield;    # skip if not mapped to MARC field
2475         my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2476         foreach my $value (@values){
2477             if ( my $field = $item_marc->field($tag) ) {
2478                     $field->add_subfields( $subfield => $value );
2479             } else {
2480                 my $add_subfields = [];
2481                 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2482                     $add_subfields = $unlinked_item_subfields;
2483             }
2484             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2485             }
2486         }
2487     }
2488
2489     return $item_marc;
2490 }
2491
2492 =head2 _repack_item_errors
2493
2494 Add an error message hash generated by C<CheckItemPreSave>
2495 to a list of errors.
2496
2497 =cut
2498
2499 sub _repack_item_errors {
2500     my $item_sequence_num = shift;
2501     my $item_ref = shift;
2502     my $error_ref = shift;
2503
2504     my @repacked_errors = ();
2505
2506     foreach my $error_code (sort keys %{ $error_ref }) {
2507         my $repacked_error = {};
2508         $repacked_error->{'item_sequence'} = $item_sequence_num;
2509         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2510         $repacked_error->{'error_code'} = $error_code;
2511         $repacked_error->{'error_information'} = $error_ref->{$error_code};
2512         push @repacked_errors, $repacked_error;
2513     } 
2514
2515     return @repacked_errors;
2516 }
2517
2518 =head2 _get_unlinked_item_subfields
2519
2520   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2521
2522 =cut
2523
2524 sub _get_unlinked_item_subfields {
2525     my $original_item_marc = shift;
2526     my $frameworkcode = shift;
2527
2528     my $marcstructure = GetMarcStructure(1, $frameworkcode);
2529
2530     # assume that this record has only one field, and that that
2531     # field contains only the item information
2532     my $subfields = [];
2533     my @fields = $original_item_marc->fields();
2534     if ($#fields > -1) {
2535         my $field = $fields[0];
2536             my $tag = $field->tag();
2537         foreach my $subfield ($field->subfields()) {
2538             if (defined $subfield->[1] and
2539                 $subfield->[1] ne '' and
2540                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2541                 push @$subfields, $subfield->[0] => $subfield->[1];
2542             }
2543         }
2544     }
2545     return $subfields;
2546 }
2547
2548 =head2 _get_unlinked_subfields_xml
2549
2550   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2551
2552 =cut
2553
2554 sub _get_unlinked_subfields_xml {
2555     my $unlinked_item_subfields = shift;
2556
2557     my $xml;
2558     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2559         my $marc = MARC::Record->new();
2560         # use of tag 999 is arbitrary, and doesn't need to match the item tag
2561         # used in the framework
2562         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2563         $marc->encoding("UTF-8");    
2564         $xml = $marc->as_xml("USMARC");
2565     }
2566
2567     return $xml;
2568 }
2569
2570 =head2 _parse_unlinked_item_subfields_from_xml
2571
2572   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2573
2574 =cut
2575
2576 sub  _parse_unlinked_item_subfields_from_xml {
2577     my $xml = shift;
2578     require C4::Charset;
2579     return unless defined $xml and $xml ne "";
2580     my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2581     my $unlinked_subfields = [];
2582     my @fields = $marc->fields();
2583     if ($#fields > -1) {
2584         foreach my $subfield ($fields[0]->subfields()) {
2585             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2586         }
2587     }
2588     return $unlinked_subfields;
2589 }
2590
2591 =head2 GetAnalyticsCount
2592
2593   $count= &GetAnalyticsCount($itemnumber)
2594
2595 counts Usage of itemnumber in Analytical bibliorecords. 
2596
2597 =cut
2598
2599 sub GetAnalyticsCount {
2600     my ($itemnumber) = @_;
2601     require C4::Search;
2602
2603     ### ZOOM search here
2604     my $query;
2605     $query= "hi=".$itemnumber;
2606             my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2607     return ($result);
2608 }
2609
2610 =head2 GetItemHolds
2611
2612   $holds = &GetItemHolds($biblionumber, $itemnumber);
2613
2614 This function return the count of holds with $biblionumber and $itemnumber
2615
2616 =cut
2617
2618 sub GetItemHolds {
2619     my ($biblionumber, $itemnumber) = @_;
2620     my $holds;
2621     my $dbh            = C4::Context->dbh;
2622     my $query          = "SELECT count(*)
2623         FROM  reserves
2624         WHERE biblionumber=? AND itemnumber=?";
2625     my $sth = $dbh->prepare($query);
2626     $sth->execute($biblionumber, $itemnumber);
2627     $holds = $sth->fetchrow;
2628     return $holds;
2629 }
2630
2631 =head2 SearchItemsByField
2632
2633     my $items = SearchItemsByField($field, $value);
2634
2635 SearchItemsByField will search for items on a specific given field.
2636 For instance you can search all items with a specific stocknumber like this:
2637
2638     my $items = SearchItemsByField('stocknumber', $stocknumber);
2639
2640 =cut
2641
2642 sub SearchItemsByField {
2643     my ($field, $value) = @_;
2644
2645     my $filters = {
2646         field => $field,
2647         query => $value,
2648     };
2649
2650     my ($results) = SearchItems($filters);
2651     return $results;
2652 }
2653
2654 sub _SearchItems_build_where_fragment {
2655     my ($filter) = @_;
2656
2657     my $dbh = C4::Context->dbh;
2658
2659     my $where_fragment;
2660     if (exists($filter->{conjunction})) {
2661         my (@where_strs, @where_args);
2662         foreach my $f (@{ $filter->{filters} }) {
2663             my $fragment = _SearchItems_build_where_fragment($f);
2664             if ($fragment) {
2665                 push @where_strs, $fragment->{str};
2666                 push @where_args, @{ $fragment->{args} };
2667             }
2668         }
2669         my $where_str = '';
2670         if (@where_strs) {
2671             $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
2672             $where_fragment = {
2673                 str => $where_str,
2674                 args => \@where_args,
2675             };
2676         }
2677     } else {
2678         my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2679         push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2680         push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2681         my @operators = qw(= != > < >= <= like);
2682         my $field = $filter->{field};
2683         if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
2684             my $op = $filter->{operator};
2685             my $query = $filter->{query};
2686
2687             if (!$op or (0 == grep /^$op$/, @operators)) {
2688                 $op = '='; # default operator
2689             }
2690
2691             my $column;
2692             if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
2693                 my $marcfield = $1;
2694                 my $marcsubfield = $2;
2695                 my ($kohafield) = $dbh->selectrow_array(q|
2696                     SELECT kohafield FROM marc_subfield_structure
2697                     WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
2698                 |, undef, $marcfield, $marcsubfield);
2699
2700                 if ($kohafield) {
2701                     $column = $kohafield;
2702                 } else {
2703                     # MARC field is not linked to a DB field so we need to use
2704                     # ExtractValue on biblioitems.marcxml or
2705                     # items.more_subfields_xml, depending on the MARC field.
2706                     my $xpath;
2707                     my $sqlfield;
2708                     my ($itemfield) = GetMarcFromKohaField('items.itemnumber');
2709                     if ($marcfield eq $itemfield) {
2710                         $sqlfield = 'more_subfields_xml';
2711                         $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
2712                     } else {
2713                         $sqlfield = 'marcxml';
2714                         if ($marcfield < 10) {
2715                             $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
2716                         } else {
2717                             $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
2718                         }
2719                     }
2720                     $column = "ExtractValue($sqlfield, '$xpath')";
2721                 }
2722             } else {
2723                 $column = $field;
2724             }
2725
2726             if (ref $query eq 'ARRAY') {
2727                 if ($op eq '=') {
2728                     $op = 'IN';
2729                 } elsif ($op eq '!=') {
2730                     $op = 'NOT IN';
2731                 }
2732                 $where_fragment = {
2733                     str => "$column $op (" . join (',', ('?') x @$query) . ")",
2734                     args => $query,
2735                 };
2736             } else {
2737                 $where_fragment = {
2738                     str => "$column $op ?",
2739                     args => [ $query ],
2740                 };
2741             }
2742         }
2743     }
2744
2745     return $where_fragment;
2746 }
2747
2748 =head2 SearchItems
2749
2750     my ($items, $total) = SearchItems($filter, $params);
2751
2752 Perform a search among items
2753
2754 $filter is a reference to a hash which can be a filter, or a combination of filters.
2755
2756 A filter has the following keys:
2757
2758 =over 2
2759
2760 =item * field: the name of a SQL column in table items
2761
2762 =item * query: the value to search in this column
2763
2764 =item * operator: comparison operator. Can be one of = != > < >= <= like
2765
2766 =back
2767
2768 A combination of filters hash the following keys:
2769
2770 =over 2
2771
2772 =item * conjunction: 'AND' or 'OR'
2773
2774 =item * filters: array ref of filters
2775
2776 =back
2777
2778 $params is a reference to a hash that can contain the following parameters:
2779
2780 =over 2
2781
2782 =item * rows: Number of items to return. 0 returns everything (default: 0)
2783
2784 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2785                (default: 1)
2786
2787 =item * sortby: A SQL column name in items table to sort on
2788
2789 =item * sortorder: 'ASC' or 'DESC'
2790
2791 =back
2792
2793 =cut
2794
2795 sub SearchItems {
2796     my ($filter, $params) = @_;
2797
2798     $filter //= {};
2799     $params //= {};
2800     return unless ref $filter eq 'HASH';
2801     return unless ref $params eq 'HASH';
2802
2803     # Default parameters
2804     $params->{rows} ||= 0;
2805     $params->{page} ||= 1;
2806     $params->{sortby} ||= 'itemnumber';
2807     $params->{sortorder} ||= 'ASC';
2808
2809     my ($where_str, @where_args);
2810     my $where_fragment = _SearchItems_build_where_fragment($filter);
2811     if ($where_fragment) {
2812         $where_str = $where_fragment->{str};
2813         @where_args = @{ $where_fragment->{args} };
2814     }
2815
2816     my $dbh = C4::Context->dbh;
2817     my $query = q{
2818         SELECT SQL_CALC_FOUND_ROWS items.*
2819         FROM items
2820           LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2821           LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2822     };
2823     if (defined $where_str and $where_str ne '') {
2824         $query .= qq{ WHERE $where_str };
2825     }
2826
2827     my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2828     push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2829     push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2830     my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
2831         ? $params->{sortby} : 'itemnumber';
2832     my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
2833     $query .= qq{ ORDER BY $sortby $sortorder };
2834
2835     my $rows = $params->{rows};
2836     my @limit_args;
2837     if ($rows > 0) {
2838         my $offset = $rows * ($params->{page}-1);
2839         $query .= qq { LIMIT ?, ? };
2840         push @limit_args, $offset, $rows;
2841     }
2842
2843     my $sth = $dbh->prepare($query);
2844     my $rv = $sth->execute(@where_args, @limit_args);
2845
2846     return unless ($rv);
2847     my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2848
2849     return ($sth->fetchall_arrayref({}), $total_rows);
2850 }
2851
2852
2853 =head1  OTHER FUNCTIONS
2854
2855 =head2 _find_value
2856
2857   ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2858
2859 Find the given $subfield in the given $tag in the given
2860 MARC::Record $record.  If the subfield is found, returns
2861 the (indicators, value) pair; otherwise, (undef, undef) is
2862 returned.
2863
2864 PROPOSITION :
2865 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2866 I suggest we export it from this module.
2867
2868 =cut
2869
2870 sub _find_value {
2871     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2872     my @result;
2873     my $indicator;
2874     if ( $tagfield < 10 ) {
2875         if ( $record->field($tagfield) ) {
2876             push @result, $record->field($tagfield)->data();
2877         } else {
2878             push @result, "";
2879         }
2880     } else {
2881         foreach my $field ( $record->field($tagfield) ) {
2882             my @subfields = $field->subfields();
2883             foreach my $subfield (@subfields) {
2884                 if ( @$subfield[0] eq $insubfield ) {
2885                     push @result, @$subfield[1];
2886                     $indicator = $field->indicator(1) . $field->indicator(2);
2887                 }
2888             }
2889         }
2890     }
2891     return ( $indicator, @result );
2892 }
2893
2894
2895 =head2 PrepareItemrecordDisplay
2896
2897   PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2898
2899 Returns a hash with all the fields for Display a given item data in a template
2900
2901 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2902
2903 =cut
2904
2905 sub PrepareItemrecordDisplay {
2906
2907     my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2908
2909     my $dbh = C4::Context->dbh;
2910     $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2911     my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2912     my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2913
2914     # return nothing if we don't have found an existing framework.
2915     return q{} unless $tagslib;
2916     my $itemrecord;
2917     if ($itemnum) {
2918         $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2919     }
2920     my @loop_data;
2921
2922     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2923     my $query = qq{
2924         SELECT authorised_value,lib FROM authorised_values
2925     };
2926     $query .= qq{
2927         LEFT JOIN authorised_values_branches ON ( id = av_id )
2928     } if $branch_limit;
2929     $query .= qq{
2930         WHERE category = ?
2931     };
2932     $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2933     $query .= qq{ ORDER BY lib};
2934     my $authorised_values_sth = $dbh->prepare( $query );
2935     foreach my $tag ( sort keys %{$tagslib} ) {
2936         my $previous_tag = '';
2937         if ( $tag ne '' ) {
2938
2939             # loop through each subfield
2940             my $cntsubf;
2941             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2942                 next if ( subfield_is_koha_internal_p($subfield) );
2943                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2944                 my %subfield_data;
2945                 $subfield_data{tag}           = $tag;
2946                 $subfield_data{subfield}      = $subfield;
2947                 $subfield_data{countsubfield} = $cntsubf++;
2948                 $subfield_data{kohafield}     = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2949                 $subfield_data{id}            = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2950
2951                 #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2952                 $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
2953                 $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
2954                 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2955                 $subfield_data{hidden}     = "display:none"
2956                   if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
2957                     || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
2958                 my ( $x, $defaultvalue );
2959                 if ($itemrecord) {
2960                     ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2961                 }
2962                 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2963                 if ( !defined $defaultvalue ) {
2964                     $defaultvalue = q||;
2965                 } else {
2966                     $defaultvalue =~ s/"/&quot;/g;
2967                 }
2968
2969                 # search for itemcallnumber if applicable
2970                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2971                     && C4::Context->preference('itemcallnumber') ) {
2972                     my $CNtag      = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2973                     my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2974                     if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2975                         $defaultvalue = $field->subfield($CNsubfield);
2976                     }
2977                 }
2978                 if (   $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2979                     && $defaultvalues
2980                     && $defaultvalues->{'callnumber'} ) {
2981                     if( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ){
2982                         # if the item record exists, only use default value if the item has no callnumber
2983                         $defaultvalue = $defaultvalues->{callnumber};
2984                     } elsif ( !$itemrecord and $defaultvalues ) {
2985                         # if the item record *doesn't* exists, always use the default value
2986                         $defaultvalue = $defaultvalues->{callnumber};
2987                     }
2988                 }
2989                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2990                     && $defaultvalues
2991                     && $defaultvalues->{'branchcode'} ) {
2992                     if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2993                         $defaultvalue = $defaultvalues->{branchcode};
2994                     }
2995                 }
2996                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2997                     && $defaultvalues
2998                     && $defaultvalues->{'location'} ) {
2999
3000                     if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
3001                         # if the item record exists, only use default value if the item has no locationr
3002                         $defaultvalue = $defaultvalues->{location};
3003                     } elsif ( !$itemrecord and $defaultvalues ) {
3004                         # if the item record *doesn't* exists, always use the default value
3005                         $defaultvalue = $defaultvalues->{location};
3006                     }
3007                 }
3008                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
3009                     my @authorised_values;
3010                     my %authorised_lib;
3011
3012                     # builds list, depending on authorised value...
3013                     #---- branch
3014                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
3015                         if (   ( C4::Context->preference("IndependentBranches") )
3016                             && !C4::Context->IsSuperLibrarian() ) {
3017                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
3018                             $sth->execute( C4::Context->userenv->{branch} );
3019                             push @authorised_values, ""
3020                               unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3021                             while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
3022                                 push @authorised_values, $branchcode;
3023                                 $authorised_lib{$branchcode} = $branchname;
3024                             }
3025                         } else {
3026                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
3027                             $sth->execute;
3028                             push @authorised_values, ""
3029                               unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3030                             while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
3031                                 push @authorised_values, $branchcode;
3032                                 $authorised_lib{$branchcode} = $branchname;
3033                             }
3034                         }
3035
3036                         $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
3037                         if ( $defaultvalues and $defaultvalues->{branchcode} ) {
3038                             $defaultvalue = $defaultvalues->{branchcode};
3039                         }
3040
3041                         #----- itemtypes
3042                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
3043                         my $itemtypes = GetItemTypes( style => 'array' );
3044                         push @authorised_values, ""
3045                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3046                         for my $itemtype ( @$itemtypes ) {
3047                             push @authorised_values, $itemtype->{itemtype};
3048                             $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
3049                         }
3050                         #---- class_sources
3051                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
3052                         push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3053
3054                         my $class_sources = GetClassSources();
3055                         my $default_source = C4::Context->preference("DefaultClassificationSource");
3056
3057                         foreach my $class_source (sort keys %$class_sources) {
3058                             next unless $class_sources->{$class_source}->{'used'} or
3059                                         ($class_source eq $default_source);
3060                             push @authorised_values, $class_source;
3061                             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
3062                         }
3063
3064                         $defaultvalue = $default_source;
3065
3066                         #---- "true" authorised value
3067                     } else {
3068                         $authorised_values_sth->execute(
3069                             $tagslib->{$tag}->{$subfield}->{authorised_value},
3070                             $branch_limit ? $branch_limit : ()
3071                         );
3072                         push @authorised_values, ""
3073                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
3074                         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
3075                             push @authorised_values, $value;
3076                             $authorised_lib{$value} = $lib;
3077                         }
3078                     }
3079                     $subfield_data{marc_value} = {
3080                         type    => 'select',
3081                         values  => \@authorised_values,
3082                         default => "$defaultvalue",
3083                         labels  => \%authorised_lib,
3084                     };
3085                 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
3086                 # it is a plugin
3087                     require Koha::FrameworkPlugin;
3088                     my $plugin = Koha::FrameworkPlugin->new({
3089                         name => $tagslib->{$tag}->{$subfield}->{value_builder},
3090                         item_style => 1,
3091                     });
3092                     my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
3093                     $plugin->build( $pars );
3094                     if( !$plugin->errstr ) {
3095                         #TODO Move html to template; see report 12176/13397
3096                         my $tab= $plugin->noclick? '-1': '';
3097                         my $class= $plugin->noclick? ' disabled': '';
3098                         my $title= $plugin->noclick? 'No popup': 'Tag editor';
3099                         $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
3100                     } else {
3101                         warn $plugin->errstr;
3102                         $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" />); # supply default input form
3103                     }
3104                 }
3105                 elsif ( $tag eq '' ) {       # it's an hidden field
3106                     $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
3107                 }
3108                 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
3109                     $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
3110                 }
3111                 elsif ( length($defaultvalue) > 100
3112                             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
3113                                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
3114                             or (C4::Context->preference("marcflavour") eq "MARC21"  and
3115                                   500 <= $tag && $tag < 600                     )
3116                           ) {
3117                     # oversize field (textarea)
3118                     $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255">$defaultvalue</textarea>\n");
3119                 } else {
3120                     $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
3121                 }
3122                 push( @loop_data, \%subfield_data );
3123             }
3124         }
3125     }
3126     my $itemnumber;
3127     if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
3128         $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
3129     }
3130     return {
3131         'itemtagfield'    => $itemtagfield,
3132         'itemtagsubfield' => $itemtagsubfield,
3133         'itemnumber'      => $itemnumber,
3134         'iteminformation' => \@loop_data
3135     };
3136 }
3137
3138 1;