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