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