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