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