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