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