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