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