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