IMPROVEMENT : serialsadditems at subscription level (bump 071)
[koha.git] / C4 / Items.pm
1 package C4::Items;
2
3 # Copyright 2007 LibLime, Inc.
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21
22 use C4::Context;
23 use C4::Koha;
24 use C4::Biblio;
25 use C4::Dates qw/format_date format_date_in_iso/;
26 use MARC::Record;
27 use C4::ClassSource;
28 use C4::Log;
29 use C4::Branch;
30 require C4::Reserves;
31 use C4::Charset;
32
33 use vars qw($VERSION @ISA @EXPORT);
34
35 BEGIN {
36     $VERSION = 3.01;
37
38         require Exporter;
39     @ISA = qw( Exporter );
40
41     # function exports
42     @EXPORT = qw(
43         GetItem
44         AddItemFromMarc
45         AddItem
46         AddItemBatchFromMarc
47         ModItemFromMarc
48         ModItem
49         ModDateLastSeen
50         ModItemTransfer
51         DelItem
52     
53         CheckItemPreSave
54     
55         GetItemStatus
56         GetItemLocation
57         GetLostItems
58         GetItemsForInventory
59         GetItemsCount
60         GetItemInfosOf
61         GetItemsByBiblioitemnumber
62         GetItemsInfo
63         get_itemnumbers_of
64         GetItemnumberFromBarcode
65     );
66 }
67
68 =head1 NAME
69
70 C4::Items - item management functions
71
72 =head1 DESCRIPTION
73
74 This module contains an API for manipulating item 
75 records in Koha, and is used by cataloguing, circulation,
76 acquisitions, and serials management.
77
78 A Koha item record is stored in two places: the
79 items table and embedded in a MARC tag in the XML
80 version of the associated bib record in C<biblioitems.marcxml>.
81 This is done to allow the item information to be readily
82 indexed (e.g., by Zebra), but means that each item
83 modification transaction must keep the items table
84 and the MARC XML in sync at all times.
85
86 Consequently, all code that creates, modifies, or deletes
87 item records B<must> use an appropriate function from 
88 C<C4::Items>.  If no existing function is suitable, it is
89 better to add one to C<C4::Items> than to use add
90 one-off SQL statements to add or modify items.
91
92 The items table will be considered authoritative.  In other
93 words, if there is ever a discrepancy between the items
94 table and the MARC XML, the items table should be considered
95 accurate.
96
97 =head1 HISTORICAL NOTE
98
99 Most of the functions in C<C4::Items> were originally in
100 the C<C4::Biblio> module.
101
102 =head1 CORE EXPORTED FUNCTIONS
103
104 The following functions are meant for use by users
105 of C<C4::Items>
106
107 =cut
108
109 =head2 GetItem
110
111 =over 4
112
113 $item = GetItem($itemnumber,$barcode,$serial);
114
115 =back
116
117 Return item information, for a given itemnumber or barcode.
118 The return value is a hashref mapping item column
119 names to values.  If C<$serial> is true, include serial publication data.
120
121 =cut
122
123 sub GetItem {
124     my ($itemnumber,$barcode, $serial) = @_;
125     my $dbh = C4::Context->dbh;
126         my $data;
127     if ($itemnumber) {
128         my $sth = $dbh->prepare("
129             SELECT * FROM items 
130             WHERE itemnumber = ?");
131         $sth->execute($itemnumber);
132         $data = $sth->fetchrow_hashref;
133     } else {
134         my $sth = $dbh->prepare("
135             SELECT * FROM items 
136             WHERE barcode = ?"
137             );
138         $sth->execute($barcode);                
139         $data = $sth->fetchrow_hashref;
140     }
141     if ( $serial) {      
142     my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
143         $ssth->execute($data->{'itemnumber'}) ;
144         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
145                 warn $data->{'serialseq'} , $data->{'publisheddate'};
146     }
147         #if we don't have an items.itype, use biblioitems.itemtype.
148         if( ! $data->{'itype'} ) {
149                 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
150                 $sth->execute($data->{'biblionumber'});
151                 ($data->{'itype'}) = $sth->fetchrow_array;
152         }
153     return $data;
154 }    # sub GetItem
155
156 =head2 AddItemFromMarc
157
158 =over 4
159
160 my ($biblionumber, $biblioitemnumber, $itemnumber) 
161     = AddItemFromMarc($source_item_marc, $biblionumber);
162
163 =back
164
165 Given a MARC::Record object containing an embedded item
166 record and a biblionumber, create a new item record.
167
168 =cut
169
170 sub AddItemFromMarc {
171     my ( $source_item_marc, $biblionumber ) = @_;
172     my $dbh = C4::Context->dbh;
173
174     # parse item hash from MARC
175     my $frameworkcode = GetFrameworkCode( $biblionumber );
176     my $item = &TransformMarcToKoha( $dbh, $source_item_marc, $frameworkcode );
177     my $unlinked_item_subfields = _get_unlinked_item_subfields($source_item_marc, $frameworkcode);
178     return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
179 }
180
181 =head2 AddItem
182
183 =over 4
184
185 my ($biblionumber, $biblioitemnumber, $itemnumber) 
186     = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
187
188 =back
189
190 Given a hash containing item column names as keys,
191 create a new Koha item record.
192
193 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
194 do not need to be supplied for general use; they exist
195 simply to allow them to be picked up from AddItemFromMarc.
196
197 The final optional parameter, C<$unlinked_item_subfields>, contains
198 an arrayref containing subfields present in the original MARC
199 representation of the item (e.g., from the item editor) that are
200 not mapped to C<items> columns directly but should instead
201 be stored in C<items.more_subfields_xml> and included in 
202 the biblio items tag for display and indexing.
203
204 =cut
205
206 sub AddItem {
207     my $item = shift;
208     my $biblionumber = shift;
209
210     my $dbh           = @_ ? shift : C4::Context->dbh;
211     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
212     my $unlinked_item_subfields;  
213     if (@_) {
214         $unlinked_item_subfields = shift
215     };
216
217     # needs old biblionumber and biblioitemnumber
218     $item->{'biblionumber'} = $biblionumber;
219     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
220     $sth->execute( $item->{'biblionumber'} );
221     ($item->{'biblioitemnumber'}) = $sth->fetchrow;
222
223     _set_defaults_for_add($item);
224     _set_derived_columns_for_add($item);
225     $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
226     # FIXME - checks here
227         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
228     $item->{'itemnumber'} = $itemnumber;
229
230     # create MARC tag representing item and add to bib
231     my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
232     warn "HERE : ".$item->{'biblionumber'};
233     warn "HERE 2 : ".$new_item_marc->as_formatted;
234     _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
235    
236     logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
237     
238     return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
239 }
240
241 =head2 AddItemBatchFromMarc
242
243 =over 4
244
245 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
246
247 =back
248
249 Efficiently create item records from a MARC biblio record with
250 embedded item fields.  This routine is suitable for batch jobs.
251
252 This API assumes that the bib record has already been
253 saved to the C<biblio> and C<biblioitems> tables.  It does
254 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
255 are populated, but it will do so via a call to ModBibiloMarc.
256
257 The goal of this API is to have a similar effect to using AddBiblio
258 and AddItems in succession, but without inefficient repeated
259 parsing of the MARC XML bib record.
260
261 This function returns an arrayref of new itemsnumbers and an arrayref of item
262 errors encountered during the processing.  Each entry in the errors
263 list is a hashref containing the following keys:
264
265 =over 2
266
267 =item item_sequence
268
269 Sequence number of original item tag in the MARC record.
270
271 =item item_barcode
272
273 Item barcode, provide to assist in the construction of
274 useful error messages.
275
276 =item error_condition
277
278 Code representing the error condition.  Can be 'duplicate_barcode',
279 'invalid_homebranch', or 'invalid_holdingbranch'.
280
281 =item error_information
282
283 Additional information appropriate to the error condition.
284
285 =back
286
287 =cut
288
289 sub AddItemBatchFromMarc {
290     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
291     my $error;
292     my @itemnumbers = ();
293     my @errors = ();
294     my $dbh = C4::Context->dbh;
295
296     # loop through the item tags and start creating items
297     my @bad_item_fields = ();
298     my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
299     my $item_sequence_num = 0;
300     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
301         $item_sequence_num++;
302         # we take the item field and stick it into a new
303         # MARC record -- this is required so far because (FIXME)
304         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
305         # and there is no TransformMarcFieldToKoha
306         my $temp_item_marc = MARC::Record->new();
307         $temp_item_marc->append_fields($item_field);
308     
309         # add biblionumber and biblioitemnumber
310         my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
311         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
312         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
313         $item->{'biblionumber'} = $biblionumber;
314         $item->{'biblioitemnumber'} = $biblioitemnumber;
315
316         # check for duplicate barcode
317         my %item_errors = CheckItemPreSave($item);
318         if (%item_errors) {
319             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
320             push @bad_item_fields, $item_field;
321             next ITEMFIELD;
322         }
323
324         _set_defaults_for_add($item);
325         _set_derived_columns_for_add($item);
326         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
327         warn $error if $error;
328         push @itemnumbers, $itemnumber; # FIXME not checking error
329         $item->{'itemnumber'} = $itemnumber;
330
331         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
332
333         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
334         $item_field->replace_with($new_item_marc->field($itemtag));
335     }
336
337     # remove any MARC item fields for rejected items
338     foreach my $item_field (@bad_item_fields) {
339         $record->delete_field($item_field);
340     }
341
342     # update the MARC biblio
343     $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
344
345     return (\@itemnumbers, \@errors);
346 }
347
348 =head2 ModItemFromMarc
349
350 =over 4
351
352 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
353
354 =back
355
356 This function updates an item record based on a supplied
357 C<MARC::Record> object containing an embedded item field.
358 This API is meant for the use of C<additem.pl>; for 
359 other purposes, C<ModItem> should be used.
360
361 =cut
362
363 sub ModItemFromMarc {
364     my $item_marc = shift;
365     my $biblionumber = shift;
366     my $itemnumber = shift;
367
368     my $dbh = C4::Context->dbh;
369     my $frameworkcode = GetFrameworkCode( $biblionumber );
370     my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
371     my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
372    
373     return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields); 
374 }
375
376 =head2 ModItem
377
378 =over 4
379
380 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
381
382 =back
383
384 Change one or more columns in an item record and update
385 the MARC representation of the item.
386
387 The first argument is a hashref mapping from item column
388 names to the new values.  The second and third arguments
389 are the biblionumber and itemnumber, respectively.
390
391 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
392 an arrayref containing subfields present in the original MARC
393 representation of the item (e.g., from the item editor) that are
394 not mapped to C<items> columns directly but should instead
395 be stored in C<items.more_subfields_xml> and included in 
396 the biblio items tag for display and indexing.
397
398 If one of the changed columns is used to calculate
399 the derived value of a column such as C<items.cn_sort>, 
400 this routine will perform the necessary calculation
401 and set the value.
402
403 =cut
404
405 sub ModItem {
406     my $item = shift;
407     my $biblionumber = shift;
408     my $itemnumber = shift;
409
410     # if $biblionumber is undefined, get it from the current item
411     unless (defined $biblionumber) {
412         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
413     }
414
415     my $dbh           = @_ ? shift : C4::Context->dbh;
416     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
417     
418     my $unlinked_item_subfields;  
419     if (@_) {
420         $unlinked_item_subfields = shift;
421         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
422     };
423
424     $item->{'itemnumber'} = $itemnumber or return undef;
425     _set_derived_columns_for_mod($item);
426     _do_column_fixes_for_mod($item);
427     # FIXME add checks
428     # duplicate barcode
429     # attempt to change itemnumber
430     # attempt to change biblionumber (if we want
431     # an API to relink an item to a different bib,
432     # it should be a separate function)
433
434     # update items table
435     _koha_modify_item($item);
436
437     # update biblio MARC XML
438     my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
439
440     unless (defined $unlinked_item_subfields) {
441         $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
442     }
443     my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields) 
444         or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
445     
446     _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
447         ($new_item_marc       eq '0') and die "$new_item_marc is '0', not hashref";  # logaction line would crash anyway
448     logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
449 }
450
451 =head2 ModItemTransfer
452
453 =over 4
454
455 ModItemTransfer($itenumber, $frombranch, $tobranch);
456
457 =back
458
459 Marks an item as being transferred from one branch
460 to another.
461
462 =cut
463
464 sub ModItemTransfer {
465     my ( $itemnumber, $frombranch, $tobranch ) = @_;
466
467     my $dbh = C4::Context->dbh;
468
469     #new entry in branchtransfers....
470     my $sth = $dbh->prepare(
471         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
472         VALUES (?, ?, NOW(), ?)");
473     $sth->execute($itemnumber, $frombranch, $tobranch);
474
475     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
476     ModDateLastSeen($itemnumber);
477     return;
478 }
479
480 =head2 ModDateLastSeen
481
482 =over 4
483
484 ModDateLastSeen($itemnum);
485
486 =back
487
488 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
489 C<$itemnum> is the item number
490
491 =cut
492
493 sub ModDateLastSeen {
494     my ($itemnumber) = @_;
495     
496     my $today = C4::Dates->new();    
497     ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
498 }
499
500 =head2 DelItem
501
502 =over 4
503
504 DelItem($biblionumber, $itemnumber);
505
506 =back
507
508 Exported function (core API) for deleting an item record in Koha.
509
510 =cut
511
512 sub DelItem {
513     my ( $dbh, $biblionumber, $itemnumber ) = @_;
514     
515     # FIXME check the item has no current issues
516     
517     _koha_delete_item( $dbh, $itemnumber );
518
519     # get the MARC record
520     my $record = GetMarcBiblio($biblionumber);
521     my $frameworkcode = GetFrameworkCode($biblionumber);
522
523     # backup the record
524     my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
525     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
526
527     #search item field code
528     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
529     my @fields = $record->field($itemtag);
530
531     # delete the item specified
532     foreach my $field (@fields) {
533         if ( $field->subfield($itemsubfield) eq $itemnumber ) {
534             $record->delete_field($field);
535         }
536     }
537     &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
538     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
539 }
540
541 =head2 CheckItemPreSave
542
543 =over 4
544
545     my $item_ref = TransformMarcToKoha($marc, 'items');
546     # do stuff
547     my %errors = CheckItemPreSave($item_ref);
548     if (exists $errors{'duplicate_barcode'}) {
549         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
550     } elsif (exists $errors{'invalid_homebranch'}) {
551         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
552     } elsif (exists $errors{'invalid_holdingbranch'}) {
553         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
554     } else {
555         print "item is OK";
556     }
557
558 =back
559
560 Given a hashref containing item fields, determine if it can be
561 inserted or updated in the database.  Specifically, checks for
562 database integrity issues, and returns a hash containing any
563 of the following keys, if applicable.
564
565 =over 2
566
567 =item duplicate_barcode
568
569 Barcode, if it duplicates one already found in the database.
570
571 =item invalid_homebranch
572
573 Home branch, if not defined in branches table.
574
575 =item invalid_holdingbranch
576
577 Holding branch, if not defined in branches table.
578
579 =back
580
581 This function does NOT implement any policy-related checks,
582 e.g., whether current operator is allowed to save an
583 item that has a given branch code.
584
585 =cut
586
587 sub CheckItemPreSave {
588     my $item_ref = shift;
589
590     my %errors = ();
591
592     # check for duplicate barcode
593     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
594         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
595         if ($existing_itemnumber) {
596             if (!exists $item_ref->{'itemnumber'}                       # new item
597                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
598                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
599             }
600         }
601     }
602
603     # check for valid home branch
604     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
605         my $branch_name = GetBranchName($item_ref->{'homebranch'});
606         unless (defined $branch_name) {
607             # relies on fact that branches.branchname is a non-NULL column,
608             # so GetBranchName returns undef only if branch does not exist
609             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
610         }
611     }
612
613     # check for valid holding branch
614     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
615         my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
616         unless (defined $branch_name) {
617             # relies on fact that branches.branchname is a non-NULL column,
618             # so GetBranchName returns undef only if branch does not exist
619             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
620         }
621     }
622
623     return %errors;
624
625 }
626
627 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
628
629 The following functions provide various ways of 
630 getting an item record, a set of item records, or
631 lists of authorized values for certain item fields.
632
633 Some of the functions in this group are candidates
634 for refactoring -- for example, some of the code
635 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
636 has copy-and-paste work.
637
638 =cut
639
640 =head2 GetItemStatus
641
642 =over 4
643
644 $itemstatushash = GetItemStatus($fwkcode);
645
646 =back
647
648 Returns a list of valid values for the
649 C<items.notforloan> field.
650
651 NOTE: does B<not> return an individual item's
652 status.
653
654 Can be MARC dependant.
655 fwkcode is optional.
656 But basically could be can be loan or not
657 Create a status selector with the following code
658
659 =head3 in PERL SCRIPT
660
661 =over 4
662
663 my $itemstatushash = getitemstatus;
664 my @itemstatusloop;
665 foreach my $thisstatus (keys %$itemstatushash) {
666     my %row =(value => $thisstatus,
667                 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
668             );
669     push @itemstatusloop, \%row;
670 }
671 $template->param(statusloop=>\@itemstatusloop);
672
673 =back
674
675 =head3 in TEMPLATE
676
677 =over 4
678
679 <select name="statusloop">
680     <option value="">Default</option>
681 <!-- TMPL_LOOP name="statusloop" -->
682     <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
683 <!-- /TMPL_LOOP -->
684 </select>
685
686 =back
687
688 =cut
689
690 sub GetItemStatus {
691
692     # returns a reference to a hash of references to status...
693     my ($fwk) = @_;
694     my %itemstatus;
695     my $dbh = C4::Context->dbh;
696     my $sth;
697     $fwk = '' unless ($fwk);
698     my ( $tag, $subfield ) =
699       GetMarcFromKohaField( "items.notforloan", $fwk );
700     if ( $tag and $subfield ) {
701         my $sth =
702           $dbh->prepare(
703             "SELECT authorised_value
704             FROM marc_subfield_structure
705             WHERE tagfield=?
706                 AND tagsubfield=?
707                 AND frameworkcode=?
708             "
709           );
710         $sth->execute( $tag, $subfield, $fwk );
711         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
712             my $authvalsth =
713               $dbh->prepare(
714                 "SELECT authorised_value,lib
715                 FROM authorised_values 
716                 WHERE category=? 
717                 ORDER BY lib
718                 "
719               );
720             $authvalsth->execute($authorisedvaluecat);
721             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
722                 $itemstatus{$authorisedvalue} = $lib;
723             }
724             $authvalsth->finish;
725             return \%itemstatus;
726             exit 1;
727         }
728         else {
729
730             #No authvalue list
731             # build default
732         }
733         $sth->finish;
734     }
735
736     #No authvalue list
737     #build default
738     $itemstatus{"1"} = "Not For Loan";
739     return \%itemstatus;
740 }
741
742 =head2 GetItemLocation
743
744 =over 4
745
746 $itemlochash = GetItemLocation($fwk);
747
748 =back
749
750 Returns a list of valid values for the
751 C<items.location> field.
752
753 NOTE: does B<not> return an individual item's
754 location.
755
756 where fwk stands for an optional framework code.
757 Create a location selector with the following code
758
759 =head3 in PERL SCRIPT
760
761 =over 4
762
763 my $itemlochash = getitemlocation;
764 my @itemlocloop;
765 foreach my $thisloc (keys %$itemlochash) {
766     my $selected = 1 if $thisbranch eq $branch;
767     my %row =(locval => $thisloc,
768                 selected => $selected,
769                 locname => $itemlochash->{$thisloc},
770             );
771     push @itemlocloop, \%row;
772 }
773 $template->param(itemlocationloop => \@itemlocloop);
774
775 =back
776
777 =head3 in TEMPLATE
778
779 =over 4
780
781 <select name="location">
782     <option value="">Default</option>
783 <!-- TMPL_LOOP name="itemlocationloop" -->
784     <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
785 <!-- /TMPL_LOOP -->
786 </select>
787
788 =back
789
790 =cut
791
792 sub GetItemLocation {
793
794     # returns a reference to a hash of references to location...
795     my ($fwk) = @_;
796     my %itemlocation;
797     my $dbh = C4::Context->dbh;
798     my $sth;
799     $fwk = '' unless ($fwk);
800     my ( $tag, $subfield ) =
801       GetMarcFromKohaField( "items.location", $fwk );
802     if ( $tag and $subfield ) {
803         my $sth =
804           $dbh->prepare(
805             "SELECT authorised_value
806             FROM marc_subfield_structure 
807             WHERE tagfield=? 
808                 AND tagsubfield=? 
809                 AND frameworkcode=?"
810           );
811         $sth->execute( $tag, $subfield, $fwk );
812         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
813             my $authvalsth =
814               $dbh->prepare(
815                 "SELECT authorised_value,lib
816                 FROM authorised_values
817                 WHERE category=?
818                 ORDER BY lib"
819               );
820             $authvalsth->execute($authorisedvaluecat);
821             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
822                 $itemlocation{$authorisedvalue} = $lib;
823             }
824             $authvalsth->finish;
825             return \%itemlocation;
826             exit 1;
827         }
828         else {
829
830             #No authvalue list
831             # build default
832         }
833         $sth->finish;
834     }
835
836     #No authvalue list
837     #build default
838     $itemlocation{"1"} = "Not For Loan";
839     return \%itemlocation;
840 }
841
842 =head2 GetLostItems
843
844 =over 4
845
846 $items = GetLostItems($where,$orderby);
847
848 =back
849
850 This function get the items lost into C<$items>.
851
852 =over 2
853
854 =item input:
855 C<$where> is a hashref. it containts a field of the items table as key
856 and the value to match as value.
857 C<$orderby> is a field of the items table.
858
859 =item return:
860 C<$items> is a reference to an array full of hasref which keys are items' table column.
861
862 =item usage in the perl script:
863
864 my %where;
865 $where{barcode} = 0001548;
866 my $items = GetLostItems( \%where, "homebranch" );
867 $template->param(itemsloop => $items);
868
869 =back
870
871 =cut
872
873 sub GetLostItems {
874     # Getting input args.
875     my $where   = shift;
876     my $orderby = shift;
877     my $dbh     = C4::Context->dbh;
878
879     my $query   = "
880         SELECT *
881         FROM   items, biblio, authorised_values
882         WHERE
883                         items.biblionumber = biblio.biblionumber
884                         AND items.itemlost = authorised_values.authorised_value
885                         AND authorised_values.category = 'LOST'
886                 AND itemlost IS NOT NULL
887                 AND itemlost <> 0
888           
889     ";
890     foreach my $key (keys %$where) {
891         $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
892     }
893     $query .= " ORDER BY ".$orderby." " if defined $orderby;
894
895     my $sth = $dbh->prepare($query);
896     $sth->execute;
897     my @items;
898     while ( my $row = $sth->fetchrow_hashref ){
899         push @items, $row;
900     }
901     return \@items;
902 }
903
904 =head2 GetItemsForInventory
905
906 =over 4
907
908 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
909
910 =back
911
912 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
913
914 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
915 It is ordered by callnumber,title.
916
917 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
918 the datelastseen can be used to specify that you want to see items not seen since a past date only.
919 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
920
921 =cut
922
923 sub GetItemsForInventory {
924     my ( $minlocation, $maxlocation,$location, $itemtype, $datelastseen, $branch, $offset, $size ) = @_;
925     my $dbh = C4::Context->dbh;
926     my $sth;
927     if ($datelastseen) {
928         $datelastseen=format_date_in_iso($datelastseen);  
929         my $query =
930                 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
931                  FROM items
932                    LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
933                    LEFT JOIN biblioitems on items.biblionumber=biblioitems.biblionumber
934                  WHERE itemcallnumber>= ?
935                    AND itemcallnumber <=?
936                    AND (datelastseen< ? OR datelastseen IS NULL)";
937         $query.= " AND items.location=".$dbh->quote($location) if $location;
938         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
939         $query.= " AND biblioitems.itemtype=".$dbh->quote($itemtype) if $itemtype;
940         $query .= " ORDER BY itemcallnumber,title";
941         $sth = $dbh->prepare($query);
942         $sth->execute( $minlocation, $maxlocation, $datelastseen );
943     }
944     else {
945         my $query ="
946                 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
947                 FROM items 
948                     LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber 
949                    LEFT JOIN biblioitems on items.biblionumber=biblioitems.biblionumber
950                 WHERE itemcallnumber>= ?
951                   AND itemcallnumber <=?";
952         $query.= " AND items.location=".$dbh->quote($location) if $location;
953         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
954         $query.= " AND biblioitems.itemtype=".$dbh->quote($itemtype) if $itemtype;
955         $query .= " ORDER BY itemcallnumber,title";
956         $sth = $dbh->prepare($query);
957         $sth->execute( $minlocation, $maxlocation );
958     }
959     my @results;
960     $size--;
961     while ( my $row = $sth->fetchrow_hashref ) {
962         $offset-- if ($offset);
963         $row->{datelastseen}=format_date($row->{datelastseen});
964         if ( ( !$offset ) && $size ) {
965             push @results, $row;
966             $size--;
967         }
968     }
969     return \@results;
970 }
971
972 =head2 GetItemsCount
973
974 =over 4
975 $count = &GetItemsCount( $biblionumber);
976
977 =back
978
979 This function return count of item with $biblionumber
980
981 =cut
982
983 sub GetItemsCount {
984     my ( $biblionumber ) = @_;
985     my $dbh = C4::Context->dbh;
986     my $query = "SELECT count(*)
987           FROM  items 
988           WHERE biblionumber=?";
989     my $sth = $dbh->prepare($query);
990     $sth->execute($biblionumber);
991     my $count = $sth->fetchrow;  
992     $sth->finish;
993     return ($count);
994 }
995
996 =head2 GetItemInfosOf
997
998 =over 4
999
1000 GetItemInfosOf(@itemnumbers);
1001
1002 =back
1003
1004 =cut
1005
1006 sub GetItemInfosOf {
1007     my @itemnumbers = @_;
1008
1009     my $query = '
1010         SELECT *
1011         FROM items
1012         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1013     ';
1014     return get_infos_of( $query, 'itemnumber' );
1015 }
1016
1017 =head2 GetItemsByBiblioitemnumber
1018
1019 =over 4
1020
1021 GetItemsByBiblioitemnumber($biblioitemnumber);
1022
1023 =back
1024
1025 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1026 Called by C<C4::XISBN>
1027
1028 =cut
1029
1030 sub GetItemsByBiblioitemnumber {
1031     my ( $bibitem ) = @_;
1032     my $dbh = C4::Context->dbh;
1033     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1034     # Get all items attached to a biblioitem
1035     my $i = 0;
1036     my @results; 
1037     $sth->execute($bibitem) || die $sth->errstr;
1038     while ( my $data = $sth->fetchrow_hashref ) {  
1039         # Foreach item, get circulation information
1040         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1041                                    WHERE itemnumber = ?
1042                                    AND issues.borrowernumber = borrowers.borrowernumber"
1043         );
1044         $sth2->execute( $data->{'itemnumber'} );
1045         if ( my $data2 = $sth2->fetchrow_hashref ) {
1046             # if item is out, set the due date and who it is out too
1047             $data->{'date_due'}   = $data2->{'date_due'};
1048             $data->{'cardnumber'} = $data2->{'cardnumber'};
1049             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1050         }
1051         else {
1052             # set date_due to blank, so in the template we check itemlost, and wthdrawn 
1053             $data->{'date_due'} = '';                                                                                                         
1054         }    # else         
1055         $sth2->finish;
1056         # Find the last 3 people who borrowed this item.                  
1057         my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1058                       AND old_issues.borrowernumber = borrowers.borrowernumber
1059                       ORDER BY returndate desc,timestamp desc LIMIT 3";
1060         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1061         $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1062         my $i2 = 0;
1063         while ( my $data2 = $sth2->fetchrow_hashref ) {
1064             $data->{"timestamp$i2"} = $data2->{'timestamp'};
1065             $data->{"card$i2"}      = $data2->{'cardnumber'};
1066             $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1067             $i2++;
1068         }
1069         $sth2->finish;
1070         push(@results,$data);
1071     } 
1072     $sth->finish;
1073     return (\@results); 
1074 }
1075
1076 =head2 GetItemsInfo
1077
1078 =over 4
1079
1080 @results = GetItemsInfo($biblionumber, $type);
1081
1082 =back
1083
1084 Returns information about books with the given biblionumber.
1085
1086 C<$type> may be either C<intra> or anything else. If it is not set to
1087 C<intra>, then the search will exclude lost, very overdue, and
1088 withdrawn items.
1089
1090 C<GetItemsInfo> returns a list of references-to-hash. Each element
1091 contains a number of keys. Most of them are table items from the
1092 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1093 Koha database. Other keys include:
1094
1095 =over 2
1096
1097 =item C<$data-E<gt>{branchname}>
1098
1099 The name (not the code) of the branch to which the book belongs.
1100
1101 =item C<$data-E<gt>{datelastseen}>
1102
1103 This is simply C<items.datelastseen>, except that while the date is
1104 stored in YYYY-MM-DD format in the database, here it is converted to
1105 DD/MM/YYYY format. A NULL date is returned as C<//>.
1106
1107 =item C<$data-E<gt>{datedue}>
1108
1109 =item C<$data-E<gt>{class}>
1110
1111 This is the concatenation of C<biblioitems.classification>, the book's
1112 Dewey code, and C<biblioitems.subclass>.
1113
1114 =item C<$data-E<gt>{ocount}>
1115
1116 I think this is the number of copies of the book available.
1117
1118 =item C<$data-E<gt>{order}>
1119
1120 If this is set, it is set to C<One Order>.
1121
1122 =back
1123
1124 =cut
1125
1126 sub GetItemsInfo {
1127     my ( $biblionumber, $type ) = @_;
1128     my $dbh   = C4::Context->dbh;
1129     my $query = "SELECT *,items.notforloan as itemnotforloan
1130                  FROM items 
1131                  LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1132                  LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1133     $query .=  (C4::Context->preference('item-level_itypes')) ?
1134                      " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
1135                     : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
1136     $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1137     my $sth = $dbh->prepare($query);
1138     $sth->execute($biblionumber);
1139     my $i = 0;
1140     my @results;
1141     my ( $date_due, $count_reserves, $serial );
1142
1143     my $isth    = $dbh->prepare(
1144         "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1145         FROM   issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1146         WHERE  itemnumber = ?"
1147        );
1148         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
1149         while ( my $data = $sth->fetchrow_hashref ) {
1150         my $datedue = '';
1151         $isth->execute( $data->{'itemnumber'} );
1152         if ( my $idata = $isth->fetchrow_hashref ) {
1153             $data->{borrowernumber} = $idata->{borrowernumber};
1154             $data->{cardnumber}     = $idata->{cardnumber};
1155             $data->{surname}     = $idata->{surname};
1156             $data->{firstname}     = $idata->{firstname};
1157             $datedue                = $idata->{'date_due'};
1158         if (C4::Context->preference("IndependantBranches")){
1159         my $userenv = C4::Context->userenv;
1160         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) { 
1161             $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1162         }
1163         }
1164         }
1165                 if ( $data->{'serial'}) {       
1166                         $ssth->execute($data->{'itemnumber'}) ;
1167                         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1168                         $serial = 1;
1169         }
1170                 if ( $datedue eq '' ) {
1171             my ( $restype, $reserves ) =
1172               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1173             if ($restype) {
1174                 $count_reserves = $restype;
1175             }
1176         }
1177         $isth->finish;
1178         $ssth->finish;
1179         #get branch information.....
1180         my $bsth = $dbh->prepare(
1181             "SELECT * FROM branches WHERE branchcode = ?
1182         "
1183         );
1184         $bsth->execute( $data->{'holdingbranch'} );
1185         if ( my $bdata = $bsth->fetchrow_hashref ) {
1186             $data->{'branchname'} = $bdata->{'branchname'};
1187         }
1188         $data->{'datedue'}        = $datedue;
1189         $data->{'count_reserves'} = $count_reserves;
1190
1191         # get notforloan complete status if applicable
1192         my $sthnflstatus = $dbh->prepare(
1193             'SELECT authorised_value
1194             FROM   marc_subfield_structure
1195             WHERE  kohafield="items.notforloan"
1196         '
1197         );
1198
1199         $sthnflstatus->execute;
1200         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1201         if ($authorised_valuecode) {
1202             $sthnflstatus = $dbh->prepare(
1203                 "SELECT lib FROM authorised_values
1204                  WHERE  category=?
1205                  AND authorised_value=?"
1206             );
1207             $sthnflstatus->execute( $authorised_valuecode,
1208                 $data->{itemnotforloan} );
1209             my ($lib) = $sthnflstatus->fetchrow;
1210             $data->{notforloanvalue} = $lib;
1211         }
1212
1213         # my stack procedures
1214         my $stackstatus = $dbh->prepare(
1215             'SELECT authorised_value
1216              FROM   marc_subfield_structure
1217              WHERE  kohafield="items.stack"
1218         '
1219         );
1220         $stackstatus->execute;
1221
1222         ($authorised_valuecode) = $stackstatus->fetchrow;
1223         if ($authorised_valuecode) {
1224             $stackstatus = $dbh->prepare(
1225                 "SELECT lib
1226                  FROM   authorised_values
1227                  WHERE  category=?
1228                  AND    authorised_value=?
1229             "
1230             );
1231             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1232             my ($lib) = $stackstatus->fetchrow;
1233             $data->{stack} = $lib;
1234         }
1235         # Find the last 3 people who borrowed this item.
1236         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1237                                     WHERE itemnumber = ?
1238                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1239                                     LIMIT 3");
1240         $sth2->execute($data->{'itemnumber'});
1241         my $ii = 0;
1242         while (my $data2 = $sth2->fetchrow_hashref()) {
1243             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1244             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1245             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1246             $ii++;
1247         }
1248
1249         $results[$i] = $data;
1250         $i++;
1251     }
1252     $sth->finish;
1253         if($serial) {
1254                 return( sort { $b->{'publisheddate'} cmp $a->{'publisheddate'} } @results );
1255         } else {
1256         return (@results);
1257         }
1258 }
1259
1260 =head2 get_itemnumbers_of
1261
1262 =over 4
1263
1264 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1265
1266 =back
1267
1268 Given a list of biblionumbers, return the list of corresponding itemnumbers
1269 for each biblionumber.
1270
1271 Return a reference on a hash where keys are biblionumbers and values are
1272 references on array of itemnumbers.
1273
1274 =cut
1275
1276 sub get_itemnumbers_of {
1277     my @biblionumbers = @_;
1278
1279     my $dbh = C4::Context->dbh;
1280
1281     my $query = '
1282         SELECT itemnumber,
1283             biblionumber
1284         FROM items
1285         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1286     ';
1287     my $sth = $dbh->prepare($query);
1288     $sth->execute(@biblionumbers);
1289
1290     my %itemnumbers_of;
1291
1292     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1293         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1294     }
1295
1296     return \%itemnumbers_of;
1297 }
1298
1299 =head2 GetItemnumberFromBarcode
1300
1301 =over 4
1302
1303 $result = GetItemnumberFromBarcode($barcode);
1304
1305 =back
1306
1307 =cut
1308
1309 sub GetItemnumberFromBarcode {
1310     my ($barcode) = @_;
1311     my $dbh = C4::Context->dbh;
1312
1313     my $rq =
1314       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1315     $rq->execute($barcode);
1316     my ($result) = $rq->fetchrow;
1317     return ($result);
1318 }
1319
1320 =head1 LIMITED USE FUNCTIONS
1321
1322 The following functions, while part of the public API,
1323 are not exported.  This is generally because they are
1324 meant to be used by only one script for a specific
1325 purpose, and should not be used in any other context
1326 without careful thought.
1327
1328 =cut
1329
1330 =head2 GetMarcItem
1331
1332 =over 4
1333
1334 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1335
1336 =back
1337
1338 Returns MARC::Record of the item passed in parameter.
1339 This function is meant for use only in C<cataloguing/additem.pl>,
1340 where it is needed to support that script's MARC-like
1341 editor.
1342
1343 =cut
1344
1345 sub GetMarcItem {
1346     my ( $biblionumber, $itemnumber ) = @_;
1347
1348     # GetMarcItem has been revised so that it does the following:
1349     #  1. Gets the item information from the items table.
1350     #  2. Converts it to a MARC field for storage in the bib record.
1351     #
1352     # The previous behavior was:
1353     #  1. Get the bib record.
1354     #  2. Return the MARC tag corresponding to the item record.
1355     #
1356     # The difference is that one treats the items row as authoritative,
1357     # while the other treats the MARC representation as authoritative
1358     # under certain circumstances.
1359
1360     my $itemrecord = GetItem($itemnumber);
1361
1362     # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1363     # Also, don't emit a subfield if the underlying field is blank.
1364     my $mungeditem = { map {  $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  } keys %{ $itemrecord } };
1365     my $itemmarc = TransformKohaToMarc($mungeditem);
1366
1367     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1368     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1369         my @fields = $itemmarc->fields();
1370         if ($#fields > -1) {
1371             $fields[0]->add_subfields(@$unlinked_item_subfields);
1372         }
1373     }
1374     
1375     return $itemmarc;
1376
1377 }
1378
1379 =head1 PRIVATE FUNCTIONS AND VARIABLES
1380
1381 The following functions are not meant to be called
1382 directly, but are documented in order to explain
1383 the inner workings of C<C4::Items>.
1384
1385 =cut
1386
1387 =head2 %derived_columns
1388
1389 This hash keeps track of item columns that
1390 are strictly derived from other columns in
1391 the item record and are not meant to be set
1392 independently.
1393
1394 Each key in the hash should be the name of a
1395 column (as named by TransformMarcToKoha).  Each
1396 value should be hashref whose keys are the
1397 columns on which the derived column depends.  The
1398 hashref should also contain a 'BUILDER' key
1399 that is a reference to a sub that calculates
1400 the derived value.
1401
1402 =cut
1403
1404 my %derived_columns = (
1405     'items.cn_sort' => {
1406         'itemcallnumber' => 1,
1407         'items.cn_source' => 1,
1408         'BUILDER' => \&_calc_items_cn_sort,
1409     }
1410 );
1411
1412 =head2 _set_derived_columns_for_add 
1413
1414 =over 4
1415
1416 _set_derived_column_for_add($item);
1417
1418 =back
1419
1420 Given an item hash representing a new item to be added,
1421 calculate any derived columns.  Currently the only
1422 such column is C<items.cn_sort>.
1423
1424 =cut
1425
1426 sub _set_derived_columns_for_add {
1427     my $item = shift;
1428
1429     foreach my $column (keys %derived_columns) {
1430         my $builder = $derived_columns{$column}->{'BUILDER'};
1431         my $source_values = {};
1432         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1433             next if $source_column eq 'BUILDER';
1434             $source_values->{$source_column} = $item->{$source_column};
1435         }
1436         $builder->($item, $source_values);
1437     }
1438 }
1439
1440 =head2 _set_derived_columns_for_mod 
1441
1442 =over 4
1443
1444 _set_derived_column_for_mod($item);
1445
1446 =back
1447
1448 Given an item hash representing a new item to be modified.
1449 calculate any derived columns.  Currently the only
1450 such column is C<items.cn_sort>.
1451
1452 This routine differs from C<_set_derived_columns_for_add>
1453 in that it needs to handle partial item records.  In other
1454 words, the caller of C<ModItem> may have supplied only one
1455 or two columns to be changed, so this function needs to
1456 determine whether any of the columns to be changed affect
1457 any of the derived columns.  Also, if a derived column
1458 depends on more than one column, but the caller is not
1459 changing all of then, this routine retrieves the unchanged
1460 values from the database in order to ensure a correct
1461 calculation.
1462
1463 =cut
1464
1465 sub _set_derived_columns_for_mod {
1466     my $item = shift;
1467
1468     foreach my $column (keys %derived_columns) {
1469         my $builder = $derived_columns{$column}->{'BUILDER'};
1470         my $source_values = {};
1471         my %missing_sources = ();
1472         my $must_recalc = 0;
1473         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1474             next if $source_column eq 'BUILDER';
1475             if (exists $item->{$source_column}) {
1476                 $must_recalc = 1;
1477                 $source_values->{$source_column} = $item->{$source_column};
1478             } else {
1479                 $missing_sources{$source_column} = 1;
1480             }
1481         }
1482         if ($must_recalc) {
1483             foreach my $source_column (keys %missing_sources) {
1484                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1485             }
1486             $builder->($item, $source_values);
1487         }
1488     }
1489 }
1490
1491 =head2 _do_column_fixes_for_mod
1492
1493 =over 4
1494
1495 _do_column_fixes_for_mod($item);
1496
1497 =back
1498
1499 Given an item hashref containing one or more
1500 columns to modify, fix up certain values.
1501 Specifically, set to 0 any passed value
1502 of C<notforloan>, C<damaged>, C<itemlost>, or
1503 C<wthdrawn> that is either undefined or
1504 contains the empty string.
1505
1506 =cut
1507
1508 sub _do_column_fixes_for_mod {
1509     my $item = shift;
1510
1511     if (exists $item->{'notforloan'} and
1512         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1513         $item->{'notforloan'} = 0;
1514     }
1515     if (exists $item->{'damaged'} and
1516         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1517         $item->{'damaged'} = 0;
1518     }
1519     if (exists $item->{'itemlost'} and
1520         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1521         $item->{'itemlost'} = 0;
1522     }
1523     if (exists $item->{'wthdrawn'} and
1524         (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1525         $item->{'wthdrawn'} = 0;
1526     }
1527 }
1528
1529 =head2 _get_single_item_column
1530
1531 =over 4
1532
1533 _get_single_item_column($column, $itemnumber);
1534
1535 =back
1536
1537 Retrieves the value of a single column from an C<items>
1538 row specified by C<$itemnumber>.
1539
1540 =cut
1541
1542 sub _get_single_item_column {
1543     my $column = shift;
1544     my $itemnumber = shift;
1545     
1546     my $dbh = C4::Context->dbh;
1547     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1548     $sth->execute($itemnumber);
1549     my ($value) = $sth->fetchrow();
1550     return $value; 
1551 }
1552
1553 =head2 _calc_items_cn_sort
1554
1555 =over 4
1556
1557 _calc_items_cn_sort($item, $source_values);
1558
1559 =back
1560
1561 Helper routine to calculate C<items.cn_sort>.
1562
1563 =cut
1564
1565 sub _calc_items_cn_sort {
1566     my $item = shift;
1567     my $source_values = shift;
1568
1569     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1570 }
1571
1572 =head2 _set_defaults_for_add 
1573
1574 =over 4
1575
1576 _set_defaults_for_add($item_hash);
1577
1578 =back
1579
1580 Given an item hash representing an item to be added, set
1581 correct default values for columns whose default value
1582 is not handled by the DBMS.  This includes the following
1583 columns:
1584
1585 =over 2
1586
1587 =item * 
1588
1589 C<items.dateaccessioned>
1590
1591 =item *
1592
1593 C<items.notforloan>
1594
1595 =item *
1596
1597 C<items.damaged>
1598
1599 =item *
1600
1601 C<items.itemlost>
1602
1603 =item *
1604
1605 C<items.wthdrawn>
1606
1607 =back
1608
1609 =cut
1610
1611 sub _set_defaults_for_add {
1612     my $item = shift;
1613
1614     # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1615     if (!(exists $item->{'dateaccessioned'}) || 
1616          ($item->{'dateaccessioned'} eq '')) {
1617         # FIXME add check for invalid date
1618         my $today = C4::Dates->new();    
1619         $item->{'dateaccessioned'} =  $today->output("iso"); #TODO: check time issues
1620     }
1621
1622     # various item status fields cannot be null
1623     $item->{'notforloan'} = 0 unless exists $item->{'notforloan'} and defined $item->{'notforloan'} and $item->{'notforloan'} ne '';
1624     $item->{'damaged'}    = 0 unless exists $item->{'damaged'}    and defined $item->{'damaged'}    and $item->{'damaged'} ne '';
1625     $item->{'itemlost'}   = 0 unless exists $item->{'itemlost'}   and defined $item->{'itemlost'}   and $item->{'itemlost'} ne '';
1626     $item->{'wthdrawn'}   = 0 unless exists $item->{'wthdrawn'}   and defined $item->{'wthdrawn'}   and $item->{'wthdrawn'} ne '';
1627 }
1628
1629 =head2 _koha_new_item
1630
1631 =over 4
1632
1633 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1634
1635 =back
1636
1637 Perform the actual insert into the C<items> table.
1638
1639 =cut
1640
1641 sub _koha_new_item {
1642     my ( $item, $barcode ) = @_;
1643     my $dbh=C4::Context->dbh;  
1644     my $error;
1645     my $query =
1646            "INSERT INTO items SET
1647             biblionumber        = ?,
1648             biblioitemnumber    = ?,
1649             barcode             = ?,
1650             dateaccessioned     = ?,
1651             booksellerid        = ?,
1652             homebranch          = ?,
1653             price               = ?,
1654             replacementprice    = ?,
1655             replacementpricedate = NOW(),
1656             datelastborrowed    = ?,
1657             datelastseen        = NOW(),
1658             stack               = ?,
1659             notforloan          = ?,
1660             damaged             = ?,
1661             itemlost            = ?,
1662             wthdrawn            = ?,
1663             itemcallnumber      = ?,
1664             restricted          = ?,
1665             itemnotes           = ?,
1666             holdingbranch       = ?,
1667             paidfor             = ?,
1668             location            = ?,
1669             onloan              = ?,
1670             issues              = ?,
1671             renewals            = ?,
1672             reserves            = ?,
1673             cn_source           = ?,
1674             cn_sort             = ?,
1675             ccode               = ?,
1676             itype               = ?,
1677             materials           = ?,
1678                         uri                 = ?,
1679             enumchron           = ?,
1680                         more_subfields_xml  = ?
1681           ";
1682     my $sth = $dbh->prepare($query);
1683    $sth->execute(
1684             $item->{'biblionumber'},
1685             $item->{'biblioitemnumber'},
1686             $barcode,
1687             $item->{'dateaccessioned'},
1688             $item->{'booksellerid'},
1689             $item->{'homebranch'},
1690             $item->{'price'},
1691             $item->{'replacementprice'},
1692             $item->{datelastborrowed},
1693             $item->{stack},
1694             $item->{'notforloan'},
1695             $item->{'damaged'},
1696             $item->{'itemlost'},
1697             $item->{'wthdrawn'},
1698             $item->{'itemcallnumber'},
1699             $item->{'restricted'},
1700             $item->{'itemnotes'},
1701             $item->{'holdingbranch'},
1702             $item->{'paidfor'},
1703             $item->{'location'},
1704             $item->{'onloan'},
1705             $item->{'issues'},
1706             $item->{'renewals'},
1707             $item->{'reserves'},
1708             $item->{'items.cn_source'},
1709             $item->{'items.cn_sort'},
1710             $item->{'ccode'},
1711             $item->{'itype'},
1712             $item->{'materials'},
1713             $item->{'uri'},
1714             $item->{'enumchron'},
1715                         $item->{'more_subfields_xml'},
1716     );
1717     my $itemnumber = $dbh->{'mysql_insertid'};
1718     if ( defined $sth->errstr ) {
1719         $error.="ERROR in _koha_new_item $query".$sth->errstr;
1720     }
1721     $sth->finish();
1722     return ( $itemnumber, $error );
1723 }
1724
1725 =head2 _koha_modify_item
1726
1727 =over 4
1728
1729 my ($itemnumber,$error) =_koha_modify_item( $item );
1730
1731 =back
1732
1733 Perform the actual update of the C<items> row.  Note that this
1734 routine accepts a hashref specifying the columns to update.
1735
1736 =cut
1737
1738 sub _koha_modify_item {
1739     my ( $item ) = @_;
1740     my $dbh=C4::Context->dbh;  
1741     my $error;
1742
1743     my $query = "UPDATE items SET ";
1744     my @bind;
1745     for my $key ( keys %$item ) {
1746         $query.="$key=?,";
1747         push @bind, $item->{$key};
1748     }
1749     $query =~ s/,$//;
1750     $query .= " WHERE itemnumber=?";
1751     push @bind, $item->{'itemnumber'};
1752     my $sth = C4::Context->dbh->prepare($query);
1753     $sth->execute(@bind);
1754     if ( C4::Context->dbh->errstr ) {
1755         $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1756         warn $error;
1757     }
1758     $sth->finish();
1759     return ($item->{'itemnumber'},$error);
1760 }
1761
1762 =head2 _koha_delete_item
1763
1764 =over 4
1765
1766 _koha_delete_item( $dbh, $itemnum );
1767
1768 =back
1769
1770 Internal function to delete an item record from the koha tables
1771
1772 =cut
1773
1774 sub _koha_delete_item {
1775     my ( $dbh, $itemnum ) = @_;
1776
1777     # save the deleted item to deleteditems table
1778     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1779     $sth->execute($itemnum);
1780     my $data = $sth->fetchrow_hashref();
1781     $sth->finish();
1782     my $query = "INSERT INTO deleteditems SET ";
1783     my @bind  = ();
1784     foreach my $key ( keys %$data ) {
1785         $query .= "$key = ?,";
1786         push( @bind, $data->{$key} );
1787     }
1788     $query =~ s/\,$//;
1789     $sth = $dbh->prepare($query);
1790     $sth->execute(@bind);
1791     $sth->finish();
1792
1793     # delete from items table
1794     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1795     $sth->execute($itemnum);
1796     $sth->finish();
1797     return undef;
1798 }
1799
1800 =head2 _marc_from_item_hash
1801
1802 =over 4
1803
1804 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1805
1806 =back
1807
1808 Given an item hash representing a complete item record,
1809 create a C<MARC::Record> object containing an embedded
1810 tag representing that item.
1811
1812 The third, optional parameter C<$unlinked_item_subfields> is
1813 an arrayref of subfields (not mapped to C<items> fields per the
1814 framework) to be added to the MARC representation
1815 of the item.
1816
1817 =cut
1818
1819 sub _marc_from_item_hash {
1820     my $item = shift;
1821     my $frameworkcode = shift;
1822     my $unlinked_item_subfields;
1823     if (@_) {
1824         $unlinked_item_subfields = shift;
1825     }
1826    
1827     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1828     # Also, don't emit a subfield if the underlying field is blank.
1829     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
1830                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
1831                                 : ()  } keys %{ $item } }; 
1832
1833     my $item_marc = MARC::Record->new();
1834     foreach my $item_field (keys %{ $mungeditem }) {
1835         my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
1836         next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1837         if (my $field = $item_marc->field($tag)) {
1838             $field->add_subfields($subfield => $mungeditem->{$item_field});
1839         } else {
1840             my $add_subfields = [];
1841             if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1842                 $add_subfields = $unlinked_item_subfields;
1843             }
1844             $item_marc->add_fields( $tag, " ", " ", $subfield =>  $mungeditem->{$item_field}, @$add_subfields);
1845         }
1846     }
1847
1848     return $item_marc;
1849 }
1850
1851 =head2 _add_item_field_to_biblio
1852
1853 =over 4
1854
1855 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
1856
1857 =back
1858
1859 Adds the fields from a MARC record containing the
1860 representation of a Koha item record to the MARC
1861 biblio record.  The input C<$item_marc> record
1862 is expect to contain just one field, the embedded
1863 item information field.
1864
1865 =cut
1866
1867 sub _add_item_field_to_biblio {
1868     my ($item_marc, $biblionumber, $frameworkcode) = @_;
1869
1870     my $biblio_marc = GetMarcBiblio($biblionumber);
1871     foreach my $field ($item_marc->fields()) {
1872         $biblio_marc->append_fields($field);
1873     }
1874
1875     ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
1876 }
1877
1878 =head2 _replace_item_field_in_biblio
1879
1880 =over
1881
1882 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
1883
1884 =back
1885
1886 Given a MARC::Record C<$item_marc> containing one tag with the MARC 
1887 representation of the item, examine the biblio MARC
1888 for the corresponding tag for that item and 
1889 replace it with the tag from C<$item_marc>.
1890
1891 =cut
1892
1893 sub _replace_item_field_in_biblio {
1894     my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
1895     my $dbh = C4::Context->dbh;
1896     
1897     # get complete MARC record & replace the item field by the new one
1898     my $completeRecord = GetMarcBiblio($biblionumber);
1899     my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
1900     my $itemField = $ItemRecord->field($itemtag);
1901     my @items = $completeRecord->field($itemtag);
1902     my $found = 0;
1903     foreach (@items) {
1904         if ($_->subfield($itemsubfield) eq $itemnumber) {
1905             $_->replace_with($itemField);
1906             $found = 1;
1907         }
1908     }
1909   
1910     unless ($found) { 
1911         # If we haven't found the matching field,
1912         # just add it.  However, this means that
1913         # there is likely a bug.
1914         $completeRecord->append_fields($itemField);
1915     }
1916
1917     # save the record
1918     ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
1919 }
1920
1921 =head2 _repack_item_errors
1922
1923 Add an error message hash generated by C<CheckItemPreSave>
1924 to a list of errors.
1925
1926 =cut
1927
1928 sub _repack_item_errors {
1929     my $item_sequence_num = shift;
1930     my $item_ref = shift;
1931     my $error_ref = shift;
1932
1933     my @repacked_errors = ();
1934
1935     foreach my $error_code (sort keys %{ $error_ref }) {
1936         my $repacked_error = {};
1937         $repacked_error->{'item_sequence'} = $item_sequence_num;
1938         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
1939         $repacked_error->{'error_code'} = $error_code;
1940         $repacked_error->{'error_information'} = $error_ref->{$error_code};
1941         push @repacked_errors, $repacked_error;
1942     } 
1943
1944     return @repacked_errors;
1945 }
1946
1947 =head2 _get_unlinked_item_subfields
1948
1949 =over 4
1950
1951 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
1952
1953 =back
1954
1955 =cut
1956
1957 sub _get_unlinked_item_subfields {
1958     my $original_item_marc = shift;
1959     my $frameworkcode = shift;
1960
1961     my $marcstructure = GetMarcStructure(1, $frameworkcode);
1962
1963     # assume that this record has only one field, and that that
1964     # field contains only the item information
1965     my $subfields = [];
1966     my @fields = $original_item_marc->fields();
1967     if ($#fields > -1) {
1968         my $field = $fields[0];
1969             my $tag = $field->tag();
1970         foreach my $subfield ($field->subfields()) {
1971             if (defined $subfield->[1] and
1972                 $subfield->[1] ne '' and
1973                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
1974                 push @$subfields, $subfield->[0] => $subfield->[1];
1975             }
1976         }
1977     }
1978     return $subfields;
1979 }
1980
1981 =head2 _get_unlinked_subfields_xml
1982
1983 =over 4
1984
1985 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
1986
1987 =back
1988
1989 =cut
1990
1991 sub _get_unlinked_subfields_xml {
1992     my $unlinked_item_subfields = shift;
1993
1994     my $xml;
1995     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1996         my $marc = MARC::Record->new();
1997         # use of tag 999 is arbitrary, and doesn't need to match the item tag
1998         # used in the framework
1999         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2000         $marc->encoding("UTF-8");    
2001         $xml = $marc->as_xml("USMARC");
2002     }
2003
2004     return $xml;
2005 }
2006
2007 =head2 _parse_unlinked_item_subfields_from_xml
2008
2009 =over 4
2010
2011 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2012
2013 =back
2014
2015 =cut
2016
2017 sub  _parse_unlinked_item_subfields_from_xml {
2018     my $xml = shift;
2019
2020     return unless defined $xml and $xml ne "";
2021     my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2022     my $unlinked_subfields = [];
2023     my @fields = $marc->fields();
2024     if ($#fields > -1) {
2025         foreach my $subfield ($fields[0]->subfields()) {
2026             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2027         }
2028     }
2029     return $unlinked_subfields;
2030 }
2031
2032 1;