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