Merge remote-tracking branch 'origin/new/bug_6880'
[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 C4::Branch;
33 require C4::Reserves;
34 use C4::Charset;
35 use C4::Acquisition;
36 use List::MoreUtils qw/any/;
37 use Data::Dumper; # used as part of logging item record changes, not just for
38                   # debugging; so please don't remove this
39
40 use vars qw($VERSION @ISA @EXPORT);
41
42 BEGIN {
43     $VERSION = 3.01;
44
45         require Exporter;
46     @ISA = qw( Exporter );
47
48     # function exports
49     @EXPORT = qw(
50         GetItem
51         AddItemFromMarc
52         AddItem
53         AddItemBatchFromMarc
54         ModItemFromMarc
55                 Item2Marc
56         ModItem
57         ModDateLastSeen
58         ModItemTransfer
59         DelItem
60     
61         CheckItemPreSave
62     
63         GetItemStatus
64         GetItemLocation
65         GetLostItems
66         GetItemsForInventory
67         GetItemsCount
68         GetItemInfosOf
69         GetItemsByBiblioitemnumber
70         GetItemsInfo
71         GetItemsLocationInfo
72         GetHostItemsInfo
73         get_itemnumbers_of
74         get_hostitemnumbers_of
75         GetItemnumberFromBarcode
76         GetBarcodeFromItemnumber
77         GetHiddenItemnumbers
78                 DelItemCheck
79                 MoveItemFromBiblio 
80                 GetLatestAcquisitions
81         CartToShelf
82
83         GetAnalyticsCount
84         GetItemHolds
85     );
86 }
87
88 =head1 NAME
89
90 C4::Items - item management functions
91
92 =head1 DESCRIPTION
93
94 This module contains an API for manipulating item 
95 records in Koha, and is used by cataloguing, circulation,
96 acquisitions, and serials management.
97
98 A Koha item record is stored in two places: the
99 items table and embedded in a MARC tag in the XML
100 version of the associated bib record in C<biblioitems.marcxml>.
101 This is done to allow the item information to be readily
102 indexed (e.g., by Zebra), but means that each item
103 modification transaction must keep the items table
104 and the MARC XML in sync at all times.
105
106 Consequently, all code that creates, modifies, or deletes
107 item records B<must> use an appropriate function from 
108 C<C4::Items>.  If no existing function is suitable, it is
109 better to add one to C<C4::Items> than to use add
110 one-off SQL statements to add or modify items.
111
112 The items table will be considered authoritative.  In other
113 words, if there is ever a discrepancy between the items
114 table and the MARC XML, the items table should be considered
115 accurate.
116
117 =head1 HISTORICAL NOTE
118
119 Most of the functions in C<C4::Items> were originally in
120 the C<C4::Biblio> module.
121
122 =head1 CORE EXPORTED FUNCTIONS
123
124 The following functions are meant for use by users
125 of C<C4::Items>
126
127 =cut
128
129 =head2 GetItem
130
131   $item = GetItem($itemnumber,$barcode,$serial);
132
133 Return item information, for a given itemnumber or barcode.
134 The return value is a hashref mapping item column
135 names to values.  If C<$serial> is true, include serial publication data.
136
137 =cut
138
139 sub GetItem {
140     my ($itemnumber,$barcode, $serial) = @_;
141     my $dbh = C4::Context->dbh;
142         my $data;
143     if ($itemnumber) {
144         my $sth = $dbh->prepare("
145             SELECT * FROM items 
146             WHERE itemnumber = ?");
147         $sth->execute($itemnumber);
148         $data = $sth->fetchrow_hashref;
149     } else {
150         my $sth = $dbh->prepare("
151             SELECT * FROM items 
152             WHERE barcode = ?"
153             );
154         $sth->execute($barcode);                
155         $data = $sth->fetchrow_hashref;
156     }
157     if ( $serial) {      
158     my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
159         $ssth->execute($data->{'itemnumber'}) ;
160         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
161     }
162         #if we don't have an items.itype, use biblioitems.itemtype.
163         if( ! $data->{'itype'} ) {
164                 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
165                 $sth->execute($data->{'biblionumber'});
166                 ($data->{'itype'}) = $sth->fetchrow_array;
167         }
168     return $data;
169 }    # sub GetItem
170
171 =head2 CartToShelf
172
173   CartToShelf($itemnumber);
174
175 Set the current shelving location of the item record
176 to its stored permanent shelving location.  This is
177 primarily used to indicate when an item whose current
178 location is a special processing ('PROC') or shelving cart
179 ('CART') location is back in the stacks.
180
181 =cut
182
183 sub CartToShelf {
184     my ( $itemnumber ) = @_;
185
186     unless ( $itemnumber ) {
187         croak "FAILED CartToShelf() - no itemnumber supplied";
188     }
189
190     my $item = GetItem($itemnumber);
191     $item->{location} = $item->{permanent_location};
192     ModItem($item, undef, $itemnumber);
193 }
194
195 =head2 AddItemFromMarc
196
197   my ($biblionumber, $biblioitemnumber, $itemnumber) 
198       = AddItemFromMarc($source_item_marc, $biblionumber);
199
200 Given a MARC::Record object containing an embedded item
201 record and a biblionumber, create a new item record.
202
203 =cut
204
205 sub AddItemFromMarc {
206     my ( $source_item_marc, $biblionumber ) = @_;
207     my $dbh = C4::Context->dbh;
208
209     # parse item hash from MARC
210     my $frameworkcode = GetFrameworkCode( $biblionumber );
211         my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
212         
213         my $localitemmarc=MARC::Record->new;
214         $localitemmarc->append_fields($source_item_marc->field($itemtag));
215     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
216     my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
217     return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
218 }
219
220 =head2 AddItem
221
222   my ($biblionumber, $biblioitemnumber, $itemnumber) 
223       = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
224
225 Given a hash containing item column names as keys,
226 create a new Koha item record.
227
228 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
229 do not need to be supplied for general use; they exist
230 simply to allow them to be picked up from AddItemFromMarc.
231
232 The final optional parameter, C<$unlinked_item_subfields>, contains
233 an arrayref containing subfields present in the original MARC
234 representation of the item (e.g., from the item editor) that are
235 not mapped to C<items> columns directly but should instead
236 be stored in C<items.more_subfields_xml> and included in 
237 the biblio items tag for display and indexing.
238
239 =cut
240
241 sub AddItem {
242     my $item = shift;
243     my $biblionumber = shift;
244
245     my $dbh           = @_ ? shift : C4::Context->dbh;
246     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
247     my $unlinked_item_subfields;  
248     if (@_) {
249         $unlinked_item_subfields = shift
250     };
251
252     # needs old biblionumber and biblioitemnumber
253     $item->{'biblionumber'} = $biblionumber;
254     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
255     $sth->execute( $item->{'biblionumber'} );
256     ($item->{'biblioitemnumber'}) = $sth->fetchrow;
257
258     _set_defaults_for_add($item);
259     _set_derived_columns_for_add($item);
260     $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
261     # FIXME - checks here
262     unless ( $item->{itype} ) {  # default to biblioitem.itemtype if no itype
263         my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
264         $itype_sth->execute( $item->{'biblionumber'} );
265         ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
266     }
267
268         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
269     $item->{'itemnumber'} = $itemnumber;
270
271     ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
272    
273     logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
274     
275     return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
276 }
277
278 =head2 AddItemBatchFromMarc
279
280   ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
281              $biblionumber, $biblioitemnumber, $frameworkcode);
282
283 Efficiently create item records from a MARC biblio record with
284 embedded item fields.  This routine is suitable for batch jobs.
285
286 This API assumes that the bib record has already been
287 saved to the C<biblio> and C<biblioitems> tables.  It does
288 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
289 are populated, but it will do so via a call to ModBibiloMarc.
290
291 The goal of this API is to have a similar effect to using AddBiblio
292 and AddItems in succession, but without inefficient repeated
293 parsing of the MARC XML bib record.
294
295 This function returns an arrayref of new itemsnumbers and an arrayref of item
296 errors encountered during the processing.  Each entry in the errors
297 list is a hashref containing the following keys:
298
299 =over
300
301 =item item_sequence
302
303 Sequence number of original item tag in the MARC record.
304
305 =item item_barcode
306
307 Item barcode, provide to assist in the construction of
308 useful error messages.
309
310 =item error_condition
311
312 Code representing the error condition.  Can be 'duplicate_barcode',
313 'invalid_homebranch', or 'invalid_holdingbranch'.
314
315 =item error_information
316
317 Additional information appropriate to the error condition.
318
319 =back
320
321 =cut
322
323 sub AddItemBatchFromMarc {
324     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
325     my $error;
326     my @itemnumbers = ();
327     my @errors = ();
328     my $dbh = C4::Context->dbh;
329
330     # loop through the item tags and start creating items
331     my @bad_item_fields = ();
332     my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
333     my $item_sequence_num = 0;
334     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
335         $item_sequence_num++;
336         # we take the item field and stick it into a new
337         # MARC record -- this is required so far because (FIXME)
338         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
339         # and there is no TransformMarcFieldToKoha
340         my $temp_item_marc = MARC::Record->new();
341         $temp_item_marc->append_fields($item_field);
342     
343         # add biblionumber and biblioitemnumber
344         my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
345         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
346         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
347         $item->{'biblionumber'} = $biblionumber;
348         $item->{'biblioitemnumber'} = $biblioitemnumber;
349
350         # check for duplicate barcode
351         my %item_errors = CheckItemPreSave($item);
352         if (%item_errors) {
353             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
354             push @bad_item_fields, $item_field;
355             next ITEMFIELD;
356         }
357
358         _set_defaults_for_add($item);
359         _set_derived_columns_for_add($item);
360         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
361         warn $error if $error;
362         push @itemnumbers, $itemnumber; # FIXME not checking error
363         $item->{'itemnumber'} = $itemnumber;
364
365         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
366
367         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
368         $item_field->replace_with($new_item_marc->field($itemtag));
369     }
370
371     # remove any MARC item fields for rejected items
372     foreach my $item_field (@bad_item_fields) {
373         $record->delete_field($item_field);
374     }
375
376     # update the MARC biblio
377  #   $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
378
379     return (\@itemnumbers, \@errors);
380 }
381
382 =head2 ModItemFromMarc
383
384   ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
385
386 This function updates an item record based on a supplied
387 C<MARC::Record> object containing an embedded item field.
388 This API is meant for the use of C<additem.pl>; for 
389 other purposes, C<ModItem> should be used.
390
391 This function uses the hash %default_values_for_mod_from_marc,
392 which contains default values for item fields to
393 apply when modifying an item.  This is needed beccause
394 if an item field's value is cleared, TransformMarcToKoha
395 does not include the column in the
396 hash that's passed to ModItem, which without
397 use of this hash makes it impossible to clear
398 an item field's value.  See bug 2466.
399
400 Note that only columns that can be directly
401 changed from the cataloging and serials
402 item editors are included in this hash.
403
404 Returns item record
405
406 =cut
407
408 my %default_values_for_mod_from_marc = (
409     barcode              => undef, 
410     booksellerid         => undef, 
411     ccode                => undef, 
412     'items.cn_source'    => undef, 
413     copynumber           => undef, 
414     damaged              => 0,
415 #    dateaccessioned      => undef,
416     enumchron            => undef, 
417     holdingbranch        => undef, 
418     homebranch           => undef, 
419     itemcallnumber       => undef, 
420     itemlost             => 0,
421     itemnotes            => undef, 
422     itype                => undef, 
423     location             => undef, 
424     permanent_location   => undef,
425     materials            => undef, 
426     notforloan           => 0,
427     paidfor              => undef, 
428     price                => undef, 
429     replacementprice     => undef, 
430     replacementpricedate => undef, 
431     restricted           => undef, 
432     stack                => undef, 
433     stocknumber          => undef, 
434     uri                  => undef, 
435     wthdrawn             => 0,
436 );
437
438 sub ModItemFromMarc {
439     my $item_marc = shift;
440     my $biblionumber = shift;
441     my $itemnumber = shift;
442
443     my $dbh           = C4::Context->dbh;
444     my $frameworkcode = GetFrameworkCode($biblionumber);
445     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
446
447     my $localitemmarc = MARC::Record->new;
448     $localitemmarc->append_fields( $item_marc->field($itemtag) );
449     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
450     foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
451         $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
452     }
453     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
454
455     ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields); 
456     return $item;
457 }
458
459 =head2 ModItem
460
461   ModItem({ column => $newvalue }, $biblionumber, 
462                   $itemnumber[, $original_item_marc]);
463
464 Change one or more columns in an item record and update
465 the MARC representation of the item.
466
467 The first argument is a hashref mapping from item column
468 names to the new values.  The second and third arguments
469 are the biblionumber and itemnumber, respectively.
470
471 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
472 an arrayref containing subfields present in the original MARC
473 representation of the item (e.g., from the item editor) that are
474 not mapped to C<items> columns directly but should instead
475 be stored in C<items.more_subfields_xml> and included in 
476 the biblio items tag for display and indexing.
477
478 If one of the changed columns is used to calculate
479 the derived value of a column such as C<items.cn_sort>, 
480 this routine will perform the necessary calculation
481 and set the value.
482
483 =cut
484
485 sub ModItem {
486     my $item = shift;
487     my $biblionumber = shift;
488     my $itemnumber = shift;
489
490     # if $biblionumber is undefined, get it from the current item
491     unless (defined $biblionumber) {
492         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
493     }
494
495     my $dbh           = @_ ? shift : C4::Context->dbh;
496     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
497     
498     my $unlinked_item_subfields;  
499     if (@_) {
500         $unlinked_item_subfields = shift;
501         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
502     };
503
504     $item->{'itemnumber'} = $itemnumber or return undef;
505
506     $item->{onloan} = undef if $item->{itemlost};
507
508     _set_derived_columns_for_mod($item);
509     _do_column_fixes_for_mod($item);
510     # FIXME add checks
511     # duplicate barcode
512     # attempt to change itemnumber
513     # attempt to change biblionumber (if we want
514     # an API to relink an item to a different bib,
515     # it should be a separate function)
516
517     # update items table
518     _koha_modify_item($item);
519
520     # request that bib be reindexed so that searching on current
521     # item status is possible
522     ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
523
524     logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
525 }
526
527 =head2 ModItemTransfer
528
529   ModItemTransfer($itenumber, $frombranch, $tobranch);
530
531 Marks an item as being transferred from one branch
532 to another.
533
534 =cut
535
536 sub ModItemTransfer {
537     my ( $itemnumber, $frombranch, $tobranch ) = @_;
538
539     my $dbh = C4::Context->dbh;
540
541     #new entry in branchtransfers....
542     my $sth = $dbh->prepare(
543         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
544         VALUES (?, ?, NOW(), ?)");
545     $sth->execute($itemnumber, $frombranch, $tobranch);
546
547     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
548     ModDateLastSeen($itemnumber);
549     return;
550 }
551
552 =head2 ModDateLastSeen
553
554   ModDateLastSeen($itemnum);
555
556 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
557 C<$itemnum> is the item number
558
559 =cut
560
561 sub ModDateLastSeen {
562     my ($itemnumber) = @_;
563     
564     my $today = C4::Dates->new();    
565     ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
566 }
567
568 =head2 DelItem
569
570   DelItem($dbh, $biblionumber, $itemnumber);
571
572 Exported function (core API) for deleting an item record in Koha.
573
574 =cut
575
576 sub DelItem {
577     my ( $dbh, $biblionumber, $itemnumber ) = @_;
578     
579     # FIXME check the item has no current issues
580     
581     _koha_delete_item( $dbh, $itemnumber );
582
583     # get the MARC record
584     my $record = GetMarcBiblio($biblionumber);
585     ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
586
587     # backup the record
588     my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
589     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
590     # 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).
591
592     #search item field code
593     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
594 }
595
596 =head2 CheckItemPreSave
597
598     my $item_ref = TransformMarcToKoha($marc, 'items');
599     # do stuff
600     my %errors = CheckItemPreSave($item_ref);
601     if (exists $errors{'duplicate_barcode'}) {
602         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
603     } elsif (exists $errors{'invalid_homebranch'}) {
604         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
605     } elsif (exists $errors{'invalid_holdingbranch'}) {
606         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
607     } else {
608         print "item is OK";
609     }
610
611 Given a hashref containing item fields, determine if it can be
612 inserted or updated in the database.  Specifically, checks for
613 database integrity issues, and returns a hash containing any
614 of the following keys, if applicable.
615
616 =over 2
617
618 =item duplicate_barcode
619
620 Barcode, if it duplicates one already found in the database.
621
622 =item invalid_homebranch
623
624 Home branch, if not defined in branches table.
625
626 =item invalid_holdingbranch
627
628 Holding branch, if not defined in branches table.
629
630 =back
631
632 This function does NOT implement any policy-related checks,
633 e.g., whether current operator is allowed to save an
634 item that has a given branch code.
635
636 =cut
637
638 sub CheckItemPreSave {
639     my $item_ref = shift;
640
641     my %errors = ();
642
643     # check for duplicate barcode
644     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
645         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
646         if ($existing_itemnumber) {
647             if (!exists $item_ref->{'itemnumber'}                       # new item
648                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
649                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
650             }
651         }
652     }
653
654     # check for valid home branch
655     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
656         my $branch_name = GetBranchName($item_ref->{'homebranch'});
657         unless (defined $branch_name) {
658             # relies on fact that branches.branchname is a non-NULL column,
659             # so GetBranchName returns undef only if branch does not exist
660             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
661         }
662     }
663
664     # check for valid holding branch
665     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
666         my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
667         unless (defined $branch_name) {
668             # relies on fact that branches.branchname is a non-NULL column,
669             # so GetBranchName returns undef only if branch does not exist
670             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
671         }
672     }
673
674     return %errors;
675
676 }
677
678 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
679
680 The following functions provide various ways of 
681 getting an item record, a set of item records, or
682 lists of authorized values for certain item fields.
683
684 Some of the functions in this group are candidates
685 for refactoring -- for example, some of the code
686 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
687 has copy-and-paste work.
688
689 =cut
690
691 =head2 GetItemStatus
692
693   $itemstatushash = GetItemStatus($fwkcode);
694
695 Returns a list of valid values for the
696 C<items.notforloan> field.
697
698 NOTE: does B<not> return an individual item's
699 status.
700
701 Can be MARC dependant.
702 fwkcode is optional.
703 But basically could be can be loan or not
704 Create a status selector with the following code
705
706 =head3 in PERL SCRIPT
707
708  my $itemstatushash = getitemstatus;
709  my @itemstatusloop;
710  foreach my $thisstatus (keys %$itemstatushash) {
711      my %row =(value => $thisstatus,
712                  statusname => $itemstatushash->{$thisstatus}->{'statusname'},
713              );
714      push @itemstatusloop, \%row;
715  }
716  $template->param(statusloop=>\@itemstatusloop);
717
718 =head3 in TEMPLATE
719
720  <select name="statusloop">
721      <option value="">Default</option>
722  <!-- TMPL_LOOP name="statusloop" -->
723      <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
724  <!-- /TMPL_LOOP -->
725  </select>
726
727 =cut
728
729 sub GetItemStatus {
730
731     # returns a reference to a hash of references to status...
732     my ($fwk) = @_;
733     my %itemstatus;
734     my $dbh = C4::Context->dbh;
735     my $sth;
736     $fwk = '' unless ($fwk);
737     my ( $tag, $subfield ) =
738       GetMarcFromKohaField( "items.notforloan", $fwk );
739     if ( $tag and $subfield ) {
740         my $sth =
741           $dbh->prepare(
742             "SELECT authorised_value
743             FROM marc_subfield_structure
744             WHERE tagfield=?
745                 AND tagsubfield=?
746                 AND frameworkcode=?
747             "
748           );
749         $sth->execute( $tag, $subfield, $fwk );
750         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
751             my $authvalsth =
752               $dbh->prepare(
753                 "SELECT authorised_value,lib
754                 FROM authorised_values 
755                 WHERE category=? 
756                 ORDER BY lib
757                 "
758               );
759             $authvalsth->execute($authorisedvaluecat);
760             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
761                 $itemstatus{$authorisedvalue} = $lib;
762             }
763             return \%itemstatus;
764             exit 1;
765         }
766         else {
767
768             #No authvalue list
769             # build default
770         }
771     }
772
773     #No authvalue list
774     #build default
775     $itemstatus{"1"} = "Not For Loan";
776     return \%itemstatus;
777 }
778
779 =head2 GetItemLocation
780
781   $itemlochash = GetItemLocation($fwk);
782
783 Returns a list of valid values for the
784 C<items.location> field.
785
786 NOTE: does B<not> return an individual item's
787 location.
788
789 where fwk stands for an optional framework code.
790 Create a location selector with the following code
791
792 =head3 in PERL SCRIPT
793
794   my $itemlochash = getitemlocation;
795   my @itemlocloop;
796   foreach my $thisloc (keys %$itemlochash) {
797       my $selected = 1 if $thisbranch eq $branch;
798       my %row =(locval => $thisloc,
799                   selected => $selected,
800                   locname => $itemlochash->{$thisloc},
801                );
802       push @itemlocloop, \%row;
803   }
804   $template->param(itemlocationloop => \@itemlocloop);
805
806 =head3 in TEMPLATE
807
808   <select name="location">
809       <option value="">Default</option>
810   <!-- TMPL_LOOP name="itemlocationloop" -->
811       <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
812   <!-- /TMPL_LOOP -->
813   </select>
814
815 =cut
816
817 sub GetItemLocation {
818
819     # returns a reference to a hash of references to location...
820     my ($fwk) = @_;
821     my %itemlocation;
822     my $dbh = C4::Context->dbh;
823     my $sth;
824     $fwk = '' unless ($fwk);
825     my ( $tag, $subfield ) =
826       GetMarcFromKohaField( "items.location", $fwk );
827     if ( $tag and $subfield ) {
828         my $sth =
829           $dbh->prepare(
830             "SELECT authorised_value
831             FROM marc_subfield_structure 
832             WHERE tagfield=? 
833                 AND tagsubfield=? 
834                 AND frameworkcode=?"
835           );
836         $sth->execute( $tag, $subfield, $fwk );
837         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
838             my $authvalsth =
839               $dbh->prepare(
840                 "SELECT authorised_value,lib
841                 FROM authorised_values
842                 WHERE category=?
843                 ORDER BY lib"
844               );
845             $authvalsth->execute($authorisedvaluecat);
846             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
847                 $itemlocation{$authorisedvalue} = $lib;
848             }
849             return \%itemlocation;
850             exit 1;
851         }
852         else {
853
854             #No authvalue list
855             # build default
856         }
857     }
858
859     #No authvalue list
860     #build default
861     $itemlocation{"1"} = "Not For Loan";
862     return \%itemlocation;
863 }
864
865 =head2 GetLostItems
866
867   $items = GetLostItems( $where, $orderby );
868
869 This function gets a list of lost items.
870
871 =over 2
872
873 =item input:
874
875 C<$where> is a hashref. it containts a field of the items table as key
876 and the value to match as value. For example:
877
878 { barcode    => 'abc123',
879   homebranch => 'CPL',    }
880
881 C<$orderby> is a field of the items table by which the resultset
882 should be orderd.
883
884 =item return:
885
886 C<$items> is a reference to an array full of hashrefs with columns
887 from the "items" table as keys.
888
889 =item usage in the perl script:
890
891   my $where = { barcode => '0001548' };
892   my $items = GetLostItems( $where, "homebranch" );
893   $template->param( itemsloop => $items );
894
895 =back
896
897 =cut
898
899 sub GetLostItems {
900     # Getting input args.
901     my $where   = shift;
902     my $orderby = shift;
903     my $dbh     = C4::Context->dbh;
904
905     my $query   = "
906         SELECT *
907         FROM   items
908             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
909             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
910             LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
911         WHERE
912                 authorised_values.category = 'LOST'
913                 AND itemlost IS NOT NULL
914                 AND itemlost <> 0
915     ";
916     my @query_parameters;
917     foreach my $key (keys %$where) {
918         $query .= " AND $key LIKE ?";
919         push @query_parameters, "%$where->{$key}%";
920     }
921     my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
922     
923     if ( defined $orderby && grep($orderby, @ordervalues)) {
924         $query .= ' ORDER BY '.$orderby;
925     }
926
927     my $sth = $dbh->prepare($query);
928     $sth->execute( @query_parameters );
929     my $items = [];
930     while ( my $row = $sth->fetchrow_hashref ){
931         push @$items, $row;
932     }
933     return $items;
934 }
935
936 =head2 GetItemsForInventory
937
938   $itemlist = GetItemsForInventory($minlocation, $maxlocation, 
939                  $location, $itemtype $datelastseen, $branch, 
940                  $offset, $size, $statushash);
941
942 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
943
944 The sub returns a reference to a list of hashes, each containing
945 itemnumber, author, title, barcode, item callnumber, and date last
946 seen. It is ordered by callnumber then title.
947
948 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
949 the datelastseen can be used to specify that you want to see items not seen since a past date only.
950 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
951 $statushash requires a hashref that has the authorized values fieldname (intems.notforloan, etc...) as keys, and an arrayref of statuscodes we are searching for as values.
952
953 =cut
954
955 sub GetItemsForInventory {
956     my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
957     my $dbh = C4::Context->dbh;
958     my ( @bind_params, @where_strings );
959
960     my $query = <<'END_SQL';
961 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
962 FROM items
963   LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
964   LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
965 END_SQL
966     if ($statushash){
967         for my $authvfield (keys %$statushash){
968             if ( scalar @{$statushash->{$authvfield}} > 0 ){
969                 my $joinedvals = join ',', @{$statushash->{$authvfield}};
970                 push @where_strings, "$authvfield in (" . $joinedvals . ")";
971             }
972         }
973     }
974
975     if ($minlocation) {
976         push @where_strings, 'itemcallnumber >= ?';
977         push @bind_params, $minlocation;
978     }
979
980     if ($maxlocation) {
981         push @where_strings, 'itemcallnumber <= ?';
982         push @bind_params, $maxlocation;
983     }
984
985     if ($datelastseen) {
986         $datelastseen = format_date_in_iso($datelastseen);  
987         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
988         push @bind_params, $datelastseen;
989     }
990
991     if ( $location ) {
992         push @where_strings, 'items.location = ?';
993         push @bind_params, $location;
994     }
995
996     if ( $branchcode ) {
997         if($branch eq "homebranch"){
998         push @where_strings, 'items.homebranch = ?';
999         }else{
1000             push @where_strings, 'items.holdingbranch = ?';
1001         }
1002         push @bind_params, $branchcode;
1003     }
1004     
1005     if ( $itemtype ) {
1006         push @where_strings, 'biblioitems.itemtype = ?';
1007         push @bind_params, $itemtype;
1008     }
1009
1010     if ( $ignoreissued) {
1011         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1012         push @where_strings, 'issues.date_due IS NULL';
1013     }
1014
1015     if ( @where_strings ) {
1016         $query .= 'WHERE ';
1017         $query .= join ' AND ', @where_strings;
1018     }
1019     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1020     my $sth = $dbh->prepare($query);
1021     $sth->execute( @bind_params );
1022
1023     my @results;
1024     $size--;
1025     while ( my $row = $sth->fetchrow_hashref ) {
1026         $offset-- if ($offset);
1027         $row->{datelastseen}=format_date($row->{datelastseen});
1028         if ( ( !$offset ) && $size ) {
1029             push @results, $row;
1030             $size--;
1031         }
1032     }
1033     return \@results;
1034 }
1035
1036 =head2 GetItemsCount
1037
1038   $count = &GetItemsCount( $biblionumber);
1039
1040 This function return count of item with $biblionumber
1041
1042 =cut
1043
1044 sub GetItemsCount {
1045     my ( $biblionumber ) = @_;
1046     my $dbh = C4::Context->dbh;
1047     my $query = "SELECT count(*)
1048           FROM  items 
1049           WHERE biblionumber=?";
1050     my $sth = $dbh->prepare($query);
1051     $sth->execute($biblionumber);
1052     my $count = $sth->fetchrow;  
1053     return ($count);
1054 }
1055
1056 =head2 GetItemInfosOf
1057
1058   GetItemInfosOf(@itemnumbers);
1059
1060 =cut
1061
1062 sub GetItemInfosOf {
1063     my @itemnumbers = @_;
1064
1065     my $query = '
1066         SELECT *
1067         FROM items
1068         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1069     ';
1070     return get_infos_of( $query, 'itemnumber' );
1071 }
1072
1073 =head2 GetItemsByBiblioitemnumber
1074
1075   GetItemsByBiblioitemnumber($biblioitemnumber);
1076
1077 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1078 Called by C<C4::XISBN>
1079
1080 =cut
1081
1082 sub GetItemsByBiblioitemnumber {
1083     my ( $bibitem ) = @_;
1084     my $dbh = C4::Context->dbh;
1085     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1086     # Get all items attached to a biblioitem
1087     my $i = 0;
1088     my @results; 
1089     $sth->execute($bibitem) || die $sth->errstr;
1090     while ( my $data = $sth->fetchrow_hashref ) {  
1091         # Foreach item, get circulation information
1092         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1093                                    WHERE itemnumber = ?
1094                                    AND issues.borrowernumber = borrowers.borrowernumber"
1095         );
1096         $sth2->execute( $data->{'itemnumber'} );
1097         if ( my $data2 = $sth2->fetchrow_hashref ) {
1098             # if item is out, set the due date and who it is out too
1099             $data->{'date_due'}   = $data2->{'date_due'};
1100             $data->{'cardnumber'} = $data2->{'cardnumber'};
1101             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1102         }
1103         else {
1104             # set date_due to blank, so in the template we check itemlost, and wthdrawn 
1105             $data->{'date_due'} = '';                                                                                                         
1106         }    # else         
1107         # Find the last 3 people who borrowed this item.                  
1108         my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1109                       AND old_issues.borrowernumber = borrowers.borrowernumber
1110                       ORDER BY returndate desc,timestamp desc LIMIT 3";
1111         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1112         $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1113         my $i2 = 0;
1114         while ( my $data2 = $sth2->fetchrow_hashref ) {
1115             $data->{"timestamp$i2"} = $data2->{'timestamp'};
1116             $data->{"card$i2"}      = $data2->{'cardnumber'};
1117             $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1118             $i2++;
1119         }
1120         push(@results,$data);
1121     } 
1122     return (\@results); 
1123 }
1124
1125 =head2 GetItemsInfo
1126
1127   @results = GetItemsInfo($biblionumber);
1128
1129 Returns information about items with the given biblionumber.
1130
1131 C<GetItemsInfo> returns a list of references-to-hash. Each element
1132 contains a number of keys. Most of them are attributes from the
1133 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1134 Koha database. Other keys include:
1135
1136 =over 2
1137
1138 =item C<$data-E<gt>{branchname}>
1139
1140 The name (not the code) of the branch to which the book belongs.
1141
1142 =item C<$data-E<gt>{datelastseen}>
1143
1144 This is simply C<items.datelastseen>, except that while the date is
1145 stored in YYYY-MM-DD format in the database, here it is converted to
1146 DD/MM/YYYY format. A NULL date is returned as C<//>.
1147
1148 =item C<$data-E<gt>{datedue}>
1149
1150 =item C<$data-E<gt>{class}>
1151
1152 This is the concatenation of C<biblioitems.classification>, the book's
1153 Dewey code, and C<biblioitems.subclass>.
1154
1155 =item C<$data-E<gt>{ocount}>
1156
1157 I think this is the number of copies of the book available.
1158
1159 =item C<$data-E<gt>{order}>
1160
1161 If this is set, it is set to C<One Order>.
1162
1163 =back
1164
1165 =cut
1166
1167 sub GetItemsInfo {
1168     my ( $biblionumber ) = @_;
1169     my $dbh   = C4::Context->dbh;
1170     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1171     my $query = "
1172     SELECT items.*,
1173            biblio.*,
1174            biblioitems.volume,
1175            biblioitems.number,
1176            biblioitems.itemtype,
1177            biblioitems.isbn,
1178            biblioitems.issn,
1179            biblioitems.publicationyear,
1180            biblioitems.publishercode,
1181            biblioitems.volumedate,
1182            biblioitems.volumedesc,
1183            biblioitems.lccn,
1184            biblioitems.url,
1185            items.notforloan as itemnotforloan,
1186            itemtypes.description,
1187            itemtypes.notforloan as notforloan_per_itemtype,
1188            branchurl
1189      FROM items
1190      LEFT JOIN branches ON items.holdingbranch = branches.branchcode
1191      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
1192      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1193      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
1194      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1195     $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1196     my $sth = $dbh->prepare($query);
1197     $sth->execute($biblionumber);
1198     my $i = 0;
1199     my @results;
1200     my $serial;
1201
1202     my $isth    = $dbh->prepare(
1203         "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1204         FROM   issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1205         WHERE  itemnumber = ?"
1206        );
1207         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
1208         while ( my $data = $sth->fetchrow_hashref ) {
1209         my $datedue = '';
1210         my $count_reserves;
1211         $isth->execute( $data->{'itemnumber'} );
1212         if ( my $idata = $isth->fetchrow_hashref ) {
1213             $data->{borrowernumber} = $idata->{borrowernumber};
1214             $data->{cardnumber}     = $idata->{cardnumber};
1215             $data->{surname}     = $idata->{surname};
1216             $data->{firstname}     = $idata->{firstname};
1217             $data->{lastreneweddate} = $idata->{lastreneweddate};
1218             $datedue                = $idata->{'date_due'};
1219         if (C4::Context->preference("IndependantBranches")){
1220         my $userenv = C4::Context->userenv;
1221         if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) { 
1222             $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1223         }
1224         }
1225         }
1226                 if ( $data->{'serial'}) {       
1227                         $ssth->execute($data->{'itemnumber'}) ;
1228                         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1229                         $serial = 1;
1230         }
1231                 if ( $datedue eq '' ) {
1232             my ( $restype, $reserves, undef ) =
1233               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1234 # Previous conditional check with if ($restype) is not needed because a true
1235 # result for one item will result in subsequent items defaulting to this true
1236 # value.
1237             $count_reserves = $restype;
1238         }
1239         #get branch information.....
1240         my $bsth = $dbh->prepare(
1241             "SELECT * FROM branches WHERE branchcode = ?
1242         "
1243         );
1244         $bsth->execute( $data->{'holdingbranch'} );
1245         if ( my $bdata = $bsth->fetchrow_hashref ) {
1246             $data->{'branchname'} = $bdata->{'branchname'};
1247         }
1248         $data->{'datedue'}        = $datedue;
1249         $data->{'count_reserves'} = $count_reserves;
1250
1251         # get notforloan complete status if applicable
1252         my $sthnflstatus = $dbh->prepare(
1253             'SELECT authorised_value
1254             FROM   marc_subfield_structure
1255             WHERE  kohafield="items.notforloan"
1256         '
1257         );
1258
1259         $sthnflstatus->execute;
1260         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1261         if ($authorised_valuecode) {
1262             $sthnflstatus = $dbh->prepare(
1263                 "SELECT lib FROM authorised_values
1264                  WHERE  category=?
1265                  AND authorised_value=?"
1266             );
1267             $sthnflstatus->execute( $authorised_valuecode,
1268                 $data->{itemnotforloan} );
1269             my ($lib) = $sthnflstatus->fetchrow;
1270             $data->{notforloanvalue} = $lib;
1271         }
1272
1273         # get restricted status and description if applicable
1274         my $restrictedstatus = $dbh->prepare(
1275             'SELECT authorised_value
1276             FROM   marc_subfield_structure
1277             WHERE  kohafield="items.restricted"
1278         '
1279         );
1280
1281         $restrictedstatus->execute;
1282         ($authorised_valuecode) = $restrictedstatus->fetchrow;
1283         if ($authorised_valuecode) {
1284             $restrictedstatus = $dbh->prepare(
1285                 "SELECT lib,lib_opac FROM authorised_values
1286                  WHERE  category=?
1287                  AND authorised_value=?"
1288             );
1289             $restrictedstatus->execute( $authorised_valuecode,
1290                 $data->{restricted} );
1291
1292             if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1293                 $data->{restricted} = $rstdata->{'lib'};
1294                 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1295             }
1296         }
1297
1298         # my stack procedures
1299         my $stackstatus = $dbh->prepare(
1300             'SELECT authorised_value
1301              FROM   marc_subfield_structure
1302              WHERE  kohafield="items.stack"
1303         '
1304         );
1305         $stackstatus->execute;
1306
1307         ($authorised_valuecode) = $stackstatus->fetchrow;
1308         if ($authorised_valuecode) {
1309             $stackstatus = $dbh->prepare(
1310                 "SELECT lib
1311                  FROM   authorised_values
1312                  WHERE  category=?
1313                  AND    authorised_value=?
1314             "
1315             );
1316             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1317             my ($lib) = $stackstatus->fetchrow;
1318             $data->{stack} = $lib;
1319         }
1320         # Find the last 3 people who borrowed this item.
1321         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1322                                     WHERE itemnumber = ?
1323                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1324                                     ORDER BY returndate DESC
1325                                     LIMIT 3");
1326         $sth2->execute($data->{'itemnumber'});
1327         my $ii = 0;
1328         while (my $data2 = $sth2->fetchrow_hashref()) {
1329             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1330             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1331             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1332             $ii++;
1333         }
1334
1335         $results[$i] = $data;
1336         $i++;
1337     }
1338         if($serial) {
1339                 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1340         } else {
1341         return (@results);
1342         }
1343 }
1344
1345 =head2 GetItemsLocationInfo
1346
1347   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1348
1349 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1350
1351 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1352
1353 =over 2
1354
1355 =item C<$data-E<gt>{homebranch}>
1356
1357 Branch Name of the item's homebranch
1358
1359 =item C<$data-E<gt>{holdingbranch}>
1360
1361 Branch Name of the item's holdingbranch
1362
1363 =item C<$data-E<gt>{location}>
1364
1365 Item's shelving location code
1366
1367 =item C<$data-E<gt>{location_intranet}>
1368
1369 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1370
1371 =item C<$data-E<gt>{location_opac}>
1372
1373 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
1374 description is set.
1375
1376 =item C<$data-E<gt>{itemcallnumber}>
1377
1378 Item's itemcallnumber
1379
1380 =item C<$data-E<gt>{cn_sort}>
1381
1382 Item's call number normalized for sorting
1383
1384 =back
1385   
1386 =cut
1387
1388 sub GetItemsLocationInfo {
1389         my $biblionumber = shift;
1390         my @results;
1391
1392         my $dbh = C4::Context->dbh;
1393         my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch, 
1394                             location, itemcallnumber, cn_sort
1395                      FROM items, branches as a, branches as b
1396                      WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode 
1397                      AND biblionumber = ?
1398                      ORDER BY cn_sort ASC";
1399         my $sth = $dbh->prepare($query);
1400         $sth->execute($biblionumber);
1401
1402         while ( my $data = $sth->fetchrow_hashref ) {
1403              $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1404              $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1405              push @results, $data;
1406         }
1407         return @results;
1408 }
1409
1410 =head2 GetHostItemsInfo
1411
1412         $hostiteminfo = GetHostItemsInfo($hostfield);
1413         Returns the iteminfo for items linked to records via a host field
1414
1415 =cut
1416
1417 sub GetHostItemsInfo {
1418         my ($record) = @_;
1419         my @returnitemsInfo;
1420
1421         if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1422         C4::Context->preference('marcflavour') eq 'NORMARC'){
1423             foreach my $hostfield ( $record->field('773') ) {
1424                 my $hostbiblionumber = $hostfield->subfield("0");
1425                 my $linkeditemnumber = $hostfield->subfield("9");
1426                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1427                 foreach my $hostitemInfo (@hostitemInfos){
1428                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1429                                 push (@returnitemsInfo,$hostitemInfo);
1430                                 last;
1431                         }
1432                 }
1433             }
1434         } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1435             foreach my $hostfield ( $record->field('461') ) {
1436                 my $hostbiblionumber = $hostfield->subfield("0");
1437                 my $linkeditemnumber = $hostfield->subfield("9");
1438                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1439                 foreach my $hostitemInfo (@hostitemInfos){
1440                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1441                                 push (@returnitemsInfo,$hostitemInfo);
1442                                 last;
1443                         }
1444                 }
1445             }
1446         }
1447         return @returnitemsInfo;
1448 }
1449
1450
1451 =head2 GetLastAcquisitions
1452
1453   my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
1454                                     'itemtypes' => ('BK','BD')}, 10);
1455
1456 =cut
1457
1458 sub  GetLastAcquisitions {
1459         my ($data,$max) = @_;
1460
1461         my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1462         
1463         my $number_of_branches = @{$data->{branches}};
1464         my $number_of_itemtypes   = @{$data->{itemtypes}};
1465         
1466         
1467         my @where = ('WHERE 1 '); 
1468         $number_of_branches and push @where
1469            , 'AND holdingbranch IN (' 
1470            , join(',', ('?') x $number_of_branches )
1471            , ')'
1472          ;
1473         
1474         $number_of_itemtypes and push @where
1475            , "AND $itemtype IN (" 
1476            , join(',', ('?') x $number_of_itemtypes )
1477            , ')'
1478          ;
1479
1480         my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1481                                  FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber) 
1482                                     RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1483                                     @where
1484                                     GROUP BY biblio.biblionumber 
1485                                     ORDER BY dateaccessioned DESC LIMIT $max";
1486
1487         my $dbh = C4::Context->dbh;
1488         my $sth = $dbh->prepare($query);
1489     
1490     $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1491         
1492         my @results;
1493         while( my $row = $sth->fetchrow_hashref){
1494                 push @results, {date => $row->{dateaccessioned} 
1495                                                 , biblionumber => $row->{biblionumber}
1496                                                 , title => $row->{title}};
1497         }
1498         
1499         return @results;
1500 }
1501
1502 =head2 get_itemnumbers_of
1503
1504   my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1505
1506 Given a list of biblionumbers, return the list of corresponding itemnumbers
1507 for each biblionumber.
1508
1509 Return a reference on a hash where keys are biblionumbers and values are
1510 references on array of itemnumbers.
1511
1512 =cut
1513
1514 sub get_itemnumbers_of {
1515     my @biblionumbers = @_;
1516
1517     my $dbh = C4::Context->dbh;
1518
1519     my $query = '
1520         SELECT itemnumber,
1521             biblionumber
1522         FROM items
1523         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1524     ';
1525     my $sth = $dbh->prepare($query);
1526     $sth->execute(@biblionumbers);
1527
1528     my %itemnumbers_of;
1529
1530     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1531         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1532     }
1533
1534     return \%itemnumbers_of;
1535 }
1536
1537 =head2 get_hostitemnumbers_of
1538
1539   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1540
1541 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1542
1543 Return a reference on a hash where key is a biblionumber and values are
1544 references on array of itemnumbers.
1545
1546 =cut
1547
1548
1549 sub get_hostitemnumbers_of {
1550         my ($biblionumber) = @_;
1551         my $marcrecord = GetMarcBiblio($biblionumber);
1552         my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1553         
1554         my $marcflavor = C4::Context->preference('marcflavour');
1555         if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1556         $tag='773';
1557         $biblio_s='0';
1558         $item_s='9';
1559     } elsif ($marcflavor eq 'UNIMARC') {
1560         $tag='461';
1561         $biblio_s='0';
1562         $item_s='9';
1563     }
1564
1565     foreach my $hostfield ( $marcrecord->field($tag) ) {
1566         my $hostbiblionumber = $hostfield->subfield($biblio_s);
1567         my $linkeditemnumber = $hostfield->subfield($item_s);
1568         my @itemnumbers;
1569         if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1570         {
1571             @itemnumbers = @$itemnumbers;
1572         }
1573         foreach my $itemnumber (@itemnumbers){
1574             if ($itemnumber eq $linkeditemnumber){
1575                 push (@returnhostitemnumbers,$itemnumber);
1576                 last;
1577             }
1578         }
1579     }
1580     return @returnhostitemnumbers;
1581 }
1582
1583
1584 =head2 GetItemnumberFromBarcode
1585
1586   $result = GetItemnumberFromBarcode($barcode);
1587
1588 =cut
1589
1590 sub GetItemnumberFromBarcode {
1591     my ($barcode) = @_;
1592     my $dbh = C4::Context->dbh;
1593
1594     my $rq =
1595       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1596     $rq->execute($barcode);
1597     my ($result) = $rq->fetchrow;
1598     return ($result);
1599 }
1600
1601 =head2 GetBarcodeFromItemnumber
1602
1603   $result = GetBarcodeFromItemnumber($itemnumber);
1604
1605 =cut
1606
1607 sub GetBarcodeFromItemnumber {
1608     my ($itemnumber) = @_;
1609     my $dbh = C4::Context->dbh;
1610
1611     my $rq =
1612       $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1613     $rq->execute($itemnumber);
1614     my ($result) = $rq->fetchrow;
1615     return ($result);
1616 }
1617
1618 =head2 GetHiddenItemnumbers
1619
1620 =over 4
1621
1622 $result = GetHiddenItemnumbers(@items);
1623
1624 =back
1625
1626 =cut
1627
1628 sub GetHiddenItemnumbers {
1629     my (@items) = @_;
1630     my @resultitems;
1631
1632     my $yaml = C4::Context->preference('OpacHiddenItems');
1633     my $hidingrules;
1634     eval {
1635         $hidingrules = YAML::Load($yaml);
1636     };
1637     if ($@) {
1638         warn "Unable to parse OpacHiddenItems syspref : $@";
1639         return ();
1640     } else {
1641     my $dbh = C4::Context->dbh;
1642
1643         # For each item
1644         foreach my $item (@items) {
1645
1646             # We check each rule
1647             foreach my $field (keys %$hidingrules) {
1648                 my $query = "SELECT $field from items where itemnumber = ?";
1649                 my $sth = $dbh->prepare($query);        
1650                 $sth->execute($item->{'itemnumber'});
1651                 my ($result) = $sth->fetchrow;
1652
1653                 # If the results matches the values in the yaml file
1654                 if (any { $result eq $_ } @{$hidingrules->{$field}}) {
1655
1656                     # We add the itemnumber to the list
1657                     push @resultitems, $item->{'itemnumber'};       
1658
1659                     # If at least one rule matched for an item, no need to test the others
1660                     last;
1661                 }
1662             }
1663         }
1664         return @resultitems;
1665     }
1666
1667  }
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         my $order = GetOrderFromItemnumber($itemnumber);
2179             if ($order) {
2180                     # Replacing the biblionumber within the order if necessary
2181                     $order->{'biblionumber'} = $tobiblio;
2182                 ModOrder($order);
2183             }
2184         return $tobiblio;
2185         }
2186     return;
2187 }
2188
2189 =head2 DelItemCheck
2190
2191    DelItemCheck($dbh, $biblionumber, $itemnumber);
2192
2193 Exported function (core API) for deleting an item record in Koha if there no current issue.
2194
2195 =cut
2196
2197 sub DelItemCheck {
2198     my ( $dbh, $biblionumber, $itemnumber ) = @_;
2199     my $error;
2200
2201         my $countanalytics=GetAnalyticsCount($itemnumber);
2202
2203
2204     # check that there is no issue on this item before deletion.
2205     my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2206     $sth->execute($itemnumber);
2207
2208     my $item = GetItem($itemnumber);
2209     my $onloan=$sth->fetchrow;
2210
2211     if ($onloan){
2212         $error = "book_on_loan" 
2213     }
2214     elsif ( C4::Context->userenv->{flags} & 1 and
2215             C4::Context->preference("IndependantBranches") and
2216            (C4::Context->userenv->{branch} ne
2217              $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2218     {
2219         $error = "not_same_branch";
2220     }
2221         else{
2222         # check it doesnt have a waiting reserve
2223         $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2224         $sth->execute($itemnumber);
2225         my $reserve=$sth->fetchrow;
2226         if ($reserve){
2227             $error = "book_reserved";
2228         } elsif ($countanalytics > 0){
2229                 $error = "linked_analytics";
2230         } else {
2231             DelItem($dbh, $biblionumber, $itemnumber);
2232             return 1;
2233         }
2234     }
2235     return $error;
2236 }
2237
2238 =head2 _koha_modify_item
2239
2240   my ($itemnumber,$error) =_koha_modify_item( $item );
2241
2242 Perform the actual update of the C<items> row.  Note that this
2243 routine accepts a hashref specifying the columns to update.
2244
2245 =cut
2246
2247 sub _koha_modify_item {
2248     my ( $item ) = @_;
2249     my $dbh=C4::Context->dbh;  
2250     my $error;
2251
2252     my $query = "UPDATE items SET ";
2253     my @bind;
2254     for my $key ( keys %$item ) {
2255         $query.="$key=?,";
2256         push @bind, $item->{$key};
2257     }
2258     $query =~ s/,$//;
2259     $query .= " WHERE itemnumber=?";
2260     push @bind, $item->{'itemnumber'};
2261     my $sth = C4::Context->dbh->prepare($query);
2262     $sth->execute(@bind);
2263     if ( C4::Context->dbh->errstr ) {
2264         $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2265         warn $error;
2266     }
2267     return ($item->{'itemnumber'},$error);
2268 }
2269
2270 =head2 _koha_delete_item
2271
2272   _koha_delete_item( $dbh, $itemnum );
2273
2274 Internal function to delete an item record from the koha tables
2275
2276 =cut
2277
2278 sub _koha_delete_item {
2279     my ( $dbh, $itemnum ) = @_;
2280
2281     # save the deleted item to deleteditems table
2282     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2283     $sth->execute($itemnum);
2284     my $data = $sth->fetchrow_hashref();
2285     my $query = "INSERT INTO deleteditems SET ";
2286     my @bind  = ();
2287     foreach my $key ( keys %$data ) {
2288         $query .= "$key = ?,";
2289         push( @bind, $data->{$key} );
2290     }
2291     $query =~ s/\,$//;
2292     $sth = $dbh->prepare($query);
2293     $sth->execute(@bind);
2294
2295     # delete from items table
2296     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2297     $sth->execute($itemnum);
2298     return undef;
2299 }
2300
2301 =head2 _marc_from_item_hash
2302
2303   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2304
2305 Given an item hash representing a complete item record,
2306 create a C<MARC::Record> object containing an embedded
2307 tag representing that item.
2308
2309 The third, optional parameter C<$unlinked_item_subfields> is
2310 an arrayref of subfields (not mapped to C<items> fields per the
2311 framework) to be added to the MARC representation
2312 of the item.
2313
2314 =cut
2315
2316 sub _marc_from_item_hash {
2317     my $item = shift;
2318     my $frameworkcode = shift;
2319     my $unlinked_item_subfields;
2320     if (@_) {
2321         $unlinked_item_subfields = shift;
2322     }
2323    
2324     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2325     # Also, don't emit a subfield if the underlying field is blank.
2326     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
2327                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
2328                                 : ()  } keys %{ $item } }; 
2329
2330     my $item_marc = MARC::Record->new();
2331     foreach my $item_field ( keys %{$mungeditem} ) {
2332         my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2333         next unless defined $tag and defined $subfield;    # skip if not mapped to MARC field
2334         my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2335         foreach my $value (@values){
2336             if ( my $field = $item_marc->field($tag) ) {
2337                     $field->add_subfields( $subfield => $value );
2338             } else {
2339                 my $add_subfields = [];
2340                 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2341                     $add_subfields = $unlinked_item_subfields;
2342             }
2343             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2344             }
2345         }
2346     }
2347
2348     return $item_marc;
2349 }
2350
2351 =head2 _repack_item_errors
2352
2353 Add an error message hash generated by C<CheckItemPreSave>
2354 to a list of errors.
2355
2356 =cut
2357
2358 sub _repack_item_errors {
2359     my $item_sequence_num = shift;
2360     my $item_ref = shift;
2361     my $error_ref = shift;
2362
2363     my @repacked_errors = ();
2364
2365     foreach my $error_code (sort keys %{ $error_ref }) {
2366         my $repacked_error = {};
2367         $repacked_error->{'item_sequence'} = $item_sequence_num;
2368         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2369         $repacked_error->{'error_code'} = $error_code;
2370         $repacked_error->{'error_information'} = $error_ref->{$error_code};
2371         push @repacked_errors, $repacked_error;
2372     } 
2373
2374     return @repacked_errors;
2375 }
2376
2377 =head2 _get_unlinked_item_subfields
2378
2379   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2380
2381 =cut
2382
2383 sub _get_unlinked_item_subfields {
2384     my $original_item_marc = shift;
2385     my $frameworkcode = shift;
2386
2387     my $marcstructure = GetMarcStructure(1, $frameworkcode);
2388
2389     # assume that this record has only one field, and that that
2390     # field contains only the item information
2391     my $subfields = [];
2392     my @fields = $original_item_marc->fields();
2393     if ($#fields > -1) {
2394         my $field = $fields[0];
2395             my $tag = $field->tag();
2396         foreach my $subfield ($field->subfields()) {
2397             if (defined $subfield->[1] and
2398                 $subfield->[1] ne '' and
2399                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2400                 push @$subfields, $subfield->[0] => $subfield->[1];
2401             }
2402         }
2403     }
2404     return $subfields;
2405 }
2406
2407 =head2 _get_unlinked_subfields_xml
2408
2409   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2410
2411 =cut
2412
2413 sub _get_unlinked_subfields_xml {
2414     my $unlinked_item_subfields = shift;
2415
2416     my $xml;
2417     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2418         my $marc = MARC::Record->new();
2419         # use of tag 999 is arbitrary, and doesn't need to match the item tag
2420         # used in the framework
2421         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2422         $marc->encoding("UTF-8");    
2423         $xml = $marc->as_xml("USMARC");
2424     }
2425
2426     return $xml;
2427 }
2428
2429 =head2 _parse_unlinked_item_subfields_from_xml
2430
2431   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2432
2433 =cut
2434
2435 sub  _parse_unlinked_item_subfields_from_xml {
2436     my $xml = shift;
2437
2438     return unless defined $xml and $xml ne "";
2439     my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2440     my $unlinked_subfields = [];
2441     my @fields = $marc->fields();
2442     if ($#fields > -1) {
2443         foreach my $subfield ($fields[0]->subfields()) {
2444             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2445         }
2446     }
2447     return $unlinked_subfields;
2448 }
2449
2450 =head2 GetAnalyticsCount
2451
2452   $count= &GetAnalyticsCount($itemnumber)
2453
2454 counts Usage of itemnumber in Analytical bibliorecords. 
2455
2456 =cut
2457
2458 sub GetAnalyticsCount {
2459     my ($itemnumber) = @_;
2460     if (C4::Context->preference('NoZebra')) {
2461         # Read the index Koha-Auth-Number for this authid and count the lines
2462         my $result = C4::Search::NZanalyse("hi=$itemnumber");
2463         my @tab = split /;/,$result;
2464         return scalar @tab;
2465     } else {
2466         ### ZOOM search here
2467         my $query;
2468         $query= "hi=".$itemnumber;
2469                 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2470         return ($result);
2471     }
2472 }
2473
2474 =head2 GetItemHolds
2475
2476 =over 4
2477 $holds = &GetItemHolds($biblionumber, $itemnumber);
2478
2479 =back
2480
2481 This function return the count of holds with $biblionumber and $itemnumber
2482
2483 =cut
2484
2485 sub GetItemHolds {
2486     my ($biblionumber, $itemnumber) = @_;
2487     my $holds;
2488     my $dbh            = C4::Context->dbh;
2489     my $query          = "SELECT count(*)
2490         FROM  reserves
2491         WHERE biblionumber=? AND itemnumber=?";
2492     my $sth = $dbh->prepare($query);
2493     $sth->execute($biblionumber, $itemnumber);
2494     $holds = $sth->fetchrow;
2495     return $holds;
2496 }
2497 1;