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