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