Bug 12583: DelItem prototype - Remove $dbh
[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( $biblionumber, $itemnumber );
636
637 Exported function (core API) for deleting an item record in Koha.
638
639 =cut
640
641 sub DelItem {
642     my ( $biblionumber, $itemnumber ) = @_;
643
644     # FIXME check the item has no current issues
645     _koha_delete_item( $itemnumber );
646
647     # get the MARC record
648     my $record = GetMarcBiblio($biblionumber);
649     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
650
651     #search item field code
652     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
653 }
654
655 =head2 CheckItemPreSave
656
657     my $item_ref = TransformMarcToKoha($marc, 'items');
658     # do stuff
659     my %errors = CheckItemPreSave($item_ref);
660     if (exists $errors{'duplicate_barcode'}) {
661         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
662     } elsif (exists $errors{'invalid_homebranch'}) {
663         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
664     } elsif (exists $errors{'invalid_holdingbranch'}) {
665         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
666     } else {
667         print "item is OK";
668     }
669
670 Given a hashref containing item fields, determine if it can be
671 inserted or updated in the database.  Specifically, checks for
672 database integrity issues, and returns a hash containing any
673 of the following keys, if applicable.
674
675 =over 2
676
677 =item duplicate_barcode
678
679 Barcode, if it duplicates one already found in the database.
680
681 =item invalid_homebranch
682
683 Home branch, if not defined in branches table.
684
685 =item invalid_holdingbranch
686
687 Holding branch, if not defined in branches table.
688
689 =back
690
691 This function does NOT implement any policy-related checks,
692 e.g., whether current operator is allowed to save an
693 item that has a given branch code.
694
695 =cut
696
697 sub CheckItemPreSave {
698     my $item_ref = shift;
699     require C4::Branch;
700
701     my %errors = ();
702
703     # check for duplicate barcode
704     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
705         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
706         if ($existing_itemnumber) {
707             if (!exists $item_ref->{'itemnumber'}                       # new item
708                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
709                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
710             }
711         }
712     }
713
714     # check for valid home branch
715     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
716         my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
717         unless (defined $branch_name) {
718             # relies on fact that branches.branchname is a non-NULL column,
719             # so GetBranchName returns undef only if branch does not exist
720             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
721         }
722     }
723
724     # check for valid holding branch
725     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
726         my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
727         unless (defined $branch_name) {
728             # relies on fact that branches.branchname is a non-NULL column,
729             # so GetBranchName returns undef only if branch does not exist
730             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
731         }
732     }
733
734     return %errors;
735
736 }
737
738 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
739
740 The following functions provide various ways of 
741 getting an item record, a set of item records, or
742 lists of authorized values for certain item fields.
743
744 Some of the functions in this group are candidates
745 for refactoring -- for example, some of the code
746 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
747 has copy-and-paste work.
748
749 =cut
750
751 =head2 GetItemStatus
752
753   $itemstatushash = GetItemStatus($fwkcode);
754
755 Returns a list of valid values for the
756 C<items.notforloan> field.
757
758 NOTE: does B<not> return an individual item's
759 status.
760
761 Can be MARC dependant.
762 fwkcode is optional.
763 But basically could be can be loan or not
764 Create a status selector with the following code
765
766 =head3 in PERL SCRIPT
767
768  my $itemstatushash = getitemstatus;
769  my @itemstatusloop;
770  foreach my $thisstatus (keys %$itemstatushash) {
771      my %row =(value => $thisstatus,
772                  statusname => $itemstatushash->{$thisstatus}->{'statusname'},
773              );
774      push @itemstatusloop, \%row;
775  }
776  $template->param(statusloop=>\@itemstatusloop);
777
778 =head3 in TEMPLATE
779
780 <select name="statusloop" id="statusloop">
781     <option value="">Default</option>
782     [% FOREACH statusloo IN statusloop %]
783         [% IF ( statusloo.selected ) %]
784             <option value="[% statusloo.value %]" selected="selected">[% statusloo.statusname %]</option>
785         [% ELSE %]
786             <option value="[% statusloo.value %]">[% statusloo.statusname %]</option>
787         [% END %]
788     [% END %]
789 </select>
790
791 =cut
792
793 sub GetItemStatus {
794
795     # returns a reference to a hash of references to status...
796     my ($fwk) = @_;
797     my %itemstatus;
798     my $dbh = C4::Context->dbh;
799     my $sth;
800     $fwk = '' unless ($fwk);
801     my ( $tag, $subfield ) =
802       GetMarcFromKohaField( "items.notforloan", $fwk );
803     if ( $tag and $subfield ) {
804         my $sth =
805           $dbh->prepare(
806             "SELECT authorised_value
807             FROM marc_subfield_structure
808             WHERE tagfield=?
809                 AND tagsubfield=?
810                 AND frameworkcode=?
811             "
812           );
813         $sth->execute( $tag, $subfield, $fwk );
814         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
815             my $authvalsth =
816               $dbh->prepare(
817                 "SELECT authorised_value,lib
818                 FROM authorised_values 
819                 WHERE category=? 
820                 ORDER BY lib
821                 "
822               );
823             $authvalsth->execute($authorisedvaluecat);
824             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
825                 $itemstatus{$authorisedvalue} = $lib;
826             }
827             return \%itemstatus;
828             exit 1;
829         }
830         else {
831
832             #No authvalue list
833             # build default
834         }
835     }
836
837     #No authvalue list
838     #build default
839     $itemstatus{"1"} = "Not For Loan";
840     return \%itemstatus;
841 }
842
843 =head2 GetItemLocation
844
845   $itemlochash = GetItemLocation($fwk);
846
847 Returns a list of valid values for the
848 C<items.location> field.
849
850 NOTE: does B<not> return an individual item's
851 location.
852
853 where fwk stands for an optional framework code.
854 Create a location selector with the following code
855
856 =head3 in PERL SCRIPT
857
858   my $itemlochash = getitemlocation;
859   my @itemlocloop;
860   foreach my $thisloc (keys %$itemlochash) {
861       my $selected = 1 if $thisbranch eq $branch;
862       my %row =(locval => $thisloc,
863                   selected => $selected,
864                   locname => $itemlochash->{$thisloc},
865                );
866       push @itemlocloop, \%row;
867   }
868   $template->param(itemlocationloop => \@itemlocloop);
869
870 =head3 in TEMPLATE
871
872   <select name="location">
873       <option value="">Default</option>
874   <!-- TMPL_LOOP name="itemlocationloop" -->
875       <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
876   <!-- /TMPL_LOOP -->
877   </select>
878
879 =cut
880
881 sub GetItemLocation {
882
883     # returns a reference to a hash of references to location...
884     my ($fwk) = @_;
885     my %itemlocation;
886     my $dbh = C4::Context->dbh;
887     my $sth;
888     $fwk = '' unless ($fwk);
889     my ( $tag, $subfield ) =
890       GetMarcFromKohaField( "items.location", $fwk );
891     if ( $tag and $subfield ) {
892         my $sth =
893           $dbh->prepare(
894             "SELECT authorised_value
895             FROM marc_subfield_structure 
896             WHERE tagfield=? 
897                 AND tagsubfield=? 
898                 AND frameworkcode=?"
899           );
900         $sth->execute( $tag, $subfield, $fwk );
901         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
902             my $authvalsth =
903               $dbh->prepare(
904                 "SELECT authorised_value,lib
905                 FROM authorised_values
906                 WHERE category=?
907                 ORDER BY lib"
908               );
909             $authvalsth->execute($authorisedvaluecat);
910             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
911                 $itemlocation{$authorisedvalue} = $lib;
912             }
913             return \%itemlocation;
914             exit 1;
915         }
916         else {
917
918             #No authvalue list
919             # build default
920         }
921     }
922
923     #No authvalue list
924     #build default
925     $itemlocation{"1"} = "Not For Loan";
926     return \%itemlocation;
927 }
928
929 =head2 GetLostItems
930
931   $items = GetLostItems( $where, $orderby );
932
933 This function gets a list of lost items.
934
935 =over 2
936
937 =item input:
938
939 C<$where> is a hashref. it containts a field of the items table as key
940 and the value to match as value. For example:
941
942 { barcode    => 'abc123',
943   homebranch => 'CPL',    }
944
945 C<$orderby> is a field of the items table by which the resultset
946 should be orderd.
947
948 =item return:
949
950 C<$items> is a reference to an array full of hashrefs with columns
951 from the "items" table as keys.
952
953 =item usage in the perl script:
954
955   my $where = { barcode => '0001548' };
956   my $items = GetLostItems( $where, "homebranch" );
957   $template->param( itemsloop => $items );
958
959 =back
960
961 =cut
962
963 sub GetLostItems {
964     # Getting input args.
965     my $where   = shift;
966     my $orderby = shift;
967     my $dbh     = C4::Context->dbh;
968
969     my $query   = "
970         SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
971                itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber
972         FROM   items
973             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
974             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
975             LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
976         WHERE
977                 authorised_values.category = 'LOST'
978                 AND itemlost IS NOT NULL
979                 AND itemlost <> 0
980     ";
981     my @query_parameters;
982     foreach my $key (keys %$where) {
983         $query .= " AND $key LIKE ?";
984         push @query_parameters, "%$where->{$key}%";
985     }
986     my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
987     
988     if ( defined $orderby && grep($orderby, @ordervalues)) {
989         $query .= ' ORDER BY '.$orderby;
990     }
991
992     my $sth = $dbh->prepare($query);
993     $sth->execute( @query_parameters );
994     my $items = [];
995     while ( my $row = $sth->fetchrow_hashref ){
996         push @$items, $row;
997     }
998     return $items;
999 }
1000
1001 =head2 GetItemsForInventory
1002
1003 ($itemlist, $iTotalRecords)  = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $offset, $size, $statushash);
1004
1005 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1006
1007 The sub returns a reference to a list of hashes, each containing
1008 itemnumber, author, title, barcode, item callnumber, and date last
1009 seen. It is ordered by callnumber then title.
1010
1011 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1012 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1013 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1014 $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.
1015
1016 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
1017
1018 =cut
1019
1020 sub GetItemsForInventory {
1021     my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
1022     my $dbh = C4::Context->dbh;
1023     my ( @bind_params, @where_strings );
1024
1025     my $select_columns = q{
1026         SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, stocknumber
1027     };
1028     my $select_count = q{SELECT COUNT(*)};
1029     my $query = q{
1030         FROM items
1031         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1032         LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1033     };
1034     if ($statushash){
1035         for my $authvfield (keys %$statushash){
1036             if ( scalar @{$statushash->{$authvfield}} > 0 ){
1037                 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1038                 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1039             }
1040         }
1041     }
1042
1043     if ($minlocation) {
1044         push @where_strings, 'itemcallnumber >= ?';
1045         push @bind_params, $minlocation;
1046     }
1047
1048     if ($maxlocation) {
1049         push @where_strings, 'itemcallnumber <= ?';
1050         push @bind_params, $maxlocation;
1051     }
1052
1053     if ($datelastseen) {
1054         $datelastseen = format_date_in_iso($datelastseen);  
1055         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1056         push @bind_params, $datelastseen;
1057     }
1058
1059     if ( $location ) {
1060         push @where_strings, 'items.location = ?';
1061         push @bind_params, $location;
1062     }
1063
1064     if ( $branchcode ) {
1065         if($branch eq "homebranch"){
1066         push @where_strings, 'items.homebranch = ?';
1067         }else{
1068             push @where_strings, 'items.holdingbranch = ?';
1069         }
1070         push @bind_params, $branchcode;
1071     }
1072
1073     if ( $itemtype ) {
1074         push @where_strings, 'biblioitems.itemtype = ?';
1075         push @bind_params, $itemtype;
1076     }
1077
1078     if ( $ignoreissued) {
1079         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1080         push @where_strings, 'issues.date_due IS NULL';
1081     }
1082
1083     if ( @where_strings ) {
1084         $query .= 'WHERE ';
1085         $query .= join ' AND ', @where_strings;
1086     }
1087     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1088     my $count_query = $select_count . $query;
1089     $query .= " LIMIT $offset, $size" if ($offset and $size);
1090     $query = $select_columns . $query;
1091     my $sth = $dbh->prepare($query);
1092     $sth->execute( @bind_params );
1093
1094     my @results = ();
1095     my $tmpresults = $sth->fetchall_arrayref({});
1096     $sth = $dbh->prepare( $count_query );
1097     $sth->execute( @bind_params );
1098     my ($iTotalRecords) = $sth->fetchrow_array();
1099
1100     foreach my $row (@$tmpresults) {
1101
1102         # Auth values
1103         foreach (keys %$row) {
1104             # If the koha field is mapped to a marc field
1105             my ($f, $sf) = GetMarcFromKohaField("items.$_", $row->{'frameworkcode'});
1106             if ($f and $sf) {
1107                 # We replace the code with it's description
1108                 my $authvals = C4::Koha::GetKohaAuthorisedValuesFromField($f, $sf, $row->{'frameworkcode'});
1109                 $row->{$_} = $authvals->{$row->{$_}} if defined $authvals->{$row->{$_}};
1110             }
1111         }
1112         push @results, $row;
1113     }
1114
1115     return (\@results, $iTotalRecords);
1116 }
1117
1118 =head2 GetItemsCount
1119
1120   $count = &GetItemsCount( $biblionumber);
1121
1122 This function return count of item with $biblionumber
1123
1124 =cut
1125
1126 sub GetItemsCount {
1127     my ( $biblionumber ) = @_;
1128     my $dbh = C4::Context->dbh;
1129     my $query = "SELECT count(*)
1130           FROM  items 
1131           WHERE biblionumber=?";
1132     my $sth = $dbh->prepare($query);
1133     $sth->execute($biblionumber);
1134     my $count = $sth->fetchrow;  
1135     return ($count);
1136 }
1137
1138 =head2 GetItemInfosOf
1139
1140   GetItemInfosOf(@itemnumbers);
1141
1142 =cut
1143
1144 sub GetItemInfosOf {
1145     my @itemnumbers = @_;
1146
1147     my $itemnumber_values = @itemnumbers ? join( ',', @itemnumbers ) : "''";
1148
1149     my $query = "
1150         SELECT *
1151         FROM items
1152         WHERE itemnumber IN ($itemnumber_values)
1153     ";
1154     return get_infos_of( $query, 'itemnumber' );
1155 }
1156
1157 =head2 GetItemsByBiblioitemnumber
1158
1159   GetItemsByBiblioitemnumber($biblioitemnumber);
1160
1161 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1162 Called by C<C4::XISBN>
1163
1164 =cut
1165
1166 sub GetItemsByBiblioitemnumber {
1167     my ( $bibitem ) = @_;
1168     my $dbh = C4::Context->dbh;
1169     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1170     # Get all items attached to a biblioitem
1171     my $i = 0;
1172     my @results; 
1173     $sth->execute($bibitem) || die $sth->errstr;
1174     while ( my $data = $sth->fetchrow_hashref ) {  
1175         # Foreach item, get circulation information
1176         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1177                                    WHERE itemnumber = ?
1178                                    AND issues.borrowernumber = borrowers.borrowernumber"
1179         );
1180         $sth2->execute( $data->{'itemnumber'} );
1181         if ( my $data2 = $sth2->fetchrow_hashref ) {
1182             # if item is out, set the due date and who it is out too
1183             $data->{'date_due'}   = $data2->{'date_due'};
1184             $data->{'cardnumber'} = $data2->{'cardnumber'};
1185             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1186         }
1187         else {
1188             # set date_due to blank, so in the template we check itemlost, and withdrawn
1189             $data->{'date_due'} = '';                                                                                                         
1190         }    # else         
1191         # Find the last 3 people who borrowed this item.                  
1192         my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1193                       AND old_issues.borrowernumber = borrowers.borrowernumber
1194                       ORDER BY returndate desc,timestamp desc LIMIT 3";
1195         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1196         $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1197         my $i2 = 0;
1198         while ( my $data2 = $sth2->fetchrow_hashref ) {
1199             $data->{"timestamp$i2"} = $data2->{'timestamp'};
1200             $data->{"card$i2"}      = $data2->{'cardnumber'};
1201             $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1202             $i2++;
1203         }
1204         push(@results,$data);
1205     } 
1206     return (\@results); 
1207 }
1208
1209 =head2 GetItemsInfo
1210
1211   @results = GetItemsInfo($biblionumber);
1212
1213 Returns information about items with the given biblionumber.
1214
1215 C<GetItemsInfo> returns a list of references-to-hash. Each element
1216 contains a number of keys. Most of them are attributes from the
1217 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1218 Koha database. Other keys include:
1219
1220 =over 2
1221
1222 =item C<$data-E<gt>{branchname}>
1223
1224 The name (not the code) of the branch to which the book belongs.
1225
1226 =item C<$data-E<gt>{datelastseen}>
1227
1228 This is simply C<items.datelastseen>, except that while the date is
1229 stored in YYYY-MM-DD format in the database, here it is converted to
1230 DD/MM/YYYY format. A NULL date is returned as C<//>.
1231
1232 =item C<$data-E<gt>{datedue}>
1233
1234 =item C<$data-E<gt>{class}>
1235
1236 This is the concatenation of C<biblioitems.classification>, the book's
1237 Dewey code, and C<biblioitems.subclass>.
1238
1239 =item C<$data-E<gt>{ocount}>
1240
1241 I think this is the number of copies of the book available.
1242
1243 =item C<$data-E<gt>{order}>
1244
1245 If this is set, it is set to C<One Order>.
1246
1247 =back
1248
1249 =cut
1250
1251 sub GetItemsInfo {
1252     my ( $biblionumber ) = @_;
1253     my $dbh   = C4::Context->dbh;
1254     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1255     my $query = "
1256     SELECT items.*,
1257            biblio.*,
1258            biblioitems.volume,
1259            biblioitems.number,
1260            biblioitems.itemtype,
1261            biblioitems.isbn,
1262            biblioitems.issn,
1263            biblioitems.publicationyear,
1264            biblioitems.publishercode,
1265            biblioitems.volumedate,
1266            biblioitems.volumedesc,
1267            biblioitems.lccn,
1268            biblioitems.url,
1269            items.notforloan as itemnotforloan,
1270            itemtypes.description,
1271            itemtypes.notforloan as notforloan_per_itemtype,
1272            holding.branchurl,
1273            holding.branchname,
1274            holding.opac_info as holding_branch_opac_info,
1275            home.opac_info as home_branch_opac_info
1276      FROM items
1277      LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1278      LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1279      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
1280      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1281      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
1282      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1283     $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1284     my $sth = $dbh->prepare($query);
1285     $sth->execute($biblionumber);
1286     my $i = 0;
1287     my @results;
1288     my $serial;
1289
1290     my $isth    = $dbh->prepare(
1291         "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1292         FROM   issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1293         WHERE  itemnumber = ?"
1294        );
1295         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
1296         while ( my $data = $sth->fetchrow_hashref ) {
1297         my $datedue = '';
1298         $isth->execute( $data->{'itemnumber'} );
1299         if ( my $idata = $isth->fetchrow_hashref ) {
1300             $data->{borrowernumber} = $idata->{borrowernumber};
1301             $data->{cardnumber}     = $idata->{cardnumber};
1302             $data->{surname}     = $idata->{surname};
1303             $data->{firstname}     = $idata->{firstname};
1304             $data->{lastreneweddate} = $idata->{lastreneweddate};
1305             $datedue                = $idata->{'date_due'};
1306         if (C4::Context->preference("IndependentBranches")){
1307         my $userenv = C4::Context->userenv;
1308         unless ( C4::Context->IsSuperLibrarian() ) {
1309             $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1310         }
1311         }
1312         }
1313                 if ( $data->{'serial'}) {       
1314                         $ssth->execute($data->{'itemnumber'}) ;
1315                         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1316                         $serial = 1;
1317         }
1318         #get branch information.....
1319         my $bsth = $dbh->prepare(
1320             "SELECT * FROM branches WHERE branchcode = ?
1321         "
1322         );
1323         $bsth->execute( $data->{'holdingbranch'} );
1324         if ( my $bdata = $bsth->fetchrow_hashref ) {
1325             $data->{'branchname'} = $bdata->{'branchname'};
1326         }
1327         $data->{'datedue'}        = $datedue;
1328
1329         # get notforloan complete status if applicable
1330         if ( my $code = C4::Koha::GetAuthValCode( 'items.notforloan', $data->{frameworkcode} ) ) {
1331             $data->{notforloanvalue}     = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan} );
1332             $data->{notforloanvalueopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{itemnotforloan}, 1 );
1333         }
1334
1335         # get restricted status and description if applicable
1336         if ( my $code = C4::Koha::GetAuthValCode( 'items.restricted', $data->{frameworkcode} ) ) {
1337             $data->{restrictedopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted}, 1 );
1338             $data->{restricted}     = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
1339         }
1340
1341         # my stack procedures
1342         if ( my $code = C4::Koha::GetAuthValCode( 'items.stack', $data->{frameworkcode} ) ) {
1343             $data->{stack}          = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{stack} );
1344         }
1345         # Find the last 3 people who borrowed this item.
1346         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1347                                     WHERE itemnumber = ?
1348                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1349                                     ORDER BY returndate DESC
1350                                     LIMIT 3");
1351         $sth2->execute($data->{'itemnumber'});
1352         my $ii = 0;
1353         while (my $data2 = $sth2->fetchrow_hashref()) {
1354             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1355             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1356             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1357             $ii++;
1358         }
1359
1360         $results[$i] = $data;
1361         $i++;
1362     }
1363         if($serial) {
1364                 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1365         } else {
1366         return (@results);
1367         }
1368 }
1369
1370 =head2 GetItemsLocationInfo
1371
1372   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1373
1374 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1375
1376 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1377
1378 =over 2
1379
1380 =item C<$data-E<gt>{homebranch}>
1381
1382 Branch Name of the item's homebranch
1383
1384 =item C<$data-E<gt>{holdingbranch}>
1385
1386 Branch Name of the item's holdingbranch
1387
1388 =item C<$data-E<gt>{location}>
1389
1390 Item's shelving location code
1391
1392 =item C<$data-E<gt>{location_intranet}>
1393
1394 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1395
1396 =item C<$data-E<gt>{location_opac}>
1397
1398 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
1399 description is set.
1400
1401 =item C<$data-E<gt>{itemcallnumber}>
1402
1403 Item's itemcallnumber
1404
1405 =item C<$data-E<gt>{cn_sort}>
1406
1407 Item's call number normalized for sorting
1408
1409 =back
1410   
1411 =cut
1412
1413 sub GetItemsLocationInfo {
1414         my $biblionumber = shift;
1415         my @results;
1416
1417         my $dbh = C4::Context->dbh;
1418         my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch, 
1419                             location, itemcallnumber, cn_sort
1420                      FROM items, branches as a, branches as b
1421                      WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode 
1422                      AND biblionumber = ?
1423                      ORDER BY cn_sort ASC";
1424         my $sth = $dbh->prepare($query);
1425         $sth->execute($biblionumber);
1426
1427         while ( my $data = $sth->fetchrow_hashref ) {
1428              $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1429              $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1430              push @results, $data;
1431         }
1432         return @results;
1433 }
1434
1435 =head2 GetHostItemsInfo
1436
1437         $hostiteminfo = GetHostItemsInfo($hostfield);
1438         Returns the iteminfo for items linked to records via a host field
1439
1440 =cut
1441
1442 sub GetHostItemsInfo {
1443         my ($record) = @_;
1444         my @returnitemsInfo;
1445
1446         if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1447         C4::Context->preference('marcflavour') eq 'NORMARC'){
1448             foreach my $hostfield ( $record->field('773') ) {
1449                 my $hostbiblionumber = $hostfield->subfield("0");
1450                 my $linkeditemnumber = $hostfield->subfield("9");
1451                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1452                 foreach my $hostitemInfo (@hostitemInfos){
1453                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1454                                 push (@returnitemsInfo,$hostitemInfo);
1455                                 last;
1456                         }
1457                 }
1458             }
1459         } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1460             foreach my $hostfield ( $record->field('461') ) {
1461                 my $hostbiblionumber = $hostfield->subfield("0");
1462                 my $linkeditemnumber = $hostfield->subfield("9");
1463                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1464                 foreach my $hostitemInfo (@hostitemInfos){
1465                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1466                                 push (@returnitemsInfo,$hostitemInfo);
1467                                 last;
1468                         }
1469                 }
1470             }
1471         }
1472         return @returnitemsInfo;
1473 }
1474
1475
1476 =head2 GetLastAcquisitions
1477
1478   my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
1479                                     'itemtypes' => ('BK','BD')}, 10);
1480
1481 =cut
1482
1483 sub  GetLastAcquisitions {
1484         my ($data,$max) = @_;
1485
1486         my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1487         
1488         my $number_of_branches = @{$data->{branches}};
1489         my $number_of_itemtypes   = @{$data->{itemtypes}};
1490         
1491         
1492         my @where = ('WHERE 1 '); 
1493         $number_of_branches and push @where
1494            , 'AND holdingbranch IN (' 
1495            , join(',', ('?') x $number_of_branches )
1496            , ')'
1497          ;
1498         
1499         $number_of_itemtypes and push @where
1500            , "AND $itemtype IN (" 
1501            , join(',', ('?') x $number_of_itemtypes )
1502            , ')'
1503          ;
1504
1505         my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1506                                  FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber) 
1507                                     RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1508                                     @where
1509                                     GROUP BY biblio.biblionumber 
1510                                     ORDER BY dateaccessioned DESC LIMIT $max";
1511
1512         my $dbh = C4::Context->dbh;
1513         my $sth = $dbh->prepare($query);
1514     
1515     $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1516         
1517         my @results;
1518         while( my $row = $sth->fetchrow_hashref){
1519                 push @results, {date => $row->{dateaccessioned} 
1520                                                 , biblionumber => $row->{biblionumber}
1521                                                 , title => $row->{title}};
1522         }
1523         
1524         return @results;
1525 }
1526
1527 =head2 GetItemnumbersForBiblio
1528
1529   my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1530
1531 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1532
1533 =cut
1534
1535 sub GetItemnumbersForBiblio {
1536     my $biblionumber = shift;
1537     my @items;
1538     my $dbh = C4::Context->dbh;
1539     my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1540     $sth->execute($biblionumber);
1541     while (my $result = $sth->fetchrow_hashref) {
1542         push @items, $result->{'itemnumber'};
1543     }
1544     return \@items;
1545 }
1546
1547 =head2 get_itemnumbers_of
1548
1549   my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1550
1551 Given a list of biblionumbers, return the list of corresponding itemnumbers
1552 for each biblionumber.
1553
1554 Return a reference on a hash where keys are biblionumbers and values are
1555 references on array of itemnumbers.
1556
1557 =cut
1558
1559 sub get_itemnumbers_of {
1560     my @biblionumbers = @_;
1561
1562     my $dbh = C4::Context->dbh;
1563
1564     my $query = '
1565         SELECT itemnumber,
1566             biblionumber
1567         FROM items
1568         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1569     ';
1570     my $sth = $dbh->prepare($query);
1571     $sth->execute(@biblionumbers);
1572
1573     my %itemnumbers_of;
1574
1575     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1576         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1577     }
1578
1579     return \%itemnumbers_of;
1580 }
1581
1582 =head2 get_hostitemnumbers_of
1583
1584   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1585
1586 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1587
1588 Return a reference on a hash where key is a biblionumber and values are
1589 references on array of itemnumbers.
1590
1591 =cut
1592
1593
1594 sub get_hostitemnumbers_of {
1595         my ($biblionumber) = @_;
1596         my $marcrecord = GetMarcBiblio($biblionumber);
1597         my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1598         
1599         my $marcflavor = C4::Context->preference('marcflavour');
1600         if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1601         $tag='773';
1602         $biblio_s='0';
1603         $item_s='9';
1604     } elsif ($marcflavor eq 'UNIMARC') {
1605         $tag='461';
1606         $biblio_s='0';
1607         $item_s='9';
1608     }
1609
1610     foreach my $hostfield ( $marcrecord->field($tag) ) {
1611         my $hostbiblionumber = $hostfield->subfield($biblio_s);
1612         my $linkeditemnumber = $hostfield->subfield($item_s);
1613         my @itemnumbers;
1614         if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1615         {
1616             @itemnumbers = @$itemnumbers;
1617         }
1618         foreach my $itemnumber (@itemnumbers){
1619             if ($itemnumber eq $linkeditemnumber){
1620                 push (@returnhostitemnumbers,$itemnumber);
1621                 last;
1622             }
1623         }
1624     }
1625     return @returnhostitemnumbers;
1626 }
1627
1628
1629 =head2 GetItemnumberFromBarcode
1630
1631   $result = GetItemnumberFromBarcode($barcode);
1632
1633 =cut
1634
1635 sub GetItemnumberFromBarcode {
1636     my ($barcode) = @_;
1637     my $dbh = C4::Context->dbh;
1638
1639     my $rq =
1640       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1641     $rq->execute($barcode);
1642     my ($result) = $rq->fetchrow;
1643     return ($result);
1644 }
1645
1646 =head2 GetBarcodeFromItemnumber
1647
1648   $result = GetBarcodeFromItemnumber($itemnumber);
1649
1650 =cut
1651
1652 sub GetBarcodeFromItemnumber {
1653     my ($itemnumber) = @_;
1654     my $dbh = C4::Context->dbh;
1655
1656     my $rq =
1657       $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1658     $rq->execute($itemnumber);
1659     my ($result) = $rq->fetchrow;
1660     return ($result);
1661 }
1662
1663 =head2 GetHiddenItemnumbers
1664
1665     my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
1666
1667 Given a list of items it checks which should be hidden from the OPAC given
1668 the current configuration. Returns a list of itemnumbers corresponding to
1669 those that should be hidden.
1670
1671 =cut
1672
1673 sub GetHiddenItemnumbers {
1674     my (@items) = @_;
1675     my @resultitems;
1676
1677     my $yaml = C4::Context->preference('OpacHiddenItems');
1678     return () if (! $yaml =~ /\S/ );
1679     $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1680     my $hidingrules;
1681     eval {
1682         $hidingrules = YAML::Load($yaml);
1683     };
1684     if ($@) {
1685         warn "Unable to parse OpacHiddenItems syspref : $@";
1686         return ();
1687     }
1688     my $dbh = C4::Context->dbh;
1689
1690     # For each item
1691     foreach my $item (@items) {
1692
1693         # We check each rule
1694         foreach my $field (keys %$hidingrules) {
1695             my $val;
1696             if (exists $item->{$field}) {
1697                 $val = $item->{$field};
1698             }
1699             else {
1700                 my $query = "SELECT $field from items where itemnumber = ?";
1701                 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1702             }
1703             $val = '' unless defined $val;
1704
1705             # If the results matches the values in the yaml file
1706             if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1707
1708                 # We add the itemnumber to the list
1709                 push @resultitems, $item->{'itemnumber'};
1710
1711                 # If at least one rule matched for an item, no need to test the others
1712                 last;
1713             }
1714         }
1715     }
1716     return @resultitems;
1717 }
1718
1719 =head3 get_item_authorised_values
1720
1721 find the types and values for all authorised values assigned to this item.
1722
1723 parameters: itemnumber
1724
1725 returns: a hashref malling the authorised value to the value set for this itemnumber
1726
1727     $authorised_values = {
1728              'CCODE'      => undef,
1729              'DAMAGED'    => '0',
1730              'LOC'        => '3',
1731              'LOST'       => '0'
1732              'NOT_LOAN'   => '0',
1733              'RESTRICTED' => undef,
1734              'STACK'      => undef,
1735              'WITHDRAWN'  => '0',
1736              'branches'   => 'CPL',
1737              'cn_source'  => undef,
1738              'itemtypes'  => 'SER',
1739            };
1740
1741 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1742
1743 =cut
1744
1745 sub get_item_authorised_values {
1746     my $itemnumber = shift;
1747
1748     # assume that these entries in the authorised_value table are item level.
1749     my $query = q(SELECT distinct authorised_value, kohafield
1750                     FROM marc_subfield_structure
1751                     WHERE kohafield like 'item%'
1752                       AND authorised_value != '' );
1753
1754     my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1755     my $iteminfo = GetItem( $itemnumber );
1756     # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1757     my $return;
1758     foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1759         my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1760         $field =~ s/^items\.//;
1761         if ( exists $iteminfo->{ $field } ) {
1762             $return->{ $this_authorised_value } = $iteminfo->{ $field };
1763         }
1764     }
1765     # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1766     return $return;
1767 }
1768
1769 =head3 get_authorised_value_images
1770
1771 find a list of icons that are appropriate for display based on the
1772 authorised values for a biblio.
1773
1774 parameters: listref of authorised values, such as comes from
1775 get_item_authorised_values or
1776 from C4::Biblio::get_biblio_authorised_values
1777
1778 returns: listref of hashrefs for each image. Each hashref looks like this:
1779
1780       { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1781         label    => '',
1782         category => '',
1783         value    => '', }
1784
1785 Notes: Currently, I put on the full path to the images on the staff
1786 side. This should either be configurable or not done at all. Since I
1787 have to deal with 'intranet' or 'opac' in
1788 get_biblio_authorised_values, perhaps I should be passing it in.
1789
1790 =cut
1791
1792 sub get_authorised_value_images {
1793     my $authorised_values = shift;
1794
1795     my @imagelist;
1796
1797     my $authorised_value_list = GetAuthorisedValues();
1798     # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1799     foreach my $this_authorised_value ( @$authorised_value_list ) {
1800         if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1801              && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1802             # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1803             if ( defined $this_authorised_value->{'imageurl'} ) {
1804                 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1805                                    label    => $this_authorised_value->{'lib'},
1806                                    category => $this_authorised_value->{'category'},
1807                                    value    => $this_authorised_value->{'authorised_value'}, };
1808             }
1809         }
1810     }
1811
1812     # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1813     return \@imagelist;
1814
1815 }
1816
1817 =head1 LIMITED USE FUNCTIONS
1818
1819 The following functions, while part of the public API,
1820 are not exported.  This is generally because they are
1821 meant to be used by only one script for a specific
1822 purpose, and should not be used in any other context
1823 without careful thought.
1824
1825 =cut
1826
1827 =head2 GetMarcItem
1828
1829   my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1830
1831 Returns MARC::Record of the item passed in parameter.
1832 This function is meant for use only in C<cataloguing/additem.pl>,
1833 where it is needed to support that script's MARC-like
1834 editor.
1835
1836 =cut
1837
1838 sub GetMarcItem {
1839     my ( $biblionumber, $itemnumber ) = @_;
1840
1841     # GetMarcItem has been revised so that it does the following:
1842     #  1. Gets the item information from the items table.
1843     #  2. Converts it to a MARC field for storage in the bib record.
1844     #
1845     # The previous behavior was:
1846     #  1. Get the bib record.
1847     #  2. Return the MARC tag corresponding to the item record.
1848     #
1849     # The difference is that one treats the items row as authoritative,
1850     # while the other treats the MARC representation as authoritative
1851     # under certain circumstances.
1852
1853     my $itemrecord = GetItem($itemnumber);
1854
1855     # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1856     # Also, don't emit a subfield if the underlying field is blank.
1857
1858     
1859     return Item2Marc($itemrecord,$biblionumber);
1860
1861 }
1862 sub Item2Marc {
1863         my ($itemrecord,$biblionumber)=@_;
1864     my $mungeditem = { 
1865         map {  
1866             defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  
1867         } keys %{ $itemrecord } 
1868     };
1869     my $itemmarc = TransformKohaToMarc($mungeditem);
1870     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1871
1872     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1873     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1874                 foreach my $field ($itemmarc->field($itemtag)){
1875             $field->add_subfields(@$unlinked_item_subfields);
1876         }
1877     }
1878         return $itemmarc;
1879 }
1880
1881 =head1 PRIVATE FUNCTIONS AND VARIABLES
1882
1883 The following functions are not meant to be called
1884 directly, but are documented in order to explain
1885 the inner workings of C<C4::Items>.
1886
1887 =cut
1888
1889 =head2 %derived_columns
1890
1891 This hash keeps track of item columns that
1892 are strictly derived from other columns in
1893 the item record and are not meant to be set
1894 independently.
1895
1896 Each key in the hash should be the name of a
1897 column (as named by TransformMarcToKoha).  Each
1898 value should be hashref whose keys are the
1899 columns on which the derived column depends.  The
1900 hashref should also contain a 'BUILDER' key
1901 that is a reference to a sub that calculates
1902 the derived value.
1903
1904 =cut
1905
1906 my %derived_columns = (
1907     'items.cn_sort' => {
1908         'itemcallnumber' => 1,
1909         'items.cn_source' => 1,
1910         'BUILDER' => \&_calc_items_cn_sort,
1911     }
1912 );
1913
1914 =head2 _set_derived_columns_for_add 
1915
1916   _set_derived_column_for_add($item);
1917
1918 Given an item hash representing a new item to be added,
1919 calculate any derived columns.  Currently the only
1920 such column is C<items.cn_sort>.
1921
1922 =cut
1923
1924 sub _set_derived_columns_for_add {
1925     my $item = shift;
1926
1927     foreach my $column (keys %derived_columns) {
1928         my $builder = $derived_columns{$column}->{'BUILDER'};
1929         my $source_values = {};
1930         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1931             next if $source_column eq 'BUILDER';
1932             $source_values->{$source_column} = $item->{$source_column};
1933         }
1934         $builder->($item, $source_values);
1935     }
1936 }
1937
1938 =head2 _set_derived_columns_for_mod 
1939
1940   _set_derived_column_for_mod($item);
1941
1942 Given an item hash representing a new item to be modified.
1943 calculate any derived columns.  Currently the only
1944 such column is C<items.cn_sort>.
1945
1946 This routine differs from C<_set_derived_columns_for_add>
1947 in that it needs to handle partial item records.  In other
1948 words, the caller of C<ModItem> may have supplied only one
1949 or two columns to be changed, so this function needs to
1950 determine whether any of the columns to be changed affect
1951 any of the derived columns.  Also, if a derived column
1952 depends on more than one column, but the caller is not
1953 changing all of then, this routine retrieves the unchanged
1954 values from the database in order to ensure a correct
1955 calculation.
1956
1957 =cut
1958
1959 sub _set_derived_columns_for_mod {
1960     my $item = shift;
1961
1962     foreach my $column (keys %derived_columns) {
1963         my $builder = $derived_columns{$column}->{'BUILDER'};
1964         my $source_values = {};
1965         my %missing_sources = ();
1966         my $must_recalc = 0;
1967         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1968             next if $source_column eq 'BUILDER';
1969             if (exists $item->{$source_column}) {
1970                 $must_recalc = 1;
1971                 $source_values->{$source_column} = $item->{$source_column};
1972             } else {
1973                 $missing_sources{$source_column} = 1;
1974             }
1975         }
1976         if ($must_recalc) {
1977             foreach my $source_column (keys %missing_sources) {
1978                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1979             }
1980             $builder->($item, $source_values);
1981         }
1982     }
1983 }
1984
1985 =head2 _do_column_fixes_for_mod
1986
1987   _do_column_fixes_for_mod($item);
1988
1989 Given an item hashref containing one or more
1990 columns to modify, fix up certain values.
1991 Specifically, set to 0 any passed value
1992 of C<notforloan>, C<damaged>, C<itemlost>, or
1993 C<withdrawn> that is either undefined or
1994 contains the empty string.
1995
1996 =cut
1997
1998 sub _do_column_fixes_for_mod {
1999     my $item = shift;
2000
2001     if (exists $item->{'notforloan'} and
2002         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
2003         $item->{'notforloan'} = 0;
2004     }
2005     if (exists $item->{'damaged'} and
2006         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
2007         $item->{'damaged'} = 0;
2008     }
2009     if (exists $item->{'itemlost'} and
2010         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
2011         $item->{'itemlost'} = 0;
2012     }
2013     if (exists $item->{'withdrawn'} and
2014         (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
2015         $item->{'withdrawn'} = 0;
2016     }
2017     if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
2018         $item->{'permanent_location'} = $item->{'location'};
2019     }
2020     if (exists $item->{'timestamp'}) {
2021         delete $item->{'timestamp'};
2022     }
2023 }
2024
2025 =head2 _get_single_item_column
2026
2027   _get_single_item_column($column, $itemnumber);
2028
2029 Retrieves the value of a single column from an C<items>
2030 row specified by C<$itemnumber>.
2031
2032 =cut
2033
2034 sub _get_single_item_column {
2035     my $column = shift;
2036     my $itemnumber = shift;
2037     
2038     my $dbh = C4::Context->dbh;
2039     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2040     $sth->execute($itemnumber);
2041     my ($value) = $sth->fetchrow();
2042     return $value; 
2043 }
2044
2045 =head2 _calc_items_cn_sort
2046
2047   _calc_items_cn_sort($item, $source_values);
2048
2049 Helper routine to calculate C<items.cn_sort>.
2050
2051 =cut
2052
2053 sub _calc_items_cn_sort {
2054     my $item = shift;
2055     my $source_values = shift;
2056
2057     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2058 }
2059
2060 =head2 _set_defaults_for_add 
2061
2062   _set_defaults_for_add($item_hash);
2063
2064 Given an item hash representing an item to be added, set
2065 correct default values for columns whose default value
2066 is not handled by the DBMS.  This includes the following
2067 columns:
2068
2069 =over 2
2070
2071 =item * 
2072
2073 C<items.dateaccessioned>
2074
2075 =item *
2076
2077 C<items.notforloan>
2078
2079 =item *
2080
2081 C<items.damaged>
2082
2083 =item *
2084
2085 C<items.itemlost>
2086
2087 =item *
2088
2089 C<items.withdrawn>
2090
2091 =back
2092
2093 =cut
2094
2095 sub _set_defaults_for_add {
2096     my $item = shift;
2097     $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2098     $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
2099 }
2100
2101 =head2 _koha_new_item
2102
2103   my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2104
2105 Perform the actual insert into the C<items> table.
2106
2107 =cut
2108
2109 sub _koha_new_item {
2110     my ( $item, $barcode ) = @_;
2111     my $dbh=C4::Context->dbh;  
2112     my $error;
2113     my $query =
2114            "INSERT INTO items SET
2115             biblionumber        = ?,
2116             biblioitemnumber    = ?,
2117             barcode             = ?,
2118             dateaccessioned     = ?,
2119             booksellerid        = ?,
2120             homebranch          = ?,
2121             price               = ?,
2122             replacementprice    = ?,
2123             replacementpricedate = ?,
2124             datelastborrowed    = ?,
2125             datelastseen        = ?,
2126             stack               = ?,
2127             notforloan          = ?,
2128             damaged             = ?,
2129             itemlost            = ?,
2130             withdrawn            = ?,
2131             itemcallnumber      = ?,
2132             coded_location_qualifier = ?,
2133             restricted          = ?,
2134             itemnotes           = ?,
2135             holdingbranch       = ?,
2136             paidfor             = ?,
2137             location            = ?,
2138             permanent_location            = ?,
2139             onloan              = ?,
2140             issues              = ?,
2141             renewals            = ?,
2142             reserves            = ?,
2143             cn_source           = ?,
2144             cn_sort             = ?,
2145             ccode               = ?,
2146             itype               = ?,
2147             materials           = ?,
2148             uri = ?,
2149             enumchron           = ?,
2150             more_subfields_xml  = ?,
2151             copynumber          = ?,
2152             stocknumber         = ?
2153           ";
2154     my $sth = $dbh->prepare($query);
2155     my $today = C4::Dates->today('iso');
2156    $sth->execute(
2157             $item->{'biblionumber'},
2158             $item->{'biblioitemnumber'},
2159             $barcode,
2160             $item->{'dateaccessioned'},
2161             $item->{'booksellerid'},
2162             $item->{'homebranch'},
2163             $item->{'price'},
2164             $item->{'replacementprice'},
2165             $item->{'replacementpricedate'} || $today,
2166             $item->{datelastborrowed},
2167             $item->{datelastseen} || $today,
2168             $item->{stack},
2169             $item->{'notforloan'},
2170             $item->{'damaged'},
2171             $item->{'itemlost'},
2172             $item->{'withdrawn'},
2173             $item->{'itemcallnumber'},
2174             $item->{'coded_location_qualifier'},
2175             $item->{'restricted'},
2176             $item->{'itemnotes'},
2177             $item->{'holdingbranch'},
2178             $item->{'paidfor'},
2179             $item->{'location'},
2180             $item->{'permanent_location'},
2181             $item->{'onloan'},
2182             $item->{'issues'},
2183             $item->{'renewals'},
2184             $item->{'reserves'},
2185             $item->{'items.cn_source'},
2186             $item->{'items.cn_sort'},
2187             $item->{'ccode'},
2188             $item->{'itype'},
2189             $item->{'materials'},
2190             $item->{'uri'},
2191             $item->{'enumchron'},
2192             $item->{'more_subfields_xml'},
2193             $item->{'copynumber'},
2194             $item->{'stocknumber'},
2195     );
2196
2197     my $itemnumber;
2198     if ( defined $sth->errstr ) {
2199         $error.="ERROR in _koha_new_item $query".$sth->errstr;
2200     }
2201     else {
2202         $itemnumber = $dbh->{'mysql_insertid'};
2203     }
2204
2205     return ( $itemnumber, $error );
2206 }
2207
2208 =head2 MoveItemFromBiblio
2209
2210   MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2211
2212 Moves an item from a biblio to another
2213
2214 Returns undef if the move failed or the biblionumber of the destination record otherwise
2215
2216 =cut
2217
2218 sub MoveItemFromBiblio {
2219     my ($itemnumber, $frombiblio, $tobiblio) = @_;
2220     my $dbh = C4::Context->dbh;
2221     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2222     $sth->execute( $tobiblio );
2223     my ( $tobiblioitem ) = $sth->fetchrow();
2224     $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2225     my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2226     if ($return == 1) {
2227         ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
2228         ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
2229             # Checking if the item we want to move is in an order 
2230         require C4::Acquisition;
2231         my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2232             if ($order) {
2233                     # Replacing the biblionumber within the order if necessary
2234                     $order->{'biblionumber'} = $tobiblio;
2235                 C4::Acquisition::ModOrder($order);
2236             }
2237         return $tobiblio;
2238         }
2239     return;
2240 }
2241
2242 =head2 DelItemCheck
2243
2244    DelItemCheck($dbh, $biblionumber, $itemnumber);
2245
2246 Exported function (core API) for deleting an item record in Koha if there no current issue.
2247
2248 =cut
2249
2250 sub DelItemCheck {
2251     my ( $dbh, $biblionumber, $itemnumber ) = @_;
2252     my $error;
2253
2254         my $countanalytics=GetAnalyticsCount($itemnumber);
2255
2256
2257     # check that there is no issue on this item before deletion.
2258     my $sth = $dbh->prepare(q{
2259         SELECT COUNT(*) FROM issues
2260         WHERE itemnumber = ?
2261     });
2262     $sth->execute($itemnumber);
2263     my ($onloan) = $sth->fetchrow;
2264
2265     my $item = GetItem($itemnumber);
2266
2267     if ($onloan){
2268         $error = "book_on_loan" 
2269     }
2270     elsif ( !C4::Context->IsSuperLibrarian()
2271         and C4::Context->preference("IndependentBranches")
2272         and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
2273     {
2274         $error = "not_same_branch";
2275     }
2276         else{
2277         # check it doesnt have a waiting reserve
2278         $sth = $dbh->prepare(q{
2279             SELECT COUNT(*) FROM reserves
2280             WHERE (found = 'W' OR found = 'T')
2281             AND itemnumber = ?
2282         });
2283         $sth->execute($itemnumber);
2284         my ($reserve) = $sth->fetchrow;
2285         if ($reserve){
2286             $error = "book_reserved";
2287         } elsif ($countanalytics > 0){
2288                 $error = "linked_analytics";
2289         } else {
2290             DelItem($biblionumber, $itemnumber);
2291             return 1;
2292         }
2293     }
2294     return $error;
2295 }
2296
2297 =head2 _koha_modify_item
2298
2299   my ($itemnumber,$error) =_koha_modify_item( $item );
2300
2301 Perform the actual update of the C<items> row.  Note that this
2302 routine accepts a hashref specifying the columns to update.
2303
2304 =cut
2305
2306 sub _koha_modify_item {
2307     my ( $item ) = @_;
2308     my $dbh=C4::Context->dbh;  
2309     my $error;
2310
2311     my $query = "UPDATE items SET ";
2312     my @bind;
2313     for my $key ( keys %$item ) {
2314         next if ( $key eq 'itemnumber' );
2315         $query.="$key=?,";
2316         push @bind, $item->{$key};
2317     }
2318     $query =~ s/,$//;
2319     $query .= " WHERE itemnumber=?";
2320     push @bind, $item->{'itemnumber'};
2321     my $sth = $dbh->prepare($query);
2322     $sth->execute(@bind);
2323     if ( $sth->err ) {
2324         $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
2325         warn $error;
2326     }
2327     return ($item->{'itemnumber'},$error);
2328 }
2329
2330 =head2 _koha_delete_item
2331
2332   _koha_delete_item( $itemnum );
2333
2334 Internal function to delete an item record from the koha tables
2335
2336 =cut
2337
2338 sub _koha_delete_item {
2339     my ( $itemnum ) = @_;
2340
2341     my $dbh = C4::Context->dbh;
2342     # save the deleted item to deleteditems table
2343     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2344     $sth->execute($itemnum);
2345     my $data = $sth->fetchrow_hashref();
2346     my $query = "INSERT INTO deleteditems SET ";
2347     my @bind  = ();
2348     foreach my $key ( keys %$data ) {
2349         next if ( $key eq 'timestamp' ); # timestamp will be set by db
2350         $query .= "$key = ?,";
2351         push( @bind, $data->{$key} );
2352     }
2353     $query =~ s/\,$//;
2354     $sth = $dbh->prepare($query);
2355     $sth->execute(@bind);
2356
2357     # delete from items table
2358     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2359     $sth->execute($itemnum);
2360     return;
2361 }
2362
2363 =head2 _marc_from_item_hash
2364
2365   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2366
2367 Given an item hash representing a complete item record,
2368 create a C<MARC::Record> object containing an embedded
2369 tag representing that item.
2370
2371 The third, optional parameter C<$unlinked_item_subfields> is
2372 an arrayref of subfields (not mapped to C<items> fields per the
2373 framework) to be added to the MARC representation
2374 of the item.
2375
2376 =cut
2377
2378 sub _marc_from_item_hash {
2379     my $item = shift;
2380     my $frameworkcode = shift;
2381     my $unlinked_item_subfields;
2382     if (@_) {
2383         $unlinked_item_subfields = shift;
2384     }
2385    
2386     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2387     # Also, don't emit a subfield if the underlying field is blank.
2388     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
2389                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
2390                                 : ()  } keys %{ $item } }; 
2391
2392     my $item_marc = MARC::Record->new();
2393     foreach my $item_field ( keys %{$mungeditem} ) {
2394         my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2395         next unless defined $tag and defined $subfield;    # skip if not mapped to MARC field
2396         my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2397         foreach my $value (@values){
2398             if ( my $field = $item_marc->field($tag) ) {
2399                     $field->add_subfields( $subfield => $value );
2400             } else {
2401                 my $add_subfields = [];
2402                 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2403                     $add_subfields = $unlinked_item_subfields;
2404             }
2405             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2406             }
2407         }
2408     }
2409
2410     return $item_marc;
2411 }
2412
2413 =head2 _repack_item_errors
2414
2415 Add an error message hash generated by C<CheckItemPreSave>
2416 to a list of errors.
2417
2418 =cut
2419
2420 sub _repack_item_errors {
2421     my $item_sequence_num = shift;
2422     my $item_ref = shift;
2423     my $error_ref = shift;
2424
2425     my @repacked_errors = ();
2426
2427     foreach my $error_code (sort keys %{ $error_ref }) {
2428         my $repacked_error = {};
2429         $repacked_error->{'item_sequence'} = $item_sequence_num;
2430         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2431         $repacked_error->{'error_code'} = $error_code;
2432         $repacked_error->{'error_information'} = $error_ref->{$error_code};
2433         push @repacked_errors, $repacked_error;
2434     } 
2435
2436     return @repacked_errors;
2437 }
2438
2439 =head2 _get_unlinked_item_subfields
2440
2441   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2442
2443 =cut
2444
2445 sub _get_unlinked_item_subfields {
2446     my $original_item_marc = shift;
2447     my $frameworkcode = shift;
2448
2449     my $marcstructure = GetMarcStructure(1, $frameworkcode);
2450
2451     # assume that this record has only one field, and that that
2452     # field contains only the item information
2453     my $subfields = [];
2454     my @fields = $original_item_marc->fields();
2455     if ($#fields > -1) {
2456         my $field = $fields[0];
2457             my $tag = $field->tag();
2458         foreach my $subfield ($field->subfields()) {
2459             if (defined $subfield->[1] and
2460                 $subfield->[1] ne '' and
2461                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2462                 push @$subfields, $subfield->[0] => $subfield->[1];
2463             }
2464         }
2465     }
2466     return $subfields;
2467 }
2468
2469 =head2 _get_unlinked_subfields_xml
2470
2471   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2472
2473 =cut
2474
2475 sub _get_unlinked_subfields_xml {
2476     my $unlinked_item_subfields = shift;
2477
2478     my $xml;
2479     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2480         my $marc = MARC::Record->new();
2481         # use of tag 999 is arbitrary, and doesn't need to match the item tag
2482         # used in the framework
2483         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2484         $marc->encoding("UTF-8");    
2485         $xml = $marc->as_xml("USMARC");
2486     }
2487
2488     return $xml;
2489 }
2490
2491 =head2 _parse_unlinked_item_subfields_from_xml
2492
2493   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2494
2495 =cut
2496
2497 sub  _parse_unlinked_item_subfields_from_xml {
2498     my $xml = shift;
2499     require C4::Charset;
2500     return unless defined $xml and $xml ne "";
2501     my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2502     my $unlinked_subfields = [];
2503     my @fields = $marc->fields();
2504     if ($#fields > -1) {
2505         foreach my $subfield ($fields[0]->subfields()) {
2506             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2507         }
2508     }
2509     return $unlinked_subfields;
2510 }
2511
2512 =head2 GetAnalyticsCount
2513
2514   $count= &GetAnalyticsCount($itemnumber)
2515
2516 counts Usage of itemnumber in Analytical bibliorecords. 
2517
2518 =cut
2519
2520 sub GetAnalyticsCount {
2521     my ($itemnumber) = @_;
2522     require C4::Search;
2523
2524     ### ZOOM search here
2525     my $query;
2526     $query= "hi=".$itemnumber;
2527             my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2528     return ($result);
2529 }
2530
2531 =head2 GetItemHolds
2532
2533 =over 4
2534 $holds = &GetItemHolds($biblionumber, $itemnumber);
2535
2536 =back
2537
2538 This function return the count of holds with $biblionumber and $itemnumber
2539
2540 =cut
2541
2542 sub GetItemHolds {
2543     my ($biblionumber, $itemnumber) = @_;
2544     my $holds;
2545     my $dbh            = C4::Context->dbh;
2546     my $query          = "SELECT count(*)
2547         FROM  reserves
2548         WHERE biblionumber=? AND itemnumber=?";
2549     my $sth = $dbh->prepare($query);
2550     $sth->execute($biblionumber, $itemnumber);
2551     $holds = $sth->fetchrow;
2552     return $holds;
2553 }
2554
2555 # Return the list of the column names of items table
2556 sub _get_items_columns {
2557     my $dbh = C4::Context->dbh;
2558     my $sth = $dbh->column_info(undef, undef, 'items', '%');
2559     $sth->execute;
2560     my $results = $sth->fetchall_hashref('COLUMN_NAME');
2561     return keys %$results;
2562 }
2563
2564 =head2 SearchItems
2565
2566     my $items = SearchItems($field, $value);
2567
2568 SearchItems will search for items on a specific given field.
2569 For instance you can search all items with a specific stocknumber like this:
2570
2571     my $items = SearchItems('stocknumber', $stocknumber);
2572
2573 =cut
2574
2575 sub SearchItems {
2576     my ($field, $value) = @_;
2577
2578     my $dbh = C4::Context->dbh;
2579     my @columns = _get_items_columns;
2580     my $results = [];
2581     if(0 < grep /^$field$/, @columns) {
2582         my $query = "SELECT $field FROM items WHERE $field = ?";
2583         my $sth = $dbh->prepare( $query );
2584         $sth->execute( $value );
2585         $results = $sth->fetchall_arrayref({});
2586     }
2587     return $results;
2588 }
2589
2590
2591 =head1  OTHER FUNCTIONS
2592
2593 =head2 _find_value
2594
2595   ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2596
2597 Find the given $subfield in the given $tag in the given
2598 MARC::Record $record.  If the subfield is found, returns
2599 the (indicators, value) pair; otherwise, (undef, undef) is
2600 returned.
2601
2602 PROPOSITION :
2603 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2604 I suggest we export it from this module.
2605
2606 =cut
2607
2608 sub _find_value {
2609     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2610     my @result;
2611     my $indicator;
2612     if ( $tagfield < 10 ) {
2613         if ( $record->field($tagfield) ) {
2614             push @result, $record->field($tagfield)->data();
2615         } else {
2616             push @result, "";
2617         }
2618     } else {
2619         foreach my $field ( $record->field($tagfield) ) {
2620             my @subfields = $field->subfields();
2621             foreach my $subfield (@subfields) {
2622                 if ( @$subfield[0] eq $insubfield ) {
2623                     push @result, @$subfield[1];
2624                     $indicator = $field->indicator(1) . $field->indicator(2);
2625                 }
2626             }
2627         }
2628     }
2629     return ( $indicator, @result );
2630 }
2631
2632
2633 =head2 PrepareItemrecordDisplay
2634
2635   PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2636
2637 Returns a hash with all the fields for Display a given item data in a template
2638
2639 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2640
2641 =cut
2642
2643 sub PrepareItemrecordDisplay {
2644
2645     my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2646
2647     my $dbh = C4::Context->dbh;
2648     $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2649     my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2650     my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2651
2652     # return nothing if we don't have found an existing framework.
2653     return q{} unless $tagslib;
2654     my $itemrecord;
2655     if ($itemnum) {
2656         $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2657     }
2658     my @loop_data;
2659
2660     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2661     my $query = qq{
2662         SELECT authorised_value,lib FROM authorised_values
2663     };
2664     $query .= qq{
2665         LEFT JOIN authorised_values_branches ON ( id = av_id )
2666     } if $branch_limit;
2667     $query .= qq{
2668         WHERE category = ?
2669     };
2670     $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2671     $query .= qq{ ORDER BY lib};
2672     my $authorised_values_sth = $dbh->prepare( $query );
2673     foreach my $tag ( sort keys %{$tagslib} ) {
2674         my $previous_tag = '';
2675         if ( $tag ne '' ) {
2676
2677             # loop through each subfield
2678             my $cntsubf;
2679             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2680                 next if ( subfield_is_koha_internal_p($subfield) );
2681                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2682                 my %subfield_data;
2683                 $subfield_data{tag}           = $tag;
2684                 $subfield_data{subfield}      = $subfield;
2685                 $subfield_data{countsubfield} = $cntsubf++;
2686                 $subfield_data{kohafield}     = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2687                 $subfield_data{id}            = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2688
2689                 #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2690                 $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
2691                 $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
2692                 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2693                 $subfield_data{hidden}     = "display:none"
2694                   if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
2695                     || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
2696                 my ( $x, $defaultvalue );
2697                 if ($itemrecord) {
2698                     ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2699                 }
2700                 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2701                 if ( !defined $defaultvalue ) {
2702                     $defaultvalue = q||;
2703                 } else {
2704                     $defaultvalue =~ s/"/&quot;/g;
2705                 }
2706
2707                 # search for itemcallnumber if applicable
2708                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2709                     && C4::Context->preference('itemcallnumber') ) {
2710                     my $CNtag      = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2711                     my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2712                     if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2713                         $defaultvalue = $field->subfield($CNsubfield);
2714                     }
2715                 }
2716                 if (   $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2717                     && $defaultvalues
2718                     && $defaultvalues->{'callnumber'} ) {
2719                     if( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ){
2720                         # if the item record exists, only use default value if the item has no callnumber
2721                         $defaultvalue = $defaultvalues->{callnumber};
2722                     } elsif ( !$itemrecord and $defaultvalues ) {
2723                         # if the item record *doesn't* exists, always use the default value
2724                         $defaultvalue = $defaultvalues->{callnumber};
2725                     }
2726                 }
2727                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2728                     && $defaultvalues
2729                     && $defaultvalues->{'branchcode'} ) {
2730                     if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2731                         $defaultvalue = $defaultvalues->{branchcode};
2732                     }
2733                 }
2734                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2735                     && $defaultvalues
2736                     && $defaultvalues->{'location'} ) {
2737
2738                     if ( $itemrecord and $defaultvalues and not $itemrecord->field($subfield) ) {
2739                         # if the item record exists, only use default value if the item has no locationr
2740                         $defaultvalue = $defaultvalues->{location};
2741                     } elsif ( !$itemrecord and $defaultvalues ) {
2742                         # if the item record *doesn't* exists, always use the default value
2743                         $defaultvalue = $defaultvalues->{location};
2744                     }
2745                 }
2746                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2747                     my @authorised_values;
2748                     my %authorised_lib;
2749
2750                     # builds list, depending on authorised value...
2751                     #---- branch
2752                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2753                         if (   ( C4::Context->preference("IndependentBranches") )
2754                             && !C4::Context->IsSuperLibrarian() ) {
2755                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2756                             $sth->execute( C4::Context->userenv->{branch} );
2757                             push @authorised_values, ""
2758                               unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2759                             while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2760                                 push @authorised_values, $branchcode;
2761                                 $authorised_lib{$branchcode} = $branchname;
2762                             }
2763                         } else {
2764                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2765                             $sth->execute;
2766                             push @authorised_values, ""
2767                               unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2768                             while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2769                                 push @authorised_values, $branchcode;
2770                                 $authorised_lib{$branchcode} = $branchname;
2771                             }
2772                         }
2773
2774                         $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2775                         if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2776                             $defaultvalue = $defaultvalues->{branchcode};
2777                         }
2778
2779                         #----- itemtypes
2780                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2781                         my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2782                         $sth->execute;
2783                         push @authorised_values, ""
2784                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2785                         while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2786                             push @authorised_values, $itemtype;
2787                             $authorised_lib{$itemtype} = $description;
2788                         }
2789                         #---- class_sources
2790                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2791                         push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2792
2793                         my $class_sources = GetClassSources();
2794                         my $default_source = C4::Context->preference("DefaultClassificationSource");
2795
2796                         foreach my $class_source (sort keys %$class_sources) {
2797                             next unless $class_sources->{$class_source}->{'used'} or
2798                                         ($class_source eq $default_source);
2799                             push @authorised_values, $class_source;
2800                             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2801                         }
2802
2803                         $defaultvalue = $default_source;
2804
2805                         #---- "true" authorised value
2806                     } else {
2807                         $authorised_values_sth->execute(
2808                             $tagslib->{$tag}->{$subfield}->{authorised_value},
2809                             $branch_limit ? $branch_limit : ()
2810                         );
2811                         push @authorised_values, ""
2812                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2813                         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2814                             push @authorised_values, $value;
2815                             $authorised_lib{$value} = $lib;
2816                         }
2817                     }
2818                     $subfield_data{marc_value} = CGI::scrolling_list(
2819                         -name     => 'field_value',
2820                         -values   => \@authorised_values,
2821                         -default  => "$defaultvalue",
2822                         -labels   => \%authorised_lib,
2823                         -size     => 1,
2824                         -tabindex => '',
2825                         -multiple => 0,
2826                     );
2827                 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2828                         # opening plugin
2829                         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2830                         if (do $plugin) {
2831                             my $extended_param = plugin_parameters( $dbh, undef, $tagslib, $subfield_data{id}, undef );
2832                             my ( $function_name, $javascript ) = plugin_javascript( $dbh, undef, $tagslib, $subfield_data{id}, undef );
2833                             $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
2834                             $subfield_data{marc_value} = qq[<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255"
2835                                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2836                                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2837                                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2838                                 $javascript];
2839                         } else {
2840                             warn "Plugin Failed: $plugin";
2841                             $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
2842                         }
2843                 }
2844                 elsif ( $tag eq '' ) {       # it's an hidden field
2845                     $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" />);
2846                 }
2847                 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
2848                     $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" />);
2849                 }
2850                 elsif ( length($defaultvalue) > 100
2851                             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2852                                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
2853                             or (C4::Context->preference("marcflavour") eq "MARC21"  and
2854                                   500 <= $tag && $tag < 600                     )
2855                           ) {
2856                     # oversize field (textarea)
2857                     $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");
2858                 } else {
2859                     $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2860                 }
2861                 push( @loop_data, \%subfield_data );
2862             }
2863         }
2864     }
2865     my $itemnumber;
2866     if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2867         $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2868     }
2869     return {
2870         'itemtagfield'    => $itemtagfield,
2871         'itemtagsubfield' => $itemtagsubfield,
2872         'itemnumber'      => $itemnumber,
2873         'iteminformation' => \@loop_data
2874     };
2875 }
2876
2877 1;