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