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