Merge remote-tracking branch 'origin/new/bug_6488'
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 C4::Dates qw/format_date format_date_in_iso/;
29 use MARC::Record;
30 use C4::ClassSource;
31 use C4::Log;
32 use C4::Branch;
33 require C4::Reserves;
34 use C4::Charset;
35 use C4::Acquisition;
36 use List::MoreUtils qw/any/;
37 use Data::Dumper; # used as part of logging item record changes, not just for
38                   # debugging; so please don't remove this
39
40 use vars qw($VERSION @ISA @EXPORT);
41
42 BEGIN {
43     $VERSION = 3.01;
44
45         require Exporter;
46     @ISA = qw( Exporter );
47
48     # function exports
49     @EXPORT = qw(
50         GetItem
51         AddItemFromMarc
52         AddItem
53         AddItemBatchFromMarc
54         ModItemFromMarc
55                 Item2Marc
56         ModItem
57         ModDateLastSeen
58         ModItemTransfer
59         DelItem
60     
61         CheckItemPreSave
62     
63         GetItemStatus
64         GetItemLocation
65         GetLostItems
66         GetItemsForInventory
67         GetItemsCount
68         GetItemInfosOf
69         GetItemsByBiblioitemnumber
70         GetItemsInfo
71         GetItemsLocationInfo
72         GetHostItemsInfo
73         get_itemnumbers_of
74         get_hostitemnumbers_of
75         GetItemnumberFromBarcode
76         GetBarcodeFromItemnumber
77         GetHiddenItemnumbers
78                 DelItemCheck
79                 MoveItemFromBiblio 
80                 GetLatestAcquisitions
81         CartToShelf
82
83         GetAnalyticsCount
84         GetItemHolds
85     );
86 }
87
88 =head1 NAME
89
90 C4::Items - item management functions
91
92 =head1 DESCRIPTION
93
94 This module contains an API for manipulating item 
95 records in Koha, and is used by cataloguing, circulation,
96 acquisitions, and serials management.
97
98 A Koha item record is stored in two places: the
99 items table and embedded in a MARC tag in the XML
100 version of the associated bib record in C<biblioitems.marcxml>.
101 This is done to allow the item information to be readily
102 indexed (e.g., by Zebra), but means that each item
103 modification transaction must keep the items table
104 and the MARC XML in sync at all times.
105
106 Consequently, all code that creates, modifies, or deletes
107 item records B<must> use an appropriate function from 
108 C<C4::Items>.  If no existing function is suitable, it is
109 better to add one to C<C4::Items> than to use add
110 one-off SQL statements to add or modify items.
111
112 The items table will be considered authoritative.  In other
113 words, if there is ever a discrepancy between the items
114 table and the MARC XML, the items table should be considered
115 accurate.
116
117 =head1 HISTORICAL NOTE
118
119 Most of the functions in C<C4::Items> were originally in
120 the C<C4::Biblio> module.
121
122 =head1 CORE EXPORTED FUNCTIONS
123
124 The following functions are meant for use by users
125 of C<C4::Items>
126
127 =cut
128
129 =head2 GetItem
130
131   $item = GetItem($itemnumber,$barcode,$serial);
132
133 Return item information, for a given itemnumber or barcode.
134 The return value is a hashref mapping item column
135 names to values.  If C<$serial> is true, include serial publication data.
136
137 =cut
138
139 sub GetItem {
140     my ($itemnumber,$barcode, $serial) = @_;
141     my $dbh = C4::Context->dbh;
142         my $data;
143     if ($itemnumber) {
144         my $sth = $dbh->prepare("
145             SELECT * FROM items 
146             WHERE itemnumber = ?");
147         $sth->execute($itemnumber);
148         $data = $sth->fetchrow_hashref;
149     } else {
150         my $sth = $dbh->prepare("
151             SELECT * FROM items 
152             WHERE barcode = ?"
153             );
154         $sth->execute($barcode);                
155         $data = $sth->fetchrow_hashref;
156     }
157     if ( $serial) {      
158     my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
159         $ssth->execute($data->{'itemnumber'}) ;
160         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
161     }
162         #if we don't have an items.itype, use biblioitems.itemtype.
163         if( ! $data->{'itype'} ) {
164                 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
165                 $sth->execute($data->{'biblionumber'});
166                 ($data->{'itype'}) = $sth->fetchrow_array;
167         }
168     return $data;
169 }    # sub GetItem
170
171 =head2 CartToShelf
172
173   CartToShelf($itemnumber);
174
175 Set the current shelving location of the item record
176 to its stored permanent shelving location.  This is
177 primarily used to indicate when an item whose current
178 location is a special processing ('PROC') or shelving cart
179 ('CART') location is back in the stacks.
180
181 =cut
182
183 sub CartToShelf {
184     my ( $itemnumber ) = @_;
185
186     unless ( $itemnumber ) {
187         croak "FAILED CartToShelf() - no itemnumber supplied";
188     }
189
190     my $item = GetItem($itemnumber);
191     $item->{location} = $item->{permanent_location};
192     ModItem($item, undef, $itemnumber);
193 }
194
195 =head2 AddItemFromMarc
196
197   my ($biblionumber, $biblioitemnumber, $itemnumber) 
198       = AddItemFromMarc($source_item_marc, $biblionumber);
199
200 Given a MARC::Record object containing an embedded item
201 record and a biblionumber, create a new item record.
202
203 =cut
204
205 sub AddItemFromMarc {
206     my ( $source_item_marc, $biblionumber ) = @_;
207     my $dbh = C4::Context->dbh;
208
209     # parse item hash from MARC
210     my $frameworkcode = GetFrameworkCode( $biblionumber );
211         my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
212         
213         my $localitemmarc=MARC::Record->new;
214         $localitemmarc->append_fields($source_item_marc->field($itemtag));
215     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
216     my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
217     return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
218 }
219
220 =head2 AddItem
221
222   my ($biblionumber, $biblioitemnumber, $itemnumber) 
223       = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
224
225 Given a hash containing item column names as keys,
226 create a new Koha item record.
227
228 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
229 do not need to be supplied for general use; they exist
230 simply to allow them to be picked up from AddItemFromMarc.
231
232 The final optional parameter, C<$unlinked_item_subfields>, contains
233 an arrayref containing subfields present in the original MARC
234 representation of the item (e.g., from the item editor) that are
235 not mapped to C<items> columns directly but should instead
236 be stored in C<items.more_subfields_xml> and included in 
237 the biblio items tag for display and indexing.
238
239 =cut
240
241 sub AddItem {
242     my $item = shift;
243     my $biblionumber = shift;
244
245     my $dbh           = @_ ? shift : C4::Context->dbh;
246     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
247     my $unlinked_item_subfields;  
248     if (@_) {
249         $unlinked_item_subfields = shift
250     };
251
252     # needs old biblionumber and biblioitemnumber
253     $item->{'biblionumber'} = $biblionumber;
254     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
255     $sth->execute( $item->{'biblionumber'} );
256     ($item->{'biblioitemnumber'}) = $sth->fetchrow;
257
258     _set_defaults_for_add($item);
259     _set_derived_columns_for_add($item);
260     $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
261     # FIXME - checks here
262     unless ( $item->{itype} ) {  # default to biblioitem.itemtype if no itype
263         my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
264         $itype_sth->execute( $item->{'biblionumber'} );
265         ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
266     }
267
268         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
269     $item->{'itemnumber'} = $itemnumber;
270
271     ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
272    
273     logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
274     
275     return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
276 }
277
278 =head2 AddItemBatchFromMarc
279
280   ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
281              $biblionumber, $biblioitemnumber, $frameworkcode);
282
283 Efficiently create item records from a MARC biblio record with
284 embedded item fields.  This routine is suitable for batch jobs.
285
286 This API assumes that the bib record has already been
287 saved to the C<biblio> and C<biblioitems> tables.  It does
288 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
289 are populated, but it will do so via a call to ModBibiloMarc.
290
291 The goal of this API is to have a similar effect to using AddBiblio
292 and AddItems in succession, but without inefficient repeated
293 parsing of the MARC XML bib record.
294
295 This function returns an arrayref of new itemsnumbers and an arrayref of item
296 errors encountered during the processing.  Each entry in the errors
297 list is a hashref containing the following keys:
298
299 =over
300
301 =item item_sequence
302
303 Sequence number of original item tag in the MARC record.
304
305 =item item_barcode
306
307 Item barcode, provide to assist in the construction of
308 useful error messages.
309
310 =item error_condition
311
312 Code representing the error condition.  Can be 'duplicate_barcode',
313 'invalid_homebranch', or 'invalid_holdingbranch'.
314
315 =item error_information
316
317 Additional information appropriate to the error condition.
318
319 =back
320
321 =cut
322
323 sub AddItemBatchFromMarc {
324     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
325     my $error;
326     my @itemnumbers = ();
327     my @errors = ();
328     my $dbh = C4::Context->dbh;
329
330     # loop through the item tags and start creating items
331     my @bad_item_fields = ();
332     my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
333     my $item_sequence_num = 0;
334     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
335         $item_sequence_num++;
336         # we take the item field and stick it into a new
337         # MARC record -- this is required so far because (FIXME)
338         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
339         # and there is no TransformMarcFieldToKoha
340         my $temp_item_marc = MARC::Record->new();
341         $temp_item_marc->append_fields($item_field);
342     
343         # add biblionumber and biblioitemnumber
344         my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
345         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
346         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
347         $item->{'biblionumber'} = $biblionumber;
348         $item->{'biblioitemnumber'} = $biblioitemnumber;
349
350         # check for duplicate barcode
351         my %item_errors = CheckItemPreSave($item);
352         if (%item_errors) {
353             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
354             push @bad_item_fields, $item_field;
355             next ITEMFIELD;
356         }
357
358         _set_defaults_for_add($item);
359         _set_derived_columns_for_add($item);
360         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
361         warn $error if $error;
362         push @itemnumbers, $itemnumber; # FIXME not checking error
363         $item->{'itemnumber'} = $itemnumber;
364
365         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
366
367         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
368         $item_field->replace_with($new_item_marc->field($itemtag));
369     }
370
371     # remove any MARC item fields for rejected items
372     foreach my $item_field (@bad_item_fields) {
373         $record->delete_field($item_field);
374     }
375
376     # update the MARC biblio
377  #   $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
378
379     return (\@itemnumbers, \@errors);
380 }
381
382 =head2 ModItemFromMarc
383
384   ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
385
386 This function updates an item record based on a supplied
387 C<MARC::Record> object containing an embedded item field.
388 This API is meant for the use of C<additem.pl>; for 
389 other purposes, C<ModItem> should be used.
390
391 This function uses the hash %default_values_for_mod_from_marc,
392 which contains default values for item fields to
393 apply when modifying an item.  This is needed beccause
394 if an item field's value is cleared, TransformMarcToKoha
395 does not include the column in the
396 hash that's passed to ModItem, which without
397 use of this hash makes it impossible to clear
398 an item field's value.  See bug 2466.
399
400 Note that only columns that can be directly
401 changed from the cataloging and serials
402 item editors are included in this hash.
403
404 Returns item record
405
406 =cut
407
408 my %default_values_for_mod_from_marc = (
409     barcode              => undef, 
410     booksellerid         => undef, 
411     ccode                => undef, 
412     'items.cn_source'    => undef, 
413     copynumber           => undef, 
414     damaged              => 0,
415 #    dateaccessioned      => undef,
416     enumchron            => undef, 
417     holdingbranch        => undef, 
418     homebranch           => undef, 
419     itemcallnumber       => undef, 
420     itemlost             => 0,
421     itemnotes            => undef, 
422     itype                => undef, 
423     location             => undef, 
424     permanent_location   => undef,
425     materials            => undef, 
426     notforloan           => 0,
427     paidfor              => undef, 
428     price                => undef, 
429     replacementprice     => undef, 
430     replacementpricedate => undef, 
431     restricted           => undef, 
432     stack                => undef, 
433     stocknumber          => undef, 
434     uri                  => undef, 
435     wthdrawn             => 0,
436 );
437
438 sub ModItemFromMarc {
439     my $item_marc = shift;
440     my $biblionumber = shift;
441     my $itemnumber = shift;
442
443     my $dbh           = C4::Context->dbh;
444     my $frameworkcode = GetFrameworkCode($biblionumber);
445     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
446
447     my $localitemmarc = MARC::Record->new;
448     $localitemmarc->append_fields( $item_marc->field($itemtag) );
449     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
450     foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
451         $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
452     }
453     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
454
455     ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields); 
456     return $item;
457 }
458
459 =head2 ModItem
460
461   ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
462
463 Change one or more columns in an item record and update
464 the MARC representation of the item.
465
466 The first argument is a hashref mapping from item column
467 names to the new values.  The second and third arguments
468 are the biblionumber and itemnumber, respectively.
469
470 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
471 an arrayref containing subfields present in the original MARC
472 representation of the item (e.g., from the item editor) that are
473 not mapped to C<items> columns directly but should instead
474 be stored in C<items.more_subfields_xml> and included in 
475 the biblio items tag for display and indexing.
476
477 If one of the changed columns is used to calculate
478 the derived value of a column such as C<items.cn_sort>, 
479 this routine will perform the necessary calculation
480 and set the value.
481
482 =cut
483
484 sub ModItem {
485     my $item = shift;
486     my $biblionumber = shift;
487     my $itemnumber = shift;
488
489     # if $biblionumber is undefined, get it from the current item
490     unless (defined $biblionumber) {
491         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
492     }
493
494     my $dbh           = @_ ? shift : C4::Context->dbh;
495     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
496     
497     my $unlinked_item_subfields;  
498     if (@_) {
499         $unlinked_item_subfields = shift;
500         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
501     };
502
503     $item->{'itemnumber'} = $itemnumber or return undef;
504
505     $item->{onloan} = undef if $item->{itemlost};
506
507     _set_derived_columns_for_mod($item);
508     _do_column_fixes_for_mod($item);
509     # FIXME add checks
510     # duplicate barcode
511     # attempt to change itemnumber
512     # attempt to change biblionumber (if we want
513     # an API to relink an item to a different bib,
514     # it should be a separate function)
515
516     # update items table
517     _koha_modify_item($item);
518
519     # request that bib be reindexed so that searching on current
520     # item status is possible
521     ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
522
523     logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
524 }
525
526 =head2 ModItemTransfer
527
528   ModItemTransfer($itenumber, $frombranch, $tobranch);
529
530 Marks an item as being transferred from one branch
531 to another.
532
533 =cut
534
535 sub ModItemTransfer {
536     my ( $itemnumber, $frombranch, $tobranch ) = @_;
537
538     my $dbh = C4::Context->dbh;
539
540     #new entry in branchtransfers....
541     my $sth = $dbh->prepare(
542         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
543         VALUES (?, ?, NOW(), ?)");
544     $sth->execute($itemnumber, $frombranch, $tobranch);
545
546     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
547     ModDateLastSeen($itemnumber);
548     return;
549 }
550
551 =head2 ModDateLastSeen
552
553   ModDateLastSeen($itemnum);
554
555 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
556 C<$itemnum> is the item number
557
558 =cut
559
560 sub ModDateLastSeen {
561     my ($itemnumber) = @_;
562     
563     my $today = C4::Dates->new();    
564     ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
565 }
566
567 =head2 DelItem
568
569   DelItem($dbh, $biblionumber, $itemnumber);
570
571 Exported function (core API) for deleting an item record in Koha.
572
573 =cut
574
575 sub DelItem {
576     my ( $dbh, $biblionumber, $itemnumber ) = @_;
577     
578     # FIXME check the item has no current issues
579     
580     _koha_delete_item( $dbh, $itemnumber );
581
582     # get the MARC record
583     my $record = GetMarcBiblio($biblionumber);
584     ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
585
586     # backup the record
587     my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
588     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
589     # This last update statement makes that the timestamp column in deleteditems is updated too. If you remove these lines, please add a line to update the timestamp separately. See Bugzilla report 7146 and Biblio.pm (DelBiblio).
590
591     #search item field code
592     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
593 }
594
595 =head2 CheckItemPreSave
596
597     my $item_ref = TransformMarcToKoha($marc, 'items');
598     # do stuff
599     my %errors = CheckItemPreSave($item_ref);
600     if (exists $errors{'duplicate_barcode'}) {
601         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
602     } elsif (exists $errors{'invalid_homebranch'}) {
603         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
604     } elsif (exists $errors{'invalid_holdingbranch'}) {
605         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
606     } else {
607         print "item is OK";
608     }
609
610 Given a hashref containing item fields, determine if it can be
611 inserted or updated in the database.  Specifically, checks for
612 database integrity issues, and returns a hash containing any
613 of the following keys, if applicable.
614
615 =over 2
616
617 =item duplicate_barcode
618
619 Barcode, if it duplicates one already found in the database.
620
621 =item invalid_homebranch
622
623 Home branch, if not defined in branches table.
624
625 =item invalid_holdingbranch
626
627 Holding branch, if not defined in branches table.
628
629 =back
630
631 This function does NOT implement any policy-related checks,
632 e.g., whether current operator is allowed to save an
633 item that has a given branch code.
634
635 =cut
636
637 sub CheckItemPreSave {
638     my $item_ref = shift;
639
640     my %errors = ();
641
642     # check for duplicate barcode
643     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
644         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
645         if ($existing_itemnumber) {
646             if (!exists $item_ref->{'itemnumber'}                       # new item
647                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
648                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
649             }
650         }
651     }
652
653     # check for valid home branch
654     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
655         my $branch_name = GetBranchName($item_ref->{'homebranch'});
656         unless (defined $branch_name) {
657             # relies on fact that branches.branchname is a non-NULL column,
658             # so GetBranchName returns undef only if branch does not exist
659             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
660         }
661     }
662
663     # check for valid holding branch
664     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
665         my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
666         unless (defined $branch_name) {
667             # relies on fact that branches.branchname is a non-NULL column,
668             # so GetBranchName returns undef only if branch does not exist
669             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
670         }
671     }
672
673     return %errors;
674
675 }
676
677 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
678
679 The following functions provide various ways of 
680 getting an item record, a set of item records, or
681 lists of authorized values for certain item fields.
682
683 Some of the functions in this group are candidates
684 for refactoring -- for example, some of the code
685 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
686 has copy-and-paste work.
687
688 =cut
689
690 =head2 GetItemStatus
691
692   $itemstatushash = GetItemStatus($fwkcode);
693
694 Returns a list of valid values for the
695 C<items.notforloan> field.
696
697 NOTE: does B<not> return an individual item's
698 status.
699
700 Can be MARC dependant.
701 fwkcode is optional.
702 But basically could be can be loan or not
703 Create a status selector with the following code
704
705 =head3 in PERL SCRIPT
706
707  my $itemstatushash = getitemstatus;
708  my @itemstatusloop;
709  foreach my $thisstatus (keys %$itemstatushash) {
710      my %row =(value => $thisstatus,
711                  statusname => $itemstatushash->{$thisstatus}->{'statusname'},
712              );
713      push @itemstatusloop, \%row;
714  }
715  $template->param(statusloop=>\@itemstatusloop);
716
717 =head3 in TEMPLATE
718
719  <select name="statusloop">
720      <option value="">Default</option>
721  <!-- TMPL_LOOP name="statusloop" -->
722      <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
723  <!-- /TMPL_LOOP -->
724  </select>
725
726 =cut
727
728 sub GetItemStatus {
729
730     # returns a reference to a hash of references to status...
731     my ($fwk) = @_;
732     my %itemstatus;
733     my $dbh = C4::Context->dbh;
734     my $sth;
735     $fwk = '' unless ($fwk);
736     my ( $tag, $subfield ) =
737       GetMarcFromKohaField( "items.notforloan", $fwk );
738     if ( $tag and $subfield ) {
739         my $sth =
740           $dbh->prepare(
741             "SELECT authorised_value
742             FROM marc_subfield_structure
743             WHERE tagfield=?
744                 AND tagsubfield=?
745                 AND frameworkcode=?
746             "
747           );
748         $sth->execute( $tag, $subfield, $fwk );
749         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
750             my $authvalsth =
751               $dbh->prepare(
752                 "SELECT authorised_value,lib
753                 FROM authorised_values 
754                 WHERE category=? 
755                 ORDER BY lib
756                 "
757               );
758             $authvalsth->execute($authorisedvaluecat);
759             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
760                 $itemstatus{$authorisedvalue} = $lib;
761             }
762             return \%itemstatus;
763             exit 1;
764         }
765         else {
766
767             #No authvalue list
768             # build default
769         }
770     }
771
772     #No authvalue list
773     #build default
774     $itemstatus{"1"} = "Not For Loan";
775     return \%itemstatus;
776 }
777
778 =head2 GetItemLocation
779
780   $itemlochash = GetItemLocation($fwk);
781
782 Returns a list of valid values for the
783 C<items.location> field.
784
785 NOTE: does B<not> return an individual item's
786 location.
787
788 where fwk stands for an optional framework code.
789 Create a location selector with the following code
790
791 =head3 in PERL SCRIPT
792
793   my $itemlochash = getitemlocation;
794   my @itemlocloop;
795   foreach my $thisloc (keys %$itemlochash) {
796       my $selected = 1 if $thisbranch eq $branch;
797       my %row =(locval => $thisloc,
798                   selected => $selected,
799                   locname => $itemlochash->{$thisloc},
800                );
801       push @itemlocloop, \%row;
802   }
803   $template->param(itemlocationloop => \@itemlocloop);
804
805 =head3 in TEMPLATE
806
807   <select name="location">
808       <option value="">Default</option>
809   <!-- TMPL_LOOP name="itemlocationloop" -->
810       <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
811   <!-- /TMPL_LOOP -->
812   </select>
813
814 =cut
815
816 sub GetItemLocation {
817
818     # returns a reference to a hash of references to location...
819     my ($fwk) = @_;
820     my %itemlocation;
821     my $dbh = C4::Context->dbh;
822     my $sth;
823     $fwk = '' unless ($fwk);
824     my ( $tag, $subfield ) =
825       GetMarcFromKohaField( "items.location", $fwk );
826     if ( $tag and $subfield ) {
827         my $sth =
828           $dbh->prepare(
829             "SELECT authorised_value
830             FROM marc_subfield_structure 
831             WHERE tagfield=? 
832                 AND tagsubfield=? 
833                 AND frameworkcode=?"
834           );
835         $sth->execute( $tag, $subfield, $fwk );
836         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
837             my $authvalsth =
838               $dbh->prepare(
839                 "SELECT authorised_value,lib
840                 FROM authorised_values
841                 WHERE category=?
842                 ORDER BY lib"
843               );
844             $authvalsth->execute($authorisedvaluecat);
845             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
846                 $itemlocation{$authorisedvalue} = $lib;
847             }
848             return \%itemlocation;
849             exit 1;
850         }
851         else {
852
853             #No authvalue list
854             # build default
855         }
856     }
857
858     #No authvalue list
859     #build default
860     $itemlocation{"1"} = "Not For Loan";
861     return \%itemlocation;
862 }
863
864 =head2 GetLostItems
865
866   $items = GetLostItems( $where, $orderby );
867
868 This function gets a list of lost items.
869
870 =over 2
871
872 =item input:
873
874 C<$where> is a hashref. it containts a field of the items table as key
875 and the value to match as value. For example:
876
877 { barcode    => 'abc123',
878   homebranch => 'CPL',    }
879
880 C<$orderby> is a field of the items table by which the resultset
881 should be orderd.
882
883 =item return:
884
885 C<$items> is a reference to an array full of hashrefs with columns
886 from the "items" table as keys.
887
888 =item usage in the perl script:
889
890   my $where = { barcode => '0001548' };
891   my $items = GetLostItems( $where, "homebranch" );
892   $template->param( itemsloop => $items );
893
894 =back
895
896 =cut
897
898 sub GetLostItems {
899     # Getting input args.
900     my $where   = shift;
901     my $orderby = shift;
902     my $dbh     = C4::Context->dbh;
903
904     my $query   = "
905         SELECT *
906         FROM   items
907             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
908             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
909             LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
910         WHERE
911                 authorised_values.category = 'LOST'
912                 AND itemlost IS NOT NULL
913                 AND itemlost <> 0
914     ";
915     my @query_parameters;
916     foreach my $key (keys %$where) {
917         $query .= " AND $key LIKE ?";
918         push @query_parameters, "%$where->{$key}%";
919     }
920     my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
921     
922     if ( defined $orderby && grep($orderby, @ordervalues)) {
923         $query .= ' ORDER BY '.$orderby;
924     }
925
926     my $sth = $dbh->prepare($query);
927     $sth->execute( @query_parameters );
928     my $items = [];
929     while ( my $row = $sth->fetchrow_hashref ){
930         push @$items, $row;
931     }
932     return $items;
933 }
934
935 =head2 GetItemsForInventory
936
937   $itemlist = GetItemsForInventory($minlocation, $maxlocation, 
938                  $location, $itemtype $datelastseen, $branch, 
939                  $offset, $size, $statushash);
940
941 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
942
943 The sub returns a reference to a list of hashes, each containing
944 itemnumber, author, title, barcode, item callnumber, and date last
945 seen. It is ordered by callnumber then title.
946
947 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
948 the datelastseen can be used to specify that you want to see items not seen since a past date only.
949 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
950 $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.
951
952 =cut
953
954 sub GetItemsForInventory {
955     my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
956     my $dbh = C4::Context->dbh;
957     my ( @bind_params, @where_strings );
958
959     my $query = <<'END_SQL';
960 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
961 FROM items
962   LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
963   LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
964 END_SQL
965     if ($statushash){
966         for my $authvfield (keys %$statushash){
967             if ( scalar @{$statushash->{$authvfield}} > 0 ){
968                 my $joinedvals = join ',', @{$statushash->{$authvfield}};
969                 push @where_strings, "$authvfield in (" . $joinedvals . ")";
970             }
971         }
972     }
973
974     if ($minlocation) {
975         push @where_strings, 'itemcallnumber >= ?';
976         push @bind_params, $minlocation;
977     }
978
979     if ($maxlocation) {
980         push @where_strings, 'itemcallnumber <= ?';
981         push @bind_params, $maxlocation;
982     }
983
984     if ($datelastseen) {
985         $datelastseen = format_date_in_iso($datelastseen);  
986         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
987         push @bind_params, $datelastseen;
988     }
989
990     if ( $location ) {
991         push @where_strings, 'items.location = ?';
992         push @bind_params, $location;
993     }
994
995     if ( $branchcode ) {
996         if($branch eq "homebranch"){
997         push @where_strings, 'items.homebranch = ?';
998         }else{
999             push @where_strings, 'items.holdingbranch = ?';
1000         }
1001         push @bind_params, $branchcode;
1002     }
1003     
1004     if ( $itemtype ) {
1005         push @where_strings, 'biblioitems.itemtype = ?';
1006         push @bind_params, $itemtype;
1007     }
1008
1009     if ( $ignoreissued) {
1010         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1011         push @where_strings, 'issues.date_due IS NULL';
1012     }
1013
1014     if ( @where_strings ) {
1015         $query .= 'WHERE ';
1016         $query .= join ' AND ', @where_strings;
1017     }
1018     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1019     my $sth = $dbh->prepare($query);
1020     $sth->execute( @bind_params );
1021
1022     my @results;
1023     $size--;
1024     while ( my $row = $sth->fetchrow_hashref ) {
1025         $offset-- if ($offset);
1026         $row->{datelastseen}=format_date($row->{datelastseen});
1027         if ( ( !$offset ) && $size ) {
1028             push @results, $row;
1029             $size--;
1030         }
1031     }
1032     return \@results;
1033 }
1034
1035 =head2 GetItemsCount
1036
1037   $count = &GetItemsCount( $biblionumber);
1038
1039 This function return count of item with $biblionumber
1040
1041 =cut
1042
1043 sub GetItemsCount {
1044     my ( $biblionumber ) = @_;
1045     my $dbh = C4::Context->dbh;
1046     my $query = "SELECT count(*)
1047           FROM  items 
1048           WHERE biblionumber=?";
1049     my $sth = $dbh->prepare($query);
1050     $sth->execute($biblionumber);
1051     my $count = $sth->fetchrow;  
1052     return ($count);
1053 }
1054
1055 =head2 GetItemInfosOf
1056
1057   GetItemInfosOf(@itemnumbers);
1058
1059 =cut
1060
1061 sub GetItemInfosOf {
1062     my @itemnumbers = @_;
1063
1064     my $query = '
1065         SELECT *
1066         FROM items
1067         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1068     ';
1069     return get_infos_of( $query, 'itemnumber' );
1070 }
1071
1072 =head2 GetItemsByBiblioitemnumber
1073
1074   GetItemsByBiblioitemnumber($biblioitemnumber);
1075
1076 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1077 Called by C<C4::XISBN>
1078
1079 =cut
1080
1081 sub GetItemsByBiblioitemnumber {
1082     my ( $bibitem ) = @_;
1083     my $dbh = C4::Context->dbh;
1084     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1085     # Get all items attached to a biblioitem
1086     my $i = 0;
1087     my @results; 
1088     $sth->execute($bibitem) || die $sth->errstr;
1089     while ( my $data = $sth->fetchrow_hashref ) {  
1090         # Foreach item, get circulation information
1091         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1092                                    WHERE itemnumber = ?
1093                                    AND issues.borrowernumber = borrowers.borrowernumber"
1094         );
1095         $sth2->execute( $data->{'itemnumber'} );
1096         if ( my $data2 = $sth2->fetchrow_hashref ) {
1097             # if item is out, set the due date and who it is out too
1098             $data->{'date_due'}   = $data2->{'date_due'};
1099             $data->{'cardnumber'} = $data2->{'cardnumber'};
1100             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1101         }
1102         else {
1103             # set date_due to blank, so in the template we check itemlost, and wthdrawn 
1104             $data->{'date_due'} = '';                                                                                                         
1105         }    # else         
1106         # Find the last 3 people who borrowed this item.                  
1107         my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1108                       AND old_issues.borrowernumber = borrowers.borrowernumber
1109                       ORDER BY returndate desc,timestamp desc LIMIT 3";
1110         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1111         $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1112         my $i2 = 0;
1113         while ( my $data2 = $sth2->fetchrow_hashref ) {
1114             $data->{"timestamp$i2"} = $data2->{'timestamp'};
1115             $data->{"card$i2"}      = $data2->{'cardnumber'};
1116             $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1117             $i2++;
1118         }
1119         push(@results,$data);
1120     } 
1121     return (\@results); 
1122 }
1123
1124 =head2 GetItemsInfo
1125
1126   @results = GetItemsInfo($biblionumber);
1127
1128 Returns information about items with the given biblionumber.
1129
1130 C<GetItemsInfo> returns a list of references-to-hash. Each element
1131 contains a number of keys. Most of them are attributes from the
1132 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1133 Koha database. Other keys include:
1134
1135 =over 2
1136
1137 =item C<$data-E<gt>{branchname}>
1138
1139 The name (not the code) of the branch to which the book belongs.
1140
1141 =item C<$data-E<gt>{datelastseen}>
1142
1143 This is simply C<items.datelastseen>, except that while the date is
1144 stored in YYYY-MM-DD format in the database, here it is converted to
1145 DD/MM/YYYY format. A NULL date is returned as C<//>.
1146
1147 =item C<$data-E<gt>{datedue}>
1148
1149 =item C<$data-E<gt>{class}>
1150
1151 This is the concatenation of C<biblioitems.classification>, the book's
1152 Dewey code, and C<biblioitems.subclass>.
1153
1154 =item C<$data-E<gt>{ocount}>
1155
1156 I think this is the number of copies of the book available.
1157
1158 =item C<$data-E<gt>{order}>
1159
1160 If this is set, it is set to C<One Order>.
1161
1162 =back
1163
1164 =cut
1165
1166 sub GetItemsInfo {
1167     my ( $biblionumber ) = @_;
1168     my $dbh   = C4::Context->dbh;
1169     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1170     my $query = "
1171     SELECT items.*,
1172            biblio.*,
1173            biblioitems.volume,
1174            biblioitems.number,
1175            biblioitems.itemtype,
1176            biblioitems.isbn,
1177            biblioitems.issn,
1178            biblioitems.publicationyear,
1179            biblioitems.publishercode,
1180            biblioitems.volumedate,
1181            biblioitems.volumedesc,
1182            biblioitems.lccn,
1183            biblioitems.url,
1184            items.notforloan as itemnotforloan,
1185            itemtypes.description,
1186            itemtypes.notforloan as notforloan_per_itemtype,
1187            branchurl
1188      FROM items
1189      LEFT JOIN branches ON items.holdingbranch = branches.branchcode
1190      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
1191      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1192      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
1193      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1194     $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1195     my $sth = $dbh->prepare($query);
1196     $sth->execute($biblionumber);
1197     my $i = 0;
1198     my @results;
1199     my $serial;
1200
1201     my $isth    = $dbh->prepare(
1202         "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1203         FROM   issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1204         WHERE  itemnumber = ?"
1205        );
1206         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
1207         while ( my $data = $sth->fetchrow_hashref ) {
1208         my $datedue = '';
1209         my $count_reserves;
1210         $isth->execute( $data->{'itemnumber'} );
1211         if ( my $idata = $isth->fetchrow_hashref ) {
1212             $data->{borrowernumber} = $idata->{borrowernumber};
1213             $data->{cardnumber}     = $idata->{cardnumber};
1214             $data->{surname}     = $idata->{surname};
1215             $data->{firstname}     = $idata->{firstname};
1216             $data->{lastreneweddate} = $idata->{lastreneweddate};
1217             $datedue                = $idata->{'date_due'};
1218         if (C4::Context->preference("IndependantBranches")){
1219         my $userenv = C4::Context->userenv;
1220         if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) { 
1221             $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1222         }
1223         }
1224         }
1225                 if ( $data->{'serial'}) {       
1226                         $ssth->execute($data->{'itemnumber'}) ;
1227                         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1228                         $serial = 1;
1229         }
1230                 if ( $datedue eq '' ) {
1231             my ( $restype, $reserves, undef ) =
1232               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1233 # Previous conditional check with if ($restype) is not needed because a true
1234 # result for one item will result in subsequent items defaulting to this true
1235 # value.
1236             $count_reserves = $restype;
1237         }
1238         #get branch information.....
1239         my $bsth = $dbh->prepare(
1240             "SELECT * FROM branches WHERE branchcode = ?
1241         "
1242         );
1243         $bsth->execute( $data->{'holdingbranch'} );
1244         if ( my $bdata = $bsth->fetchrow_hashref ) {
1245             $data->{'branchname'} = $bdata->{'branchname'};
1246         }
1247         $data->{'datedue'}        = $datedue;
1248         $data->{'count_reserves'} = $count_reserves;
1249
1250         # get notforloan complete status if applicable
1251         my $sthnflstatus = $dbh->prepare(
1252             'SELECT authorised_value
1253             FROM   marc_subfield_structure
1254             WHERE  kohafield="items.notforloan"
1255         '
1256         );
1257
1258         $sthnflstatus->execute;
1259         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1260         if ($authorised_valuecode) {
1261             $sthnflstatus = $dbh->prepare(
1262                 "SELECT lib FROM authorised_values
1263                  WHERE  category=?
1264                  AND authorised_value=?"
1265             );
1266             $sthnflstatus->execute( $authorised_valuecode,
1267                 $data->{itemnotforloan} );
1268             my ($lib) = $sthnflstatus->fetchrow;
1269             $data->{notforloanvalue} = $lib;
1270         }
1271
1272         # get restricted status and description if applicable
1273         my $restrictedstatus = $dbh->prepare(
1274             'SELECT authorised_value
1275             FROM   marc_subfield_structure
1276             WHERE  kohafield="items.restricted"
1277         '
1278         );
1279
1280         $restrictedstatus->execute;
1281         ($authorised_valuecode) = $restrictedstatus->fetchrow;
1282         if ($authorised_valuecode) {
1283             $restrictedstatus = $dbh->prepare(
1284                 "SELECT lib,lib_opac FROM authorised_values
1285                  WHERE  category=?
1286                  AND authorised_value=?"
1287             );
1288             $restrictedstatus->execute( $authorised_valuecode,
1289                 $data->{restricted} );
1290
1291             if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1292                 $data->{restricted} = $rstdata->{'lib'};
1293                 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1294             }
1295         }
1296
1297         # my stack procedures
1298         my $stackstatus = $dbh->prepare(
1299             'SELECT authorised_value
1300              FROM   marc_subfield_structure
1301              WHERE  kohafield="items.stack"
1302         '
1303         );
1304         $stackstatus->execute;
1305
1306         ($authorised_valuecode) = $stackstatus->fetchrow;
1307         if ($authorised_valuecode) {
1308             $stackstatus = $dbh->prepare(
1309                 "SELECT lib
1310                  FROM   authorised_values
1311                  WHERE  category=?
1312                  AND    authorised_value=?
1313             "
1314             );
1315             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1316             my ($lib) = $stackstatus->fetchrow;
1317             $data->{stack} = $lib;
1318         }
1319         # Find the last 3 people who borrowed this item.
1320         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1321                                     WHERE itemnumber = ?
1322                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1323                                     ORDER BY returndate DESC
1324                                     LIMIT 3");
1325         $sth2->execute($data->{'itemnumber'});
1326         my $ii = 0;
1327         while (my $data2 = $sth2->fetchrow_hashref()) {
1328             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1329             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1330             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1331             $ii++;
1332         }
1333
1334         $results[$i] = $data;
1335         $i++;
1336     }
1337         if($serial) {
1338                 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1339         } else {
1340         return (@results);
1341         }
1342 }
1343
1344 =head2 GetItemsLocationInfo
1345
1346   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1347
1348 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1349
1350 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1351
1352 =over 2
1353
1354 =item C<$data-E<gt>{homebranch}>
1355
1356 Branch Name of the item's homebranch
1357
1358 =item C<$data-E<gt>{holdingbranch}>
1359
1360 Branch Name of the item's holdingbranch
1361
1362 =item C<$data-E<gt>{location}>
1363
1364 Item's shelving location code
1365
1366 =item C<$data-E<gt>{location_intranet}>
1367
1368 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1369
1370 =item C<$data-E<gt>{location_opac}>
1371
1372 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
1373 description is set.
1374
1375 =item C<$data-E<gt>{itemcallnumber}>
1376
1377 Item's itemcallnumber
1378
1379 =item C<$data-E<gt>{cn_sort}>
1380
1381 Item's call number normalized for sorting
1382
1383 =back
1384   
1385 =cut
1386
1387 sub GetItemsLocationInfo {
1388         my $biblionumber = shift;
1389         my @results;
1390
1391         my $dbh = C4::Context->dbh;
1392         my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch, 
1393                             location, itemcallnumber, cn_sort
1394                      FROM items, branches as a, branches as b
1395                      WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode 
1396                      AND biblionumber = ?
1397                      ORDER BY cn_sort ASC";
1398         my $sth = $dbh->prepare($query);
1399         $sth->execute($biblionumber);
1400
1401         while ( my $data = $sth->fetchrow_hashref ) {
1402              $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1403              $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1404              push @results, $data;
1405         }
1406         return @results;
1407 }
1408
1409 =head2 GetHostItemsInfo
1410
1411         $hostiteminfo = GetHostItemsInfo($hostfield);
1412         Returns the iteminfo for items linked to records via a host field
1413
1414 =cut
1415
1416 sub GetHostItemsInfo {
1417         my ($record) = @_;
1418         my @returnitemsInfo;
1419
1420         if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1421         C4::Context->preference('marcflavour') eq 'NORMARC'){
1422             foreach my $hostfield ( $record->field('773') ) {
1423                 my $hostbiblionumber = $hostfield->subfield("0");
1424                 my $linkeditemnumber = $hostfield->subfield("9");
1425                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1426                 foreach my $hostitemInfo (@hostitemInfos){
1427                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1428                                 push (@returnitemsInfo,$hostitemInfo);
1429                                 last;
1430                         }
1431                 }
1432             }
1433         } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1434             foreach my $hostfield ( $record->field('461') ) {
1435                 my $hostbiblionumber = $hostfield->subfield("0");
1436                 my $linkeditemnumber = $hostfield->subfield("9");
1437                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1438                 foreach my $hostitemInfo (@hostitemInfos){
1439                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1440                                 push (@returnitemsInfo,$hostitemInfo);
1441                                 last;
1442                         }
1443                 }
1444             }
1445         }
1446         return @returnitemsInfo;
1447 }
1448
1449
1450 =head2 GetLastAcquisitions
1451
1452   my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
1453                                     'itemtypes' => ('BK','BD')}, 10);
1454
1455 =cut
1456
1457 sub  GetLastAcquisitions {
1458         my ($data,$max) = @_;
1459
1460         my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1461         
1462         my $number_of_branches = @{$data->{branches}};
1463         my $number_of_itemtypes   = @{$data->{itemtypes}};
1464         
1465         
1466         my @where = ('WHERE 1 '); 
1467         $number_of_branches and push @where
1468            , 'AND holdingbranch IN (' 
1469            , join(',', ('?') x $number_of_branches )
1470            , ')'
1471          ;
1472         
1473         $number_of_itemtypes and push @where
1474            , "AND $itemtype IN (" 
1475            , join(',', ('?') x $number_of_itemtypes )
1476            , ')'
1477          ;
1478
1479         my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1480                                  FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber) 
1481                                     RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1482                                     @where
1483                                     GROUP BY biblio.biblionumber 
1484                                     ORDER BY dateaccessioned DESC LIMIT $max";
1485
1486         my $dbh = C4::Context->dbh;
1487         my $sth = $dbh->prepare($query);
1488     
1489     $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1490         
1491         my @results;
1492         while( my $row = $sth->fetchrow_hashref){
1493                 push @results, {date => $row->{dateaccessioned} 
1494                                                 , biblionumber => $row->{biblionumber}
1495                                                 , title => $row->{title}};
1496         }
1497         
1498         return @results;
1499 }
1500
1501 =head2 get_itemnumbers_of
1502
1503   my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1504
1505 Given a list of biblionumbers, return the list of corresponding itemnumbers
1506 for each biblionumber.
1507
1508 Return a reference on a hash where keys are biblionumbers and values are
1509 references on array of itemnumbers.
1510
1511 =cut
1512
1513 sub get_itemnumbers_of {
1514     my @biblionumbers = @_;
1515
1516     my $dbh = C4::Context->dbh;
1517
1518     my $query = '
1519         SELECT itemnumber,
1520             biblionumber
1521         FROM items
1522         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1523     ';
1524     my $sth = $dbh->prepare($query);
1525     $sth->execute(@biblionumbers);
1526
1527     my %itemnumbers_of;
1528
1529     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1530         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1531     }
1532
1533     return \%itemnumbers_of;
1534 }
1535
1536 =head2 get_hostitemnumbers_of
1537
1538   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1539
1540 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1541
1542 Return a reference on a hash where key is a biblionumber and values are
1543 references on array of itemnumbers.
1544
1545 =cut
1546
1547
1548 sub get_hostitemnumbers_of {
1549         my ($biblionumber) = @_;
1550         my $marcrecord = GetMarcBiblio($biblionumber);
1551         my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1552         
1553         my $marcflavor = C4::Context->preference('marcflavour');
1554         if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1555         $tag='773';
1556         $biblio_s='0';
1557         $item_s='9';
1558     } elsif ($marcflavor eq 'UNIMARC') {
1559         $tag='461';
1560         $biblio_s='0';
1561         $item_s='9';
1562     }
1563
1564     foreach my $hostfield ( $marcrecord->field($tag) ) {
1565         my $hostbiblionumber = $hostfield->subfield($biblio_s);
1566         my $linkeditemnumber = $hostfield->subfield($item_s);
1567         my @itemnumbers;
1568         if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1569         {
1570             @itemnumbers = @$itemnumbers;
1571         }
1572         foreach my $itemnumber (@itemnumbers){
1573             if ($itemnumber eq $linkeditemnumber){
1574                 push (@returnhostitemnumbers,$itemnumber);
1575                 last;
1576             }
1577         }
1578     }
1579     return @returnhostitemnumbers;
1580 }
1581
1582
1583 =head2 GetItemnumberFromBarcode
1584
1585   $result = GetItemnumberFromBarcode($barcode);
1586
1587 =cut
1588
1589 sub GetItemnumberFromBarcode {
1590     my ($barcode) = @_;
1591     my $dbh = C4::Context->dbh;
1592
1593     my $rq =
1594       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1595     $rq->execute($barcode);
1596     my ($result) = $rq->fetchrow;
1597     return ($result);
1598 }
1599
1600 =head2 GetBarcodeFromItemnumber
1601
1602   $result = GetBarcodeFromItemnumber($itemnumber);
1603
1604 =cut
1605
1606 sub GetBarcodeFromItemnumber {
1607     my ($itemnumber) = @_;
1608     my $dbh = C4::Context->dbh;
1609
1610     my $rq =
1611       $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1612     $rq->execute($itemnumber);
1613     my ($result) = $rq->fetchrow;
1614     return ($result);
1615 }
1616
1617 =head2 GetHiddenItemnumbers
1618
1619 =over 4
1620
1621 $result = GetHiddenItemnumbers(@items);
1622
1623 =back
1624
1625 =cut
1626
1627 sub GetHiddenItemnumbers {
1628     my (@items) = @_;
1629     my @resultitems;
1630
1631     my $yaml = C4::Context->preference('OpacHiddenItems');
1632     $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1633     my $hidingrules;
1634     eval {
1635         $hidingrules = YAML::Load($yaml);
1636     };
1637     if ($@) {
1638         warn "Unable to parse OpacHiddenItems syspref : $@";
1639         return ();
1640     }
1641     my $dbh = C4::Context->dbh;
1642
1643     # For each item
1644     foreach my $item (@items) {
1645
1646         # We check each rule
1647         foreach my $field (keys %$hidingrules) {
1648             my $val;
1649             if (exists $item->{$field}) {
1650                 $val = $item->{$field};
1651             }
1652             else {
1653                 my $query = "SELECT $field from items where itemnumber = ?";
1654                 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1655             }
1656             $val = '' unless defined $val;
1657
1658             # If the results matches the values in the yaml file
1659             if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1660
1661                 # We add the itemnumber to the list
1662                 push @resultitems, $item->{'itemnumber'};
1663
1664                 # If at least one rule matched for an item, no need to test the others
1665                 last;
1666             }
1667         }
1668     }
1669     return @resultitems;
1670 }
1671
1672 =head3 get_item_authorised_values
1673
1674 find the types and values for all authorised values assigned to this item.
1675
1676 parameters: itemnumber
1677
1678 returns: a hashref malling the authorised value to the value set for this itemnumber
1679
1680     $authorised_values = {
1681              'CCODE'      => undef,
1682              'DAMAGED'    => '0',
1683              'LOC'        => '3',
1684              'LOST'       => '0'
1685              'NOT_LOAN'   => '0',
1686              'RESTRICTED' => undef,
1687              'STACK'      => undef,
1688              'WITHDRAWN'  => '0',
1689              'branches'   => 'CPL',
1690              'cn_source'  => undef,
1691              'itemtypes'  => 'SER',
1692            };
1693
1694 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1695
1696 =cut
1697
1698 sub get_item_authorised_values {
1699     my $itemnumber = shift;
1700
1701     # assume that these entries in the authorised_value table are item level.
1702     my $query = q(SELECT distinct authorised_value, kohafield
1703                     FROM marc_subfield_structure
1704                     WHERE kohafield like 'item%'
1705                       AND authorised_value != '' );
1706
1707     my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1708     my $iteminfo = GetItem( $itemnumber );
1709     # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1710     my $return;
1711     foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1712         my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1713         $field =~ s/^items\.//;
1714         if ( exists $iteminfo->{ $field } ) {
1715             $return->{ $this_authorised_value } = $iteminfo->{ $field };
1716         }
1717     }
1718     # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1719     return $return;
1720 }
1721
1722 =head3 get_authorised_value_images
1723
1724 find a list of icons that are appropriate for display based on the
1725 authorised values for a biblio.
1726
1727 parameters: listref of authorised values, such as comes from
1728 get_item_authorised_values or
1729 from C4::Biblio::get_biblio_authorised_values
1730
1731 returns: listref of hashrefs for each image. Each hashref looks like this:
1732
1733       { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1734         label    => '',
1735         category => '',
1736         value    => '', }
1737
1738 Notes: Currently, I put on the full path to the images on the staff
1739 side. This should either be configurable or not done at all. Since I
1740 have to deal with 'intranet' or 'opac' in
1741 get_biblio_authorised_values, perhaps I should be passing it in.
1742
1743 =cut
1744
1745 sub get_authorised_value_images {
1746     my $authorised_values = shift;
1747
1748     my @imagelist;
1749
1750     my $authorised_value_list = GetAuthorisedValues();
1751     # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1752     foreach my $this_authorised_value ( @$authorised_value_list ) {
1753         if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1754              && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1755             # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1756             if ( defined $this_authorised_value->{'imageurl'} ) {
1757                 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1758                                    label    => $this_authorised_value->{'lib'},
1759                                    category => $this_authorised_value->{'category'},
1760                                    value    => $this_authorised_value->{'authorised_value'}, };
1761             }
1762         }
1763     }
1764
1765     # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1766     return \@imagelist;
1767
1768 }
1769
1770 =head1 LIMITED USE FUNCTIONS
1771
1772 The following functions, while part of the public API,
1773 are not exported.  This is generally because they are
1774 meant to be used by only one script for a specific
1775 purpose, and should not be used in any other context
1776 without careful thought.
1777
1778 =cut
1779
1780 =head2 GetMarcItem
1781
1782   my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1783
1784 Returns MARC::Record of the item passed in parameter.
1785 This function is meant for use only in C<cataloguing/additem.pl>,
1786 where it is needed to support that script's MARC-like
1787 editor.
1788
1789 =cut
1790
1791 sub GetMarcItem {
1792     my ( $biblionumber, $itemnumber ) = @_;
1793
1794     # GetMarcItem has been revised so that it does the following:
1795     #  1. Gets the item information from the items table.
1796     #  2. Converts it to a MARC field for storage in the bib record.
1797     #
1798     # The previous behavior was:
1799     #  1. Get the bib record.
1800     #  2. Return the MARC tag corresponding to the item record.
1801     #
1802     # The difference is that one treats the items row as authoritative,
1803     # while the other treats the MARC representation as authoritative
1804     # under certain circumstances.
1805
1806     my $itemrecord = GetItem($itemnumber);
1807
1808     # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1809     # Also, don't emit a subfield if the underlying field is blank.
1810
1811     
1812     return Item2Marc($itemrecord,$biblionumber);
1813
1814 }
1815 sub Item2Marc {
1816         my ($itemrecord,$biblionumber)=@_;
1817     my $mungeditem = { 
1818         map {  
1819             defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  
1820         } keys %{ $itemrecord } 
1821     };
1822     my $itemmarc = TransformKohaToMarc($mungeditem);
1823     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1824
1825     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1826     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1827                 foreach my $field ($itemmarc->field($itemtag)){
1828             $field->add_subfields(@$unlinked_item_subfields);
1829         }
1830     }
1831         return $itemmarc;
1832 }
1833
1834 =head1 PRIVATE FUNCTIONS AND VARIABLES
1835
1836 The following functions are not meant to be called
1837 directly, but are documented in order to explain
1838 the inner workings of C<C4::Items>.
1839
1840 =cut
1841
1842 =head2 %derived_columns
1843
1844 This hash keeps track of item columns that
1845 are strictly derived from other columns in
1846 the item record and are not meant to be set
1847 independently.
1848
1849 Each key in the hash should be the name of a
1850 column (as named by TransformMarcToKoha).  Each
1851 value should be hashref whose keys are the
1852 columns on which the derived column depends.  The
1853 hashref should also contain a 'BUILDER' key
1854 that is a reference to a sub that calculates
1855 the derived value.
1856
1857 =cut
1858
1859 my %derived_columns = (
1860     'items.cn_sort' => {
1861         'itemcallnumber' => 1,
1862         'items.cn_source' => 1,
1863         'BUILDER' => \&_calc_items_cn_sort,
1864     }
1865 );
1866
1867 =head2 _set_derived_columns_for_add 
1868
1869   _set_derived_column_for_add($item);
1870
1871 Given an item hash representing a new item to be added,
1872 calculate any derived columns.  Currently the only
1873 such column is C<items.cn_sort>.
1874
1875 =cut
1876
1877 sub _set_derived_columns_for_add {
1878     my $item = shift;
1879
1880     foreach my $column (keys %derived_columns) {
1881         my $builder = $derived_columns{$column}->{'BUILDER'};
1882         my $source_values = {};
1883         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1884             next if $source_column eq 'BUILDER';
1885             $source_values->{$source_column} = $item->{$source_column};
1886         }
1887         $builder->($item, $source_values);
1888     }
1889 }
1890
1891 =head2 _set_derived_columns_for_mod 
1892
1893   _set_derived_column_for_mod($item);
1894
1895 Given an item hash representing a new item to be modified.
1896 calculate any derived columns.  Currently the only
1897 such column is C<items.cn_sort>.
1898
1899 This routine differs from C<_set_derived_columns_for_add>
1900 in that it needs to handle partial item records.  In other
1901 words, the caller of C<ModItem> may have supplied only one
1902 or two columns to be changed, so this function needs to
1903 determine whether any of the columns to be changed affect
1904 any of the derived columns.  Also, if a derived column
1905 depends on more than one column, but the caller is not
1906 changing all of then, this routine retrieves the unchanged
1907 values from the database in order to ensure a correct
1908 calculation.
1909
1910 =cut
1911
1912 sub _set_derived_columns_for_mod {
1913     my $item = shift;
1914
1915     foreach my $column (keys %derived_columns) {
1916         my $builder = $derived_columns{$column}->{'BUILDER'};
1917         my $source_values = {};
1918         my %missing_sources = ();
1919         my $must_recalc = 0;
1920         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1921             next if $source_column eq 'BUILDER';
1922             if (exists $item->{$source_column}) {
1923                 $must_recalc = 1;
1924                 $source_values->{$source_column} = $item->{$source_column};
1925             } else {
1926                 $missing_sources{$source_column} = 1;
1927             }
1928         }
1929         if ($must_recalc) {
1930             foreach my $source_column (keys %missing_sources) {
1931                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1932             }
1933             $builder->($item, $source_values);
1934         }
1935     }
1936 }
1937
1938 =head2 _do_column_fixes_for_mod
1939
1940   _do_column_fixes_for_mod($item);
1941
1942 Given an item hashref containing one or more
1943 columns to modify, fix up certain values.
1944 Specifically, set to 0 any passed value
1945 of C<notforloan>, C<damaged>, C<itemlost>, or
1946 C<wthdrawn> that is either undefined or
1947 contains the empty string.
1948
1949 =cut
1950
1951 sub _do_column_fixes_for_mod {
1952     my $item = shift;
1953
1954     if (exists $item->{'notforloan'} and
1955         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1956         $item->{'notforloan'} = 0;
1957     }
1958     if (exists $item->{'damaged'} and
1959         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1960         $item->{'damaged'} = 0;
1961     }
1962     if (exists $item->{'itemlost'} and
1963         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1964         $item->{'itemlost'} = 0;
1965     }
1966     if (exists $item->{'wthdrawn'} and
1967         (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1968         $item->{'wthdrawn'} = 0;
1969     }
1970     if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1971         $item->{'permanent_location'} = $item->{'location'};
1972     }
1973     if (exists $item->{'timestamp'}) {
1974         delete $item->{'timestamp'};
1975     }
1976 }
1977
1978 =head2 _get_single_item_column
1979
1980   _get_single_item_column($column, $itemnumber);
1981
1982 Retrieves the value of a single column from an C<items>
1983 row specified by C<$itemnumber>.
1984
1985 =cut
1986
1987 sub _get_single_item_column {
1988     my $column = shift;
1989     my $itemnumber = shift;
1990     
1991     my $dbh = C4::Context->dbh;
1992     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1993     $sth->execute($itemnumber);
1994     my ($value) = $sth->fetchrow();
1995     return $value; 
1996 }
1997
1998 =head2 _calc_items_cn_sort
1999
2000   _calc_items_cn_sort($item, $source_values);
2001
2002 Helper routine to calculate C<items.cn_sort>.
2003
2004 =cut
2005
2006 sub _calc_items_cn_sort {
2007     my $item = shift;
2008     my $source_values = shift;
2009
2010     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2011 }
2012
2013 =head2 _set_defaults_for_add 
2014
2015   _set_defaults_for_add($item_hash);
2016
2017 Given an item hash representing an item to be added, set
2018 correct default values for columns whose default value
2019 is not handled by the DBMS.  This includes the following
2020 columns:
2021
2022 =over 2
2023
2024 =item * 
2025
2026 C<items.dateaccessioned>
2027
2028 =item *
2029
2030 C<items.notforloan>
2031
2032 =item *
2033
2034 C<items.damaged>
2035
2036 =item *
2037
2038 C<items.itemlost>
2039
2040 =item *
2041
2042 C<items.wthdrawn>
2043
2044 =back
2045
2046 =cut
2047
2048 sub _set_defaults_for_add {
2049     my $item = shift;
2050     $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2051     $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2052 }
2053
2054 =head2 _koha_new_item
2055
2056   my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2057
2058 Perform the actual insert into the C<items> table.
2059
2060 =cut
2061
2062 sub _koha_new_item {
2063     my ( $item, $barcode ) = @_;
2064     my $dbh=C4::Context->dbh;  
2065     my $error;
2066     my $query =
2067            "INSERT INTO items SET
2068             biblionumber        = ?,
2069             biblioitemnumber    = ?,
2070             barcode             = ?,
2071             dateaccessioned     = ?,
2072             booksellerid        = ?,
2073             homebranch          = ?,
2074             price               = ?,
2075             replacementprice    = ?,
2076             replacementpricedate = ?,
2077             datelastborrowed    = ?,
2078             datelastseen        = ?,
2079             stack               = ?,
2080             notforloan          = ?,
2081             damaged             = ?,
2082             itemlost            = ?,
2083             wthdrawn            = ?,
2084             itemcallnumber      = ?,
2085             restricted          = ?,
2086             itemnotes           = ?,
2087             holdingbranch       = ?,
2088             paidfor             = ?,
2089             location            = ?,
2090             permanent_location            = ?,
2091             onloan              = ?,
2092             issues              = ?,
2093             renewals            = ?,
2094             reserves            = ?,
2095             cn_source           = ?,
2096             cn_sort             = ?,
2097             ccode               = ?,
2098             itype               = ?,
2099             materials           = ?,
2100             uri = ?,
2101             enumchron           = ?,
2102             more_subfields_xml  = ?,
2103             copynumber          = ?,
2104             stocknumber         = ?
2105           ";
2106     my $sth = $dbh->prepare($query);
2107     my $today = C4::Dates->today('iso');
2108    $sth->execute(
2109             $item->{'biblionumber'},
2110             $item->{'biblioitemnumber'},
2111             $barcode,
2112             $item->{'dateaccessioned'},
2113             $item->{'booksellerid'},
2114             $item->{'homebranch'},
2115             $item->{'price'},
2116             $item->{'replacementprice'},
2117             $item->{'replacementpricedate'} || $today,
2118             $item->{datelastborrowed},
2119             $item->{datelastseen} || $today,
2120             $item->{stack},
2121             $item->{'notforloan'},
2122             $item->{'damaged'},
2123             $item->{'itemlost'},
2124             $item->{'wthdrawn'},
2125             $item->{'itemcallnumber'},
2126             $item->{'restricted'},
2127             $item->{'itemnotes'},
2128             $item->{'holdingbranch'},
2129             $item->{'paidfor'},
2130             $item->{'location'},
2131             $item->{'permanent_location'},
2132             $item->{'onloan'},
2133             $item->{'issues'},
2134             $item->{'renewals'},
2135             $item->{'reserves'},
2136             $item->{'items.cn_source'},
2137             $item->{'items.cn_sort'},
2138             $item->{'ccode'},
2139             $item->{'itype'},
2140             $item->{'materials'},
2141             $item->{'uri'},
2142             $item->{'enumchron'},
2143             $item->{'more_subfields_xml'},
2144             $item->{'copynumber'},
2145             $item->{'stocknumber'},
2146     );
2147
2148     my $itemnumber;
2149     if ( defined $sth->errstr ) {
2150         $error.="ERROR in _koha_new_item $query".$sth->errstr;
2151     }
2152     else {
2153         $itemnumber = $dbh->{'mysql_insertid'};
2154     }
2155
2156     return ( $itemnumber, $error );
2157 }
2158
2159 =head2 MoveItemFromBiblio
2160
2161   MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2162
2163 Moves an item from a biblio to another
2164
2165 Returns undef if the move failed or the biblionumber of the destination record otherwise
2166
2167 =cut
2168
2169 sub MoveItemFromBiblio {
2170     my ($itemnumber, $frombiblio, $tobiblio) = @_;
2171     my $dbh = C4::Context->dbh;
2172     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2173     $sth->execute( $tobiblio );
2174     my ( $tobiblioitem ) = $sth->fetchrow();
2175     $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2176     my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2177     if ($return == 1) {
2178         ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2179         ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2180             # Checking if the item we want to move is in an order 
2181         my $order = GetOrderFromItemnumber($itemnumber);
2182             if ($order) {
2183                     # Replacing the biblionumber within the order if necessary
2184                     $order->{'biblionumber'} = $tobiblio;
2185                 ModOrder($order);
2186             }
2187         return $tobiblio;
2188         }
2189     return;
2190 }
2191
2192 =head2 DelItemCheck
2193
2194    DelItemCheck($dbh, $biblionumber, $itemnumber);
2195
2196 Exported function (core API) for deleting an item record in Koha if there no current issue.
2197
2198 =cut
2199
2200 sub DelItemCheck {
2201     my ( $dbh, $biblionumber, $itemnumber ) = @_;
2202     my $error;
2203
2204         my $countanalytics=GetAnalyticsCount($itemnumber);
2205
2206
2207     # check that there is no issue on this item before deletion.
2208     my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2209     $sth->execute($itemnumber);
2210
2211     my $item = GetItem($itemnumber);
2212     my $onloan=$sth->fetchrow;
2213
2214     if ($onloan){
2215         $error = "book_on_loan" 
2216     }
2217     elsif ( !(C4::Context->userenv->{flags} & 1) and
2218             C4::Context->preference("IndependantBranches") and
2219            (C4::Context->userenv->{branch} ne
2220              $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2221     {
2222         $error = "not_same_branch";
2223     }
2224         else{
2225         # check it doesnt have a waiting reserve
2226         $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2227         $sth->execute($itemnumber);
2228         my $reserve=$sth->fetchrow;
2229         if ($reserve){
2230             $error = "book_reserved";
2231         } elsif ($countanalytics > 0){
2232                 $error = "linked_analytics";
2233         } else {
2234             DelItem($dbh, $biblionumber, $itemnumber);
2235             return 1;
2236         }
2237     }
2238     return $error;
2239 }
2240
2241 =head2 _koha_modify_item
2242
2243   my ($itemnumber,$error) =_koha_modify_item( $item );
2244
2245 Perform the actual update of the C<items> row.  Note that this
2246 routine accepts a hashref specifying the columns to update.
2247
2248 =cut
2249
2250 sub _koha_modify_item {
2251     my ( $item ) = @_;
2252     my $dbh=C4::Context->dbh;  
2253     my $error;
2254
2255     my $query = "UPDATE items SET ";
2256     my @bind;
2257     for my $key ( keys %$item ) {
2258         $query.="$key=?,";
2259         push @bind, $item->{$key};
2260     }
2261     $query =~ s/,$//;
2262     $query .= " WHERE itemnumber=?";
2263     push @bind, $item->{'itemnumber'};
2264     my $sth = C4::Context->dbh->prepare($query);
2265     $sth->execute(@bind);
2266     if ( C4::Context->dbh->errstr ) {
2267         $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2268         warn $error;
2269     }
2270     return ($item->{'itemnumber'},$error);
2271 }
2272
2273 =head2 _koha_delete_item
2274
2275   _koha_delete_item( $dbh, $itemnum );
2276
2277 Internal function to delete an item record from the koha tables
2278
2279 =cut
2280
2281 sub _koha_delete_item {
2282     my ( $dbh, $itemnum ) = @_;
2283
2284     # save the deleted item to deleteditems table
2285     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2286     $sth->execute($itemnum);
2287     my $data = $sth->fetchrow_hashref();
2288     my $query = "INSERT INTO deleteditems SET ";
2289     my @bind  = ();
2290     foreach my $key ( keys %$data ) {
2291         $query .= "$key = ?,";
2292         push( @bind, $data->{$key} );
2293     }
2294     $query =~ s/\,$//;
2295     $sth = $dbh->prepare($query);
2296     $sth->execute(@bind);
2297
2298     # delete from items table
2299     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2300     $sth->execute($itemnum);
2301     return undef;
2302 }
2303
2304 =head2 _marc_from_item_hash
2305
2306   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2307
2308 Given an item hash representing a complete item record,
2309 create a C<MARC::Record> object containing an embedded
2310 tag representing that item.
2311
2312 The third, optional parameter C<$unlinked_item_subfields> is
2313 an arrayref of subfields (not mapped to C<items> fields per the
2314 framework) to be added to the MARC representation
2315 of the item.
2316
2317 =cut
2318
2319 sub _marc_from_item_hash {
2320     my $item = shift;
2321     my $frameworkcode = shift;
2322     my $unlinked_item_subfields;
2323     if (@_) {
2324         $unlinked_item_subfields = shift;
2325     }
2326    
2327     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2328     # Also, don't emit a subfield if the underlying field is blank.
2329     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
2330                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
2331                                 : ()  } keys %{ $item } }; 
2332
2333     my $item_marc = MARC::Record->new();
2334     foreach my $item_field ( keys %{$mungeditem} ) {
2335         my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2336         next unless defined $tag and defined $subfield;    # skip if not mapped to MARC field
2337         my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2338         foreach my $value (@values){
2339             if ( my $field = $item_marc->field($tag) ) {
2340                     $field->add_subfields( $subfield => $value );
2341             } else {
2342                 my $add_subfields = [];
2343                 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2344                     $add_subfields = $unlinked_item_subfields;
2345             }
2346             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2347             }
2348         }
2349     }
2350
2351     return $item_marc;
2352 }
2353
2354 =head2 _repack_item_errors
2355
2356 Add an error message hash generated by C<CheckItemPreSave>
2357 to a list of errors.
2358
2359 =cut
2360
2361 sub _repack_item_errors {
2362     my $item_sequence_num = shift;
2363     my $item_ref = shift;
2364     my $error_ref = shift;
2365
2366     my @repacked_errors = ();
2367
2368     foreach my $error_code (sort keys %{ $error_ref }) {
2369         my $repacked_error = {};
2370         $repacked_error->{'item_sequence'} = $item_sequence_num;
2371         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2372         $repacked_error->{'error_code'} = $error_code;
2373         $repacked_error->{'error_information'} = $error_ref->{$error_code};
2374         push @repacked_errors, $repacked_error;
2375     } 
2376
2377     return @repacked_errors;
2378 }
2379
2380 =head2 _get_unlinked_item_subfields
2381
2382   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2383
2384 =cut
2385
2386 sub _get_unlinked_item_subfields {
2387     my $original_item_marc = shift;
2388     my $frameworkcode = shift;
2389
2390     my $marcstructure = GetMarcStructure(1, $frameworkcode);
2391
2392     # assume that this record has only one field, and that that
2393     # field contains only the item information
2394     my $subfields = [];
2395     my @fields = $original_item_marc->fields();
2396     if ($#fields > -1) {
2397         my $field = $fields[0];
2398             my $tag = $field->tag();
2399         foreach my $subfield ($field->subfields()) {
2400             if (defined $subfield->[1] and
2401                 $subfield->[1] ne '' and
2402                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2403                 push @$subfields, $subfield->[0] => $subfield->[1];
2404             }
2405         }
2406     }
2407     return $subfields;
2408 }
2409
2410 =head2 _get_unlinked_subfields_xml
2411
2412   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2413
2414 =cut
2415
2416 sub _get_unlinked_subfields_xml {
2417     my $unlinked_item_subfields = shift;
2418
2419     my $xml;
2420     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2421         my $marc = MARC::Record->new();
2422         # use of tag 999 is arbitrary, and doesn't need to match the item tag
2423         # used in the framework
2424         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2425         $marc->encoding("UTF-8");    
2426         $xml = $marc->as_xml("USMARC");
2427     }
2428
2429     return $xml;
2430 }
2431
2432 =head2 _parse_unlinked_item_subfields_from_xml
2433
2434   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2435
2436 =cut
2437
2438 sub  _parse_unlinked_item_subfields_from_xml {
2439     my $xml = shift;
2440
2441     return unless defined $xml and $xml ne "";
2442     my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2443     my $unlinked_subfields = [];
2444     my @fields = $marc->fields();
2445     if ($#fields > -1) {
2446         foreach my $subfield ($fields[0]->subfields()) {
2447             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2448         }
2449     }
2450     return $unlinked_subfields;
2451 }
2452
2453 =head2 GetAnalyticsCount
2454
2455   $count= &GetAnalyticsCount($itemnumber)
2456
2457 counts Usage of itemnumber in Analytical bibliorecords. 
2458
2459 =cut
2460
2461 sub GetAnalyticsCount {
2462     my ($itemnumber) = @_;
2463     if (C4::Context->preference('NoZebra')) {
2464         # Read the index Koha-Auth-Number for this authid and count the lines
2465         my $result = C4::Search::NZanalyse("hi=$itemnumber");
2466         my @tab = split /;/,$result;
2467         return scalar @tab;
2468     } else {
2469         ### ZOOM search here
2470         my $query;
2471         $query= "hi=".$itemnumber;
2472                 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2473         return ($result);
2474     }
2475 }
2476
2477 =head2 GetItemHolds
2478
2479 =over 4
2480 $holds = &GetItemHolds($biblionumber, $itemnumber);
2481
2482 =back
2483
2484 This function return the count of holds with $biblionumber and $itemnumber
2485
2486 =cut
2487
2488 sub GetItemHolds {
2489     my ($biblionumber, $itemnumber) = @_;
2490     my $holds;
2491     my $dbh            = C4::Context->dbh;
2492     my $query          = "SELECT count(*)
2493         FROM  reserves
2494         WHERE biblionumber=? AND itemnumber=?";
2495     my $sth = $dbh->prepare($query);
2496     $sth->execute($biblionumber, $itemnumber);
2497     $holds = $sth->fetchrow;
2498     return $holds;
2499 }
2500 1;