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