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