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