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