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