Add Local-use statistical patron category_type
[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     _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
233    
234     logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item") 
235         if C4::Context->preference("CataloguingLog");
236     
237     return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
238 }
239
240 =head2 AddItemBatchFromMarc
241
242 =over 4
243
244 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
245
246 =back
247
248 Efficiently create item records from a MARC biblio record with
249 embedded item fields.  This routine is suitable for batch jobs.
250
251 This API assumes that the bib record has already been
252 saved to the C<biblio> and C<biblioitems> tables.  It does
253 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
254 are populated, but it will do so via a call to ModBibiloMarc.
255
256 The goal of this API is to have a similar effect to using AddBiblio
257 and AddItems in succession, but without inefficient repeated
258 parsing of the MARC XML bib record.
259
260 This function returns an arrayref of new itemsnumbers and an arrayref of item
261 errors encountered during the processing.  Each entry in the errors
262 list is a hashref containing the following keys:
263
264 =over 2
265
266 =item item_sequence
267
268 Sequence number of original item tag in the MARC record.
269
270 =item item_barcode
271
272 Item barcode, provide to assist in the construction of
273 useful error messages.
274
275 =item error_condition
276
277 Code representing the error condition.  Can be 'duplicate_barcode',
278 'invalid_homebranch', or 'invalid_holdingbranch'.
279
280 =item error_information
281
282 Additional information appropriate to the error condition.
283
284 =back
285
286 =cut
287
288 sub AddItemBatchFromMarc {
289     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
290     my $error;
291     my @itemnumbers = ();
292     my @errors = ();
293     my $dbh = C4::Context->dbh;
294
295     # loop through the item tags and start creating items
296     my @bad_item_fields = ();
297     my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
298     my $item_sequence_num = 0;
299     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
300         $item_sequence_num++;
301         # we take the item field and stick it into a new
302         # MARC record -- this is required so far because (FIXME)
303         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
304         # and there is no TransformMarcFieldToKoha
305         my $temp_item_marc = MARC::Record->new();
306         $temp_item_marc->append_fields($item_field);
307     
308         # add biblionumber and biblioitemnumber
309         my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
310         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
311         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
312         $item->{'biblionumber'} = $biblionumber;
313         $item->{'biblioitemnumber'} = $biblioitemnumber;
314
315         # check for duplicate barcode
316         my %item_errors = CheckItemPreSave($item);
317         if (%item_errors) {
318             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
319             push @bad_item_fields, $item_field;
320             next ITEMFIELD;
321         }
322
323         _set_defaults_for_add($item);
324         _set_derived_columns_for_add($item);
325         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
326         warn $error if $error;
327         push @itemnumbers, $itemnumber; # FIXME not checking error
328         $item->{'itemnumber'} = $itemnumber;
329
330         &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
331         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         (C4::Context->userenv eq '0') and die "userenv is '0', not hashref";         # logaction line would crash anyway
448         ($new_item_marc       eq '0') and die "$new_item_marc is '0', not hashref";  # logaction line would crash anyway
449     logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$new_item_marc->as_formatted)
450         if C4::Context->preference("CataloguingLog");
451 }
452
453 =head2 ModItemTransfer
454
455 =over 4
456
457 ModItemTransfer($itenumber, $frombranch, $tobranch);
458
459 =back
460
461 Marks an item as being transferred from one branch
462 to another.
463
464 =cut
465
466 sub ModItemTransfer {
467     my ( $itemnumber, $frombranch, $tobranch ) = @_;
468
469     my $dbh = C4::Context->dbh;
470
471     #new entry in branchtransfers....
472     my $sth = $dbh->prepare(
473         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
474         VALUES (?, ?, NOW(), ?)");
475     $sth->execute($itemnumber, $frombranch, $tobranch);
476
477     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
478     ModDateLastSeen($itemnumber);
479     return;
480 }
481
482 =head2 ModDateLastSeen
483
484 =over 4
485
486 ModDateLastSeen($itemnum);
487
488 =back
489
490 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
491 C<$itemnum> is the item number
492
493 =cut
494
495 sub ModDateLastSeen {
496     my ($itemnumber) = @_;
497     
498     my $today = C4::Dates->new();    
499     ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
500 }
501
502 =head2 DelItem
503
504 =over 4
505
506 DelItem($biblionumber, $itemnumber);
507
508 =back
509
510 Exported function (core API) for deleting an item record in Koha.
511
512 =cut
513
514 sub DelItem {
515     my ( $dbh, $biblionumber, $itemnumber ) = @_;
516     
517     # FIXME check the item has no current issues
518     
519     _koha_delete_item( $dbh, $itemnumber );
520
521     # get the MARC record
522     my $record = GetMarcBiblio($biblionumber);
523     my $frameworkcode = GetFrameworkCode($biblionumber);
524
525     # backup the record
526     my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
527     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
528
529     #search item field code
530     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
531     my @fields = $record->field($itemtag);
532
533     # delete the item specified
534     foreach my $field (@fields) {
535         if ( $field->subfield($itemsubfield) eq $itemnumber ) {
536             $record->delete_field($field);
537         }
538     }
539     &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
540     &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item") 
541         if C4::Context->preference("CataloguingLog");
542 }
543
544 =head2 CheckItemPreSave
545
546 =over 4
547
548     my $item_ref = TransformMarcToKoha($marc, 'items');
549     # do stuff
550     my %errors = CheckItemPreSave($item_ref);
551     if (exists $errors{'duplicate_barcode'}) {
552         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
553     } elsif (exists $errors{'invalid_homebranch'}) {
554         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
555     } elsif (exists $errors{'invalid_holdingbranch'}) {
556         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
557     } else {
558         print "item is OK";
559     }
560
561 =back
562
563 Given a hashref containing item fields, determine if it can be
564 inserted or updated in the database.  Specifically, checks for
565 database integrity issues, and returns a hash containing any
566 of the following keys, if applicable.
567
568 =over 2
569
570 =item duplicate_barcode
571
572 Barcode, if it duplicates one already found in the database.
573
574 =item invalid_homebranch
575
576 Home branch, if not defined in branches table.
577
578 =item invalid_holdingbranch
579
580 Holding branch, if not defined in branches table.
581
582 =back
583
584 This function does NOT implement any policy-related checks,
585 e.g., whether current operator is allowed to save an
586 item that has a given branch code.
587
588 =cut
589
590 sub CheckItemPreSave {
591     my $item_ref = shift;
592
593     my %errors = ();
594
595     # check for duplicate barcode
596     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
597         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
598         if ($existing_itemnumber) {
599             if (!exists $item_ref->{'itemnumber'}                       # new item
600                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
601                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
602             }
603         }
604     }
605
606     # check for valid home branch
607     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
608         my $branch_name = GetBranchName($item_ref->{'homebranch'});
609         unless (defined $branch_name) {
610             # relies on fact that branches.branchname is a non-NULL column,
611             # so GetBranchName returns undef only if branch does not exist
612             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
613         }
614     }
615
616     # check for valid holding branch
617     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
618         my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
619         unless (defined $branch_name) {
620             # relies on fact that branches.branchname is a non-NULL column,
621             # so GetBranchName returns undef only if branch does not exist
622             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
623         }
624     }
625
626     return %errors;
627
628 }
629
630 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
631
632 The following functions provide various ways of 
633 getting an item record, a set of item records, or
634 lists of authorized values for certain item fields.
635
636 Some of the functions in this group are candidates
637 for refactoring -- for example, some of the code
638 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
639 has copy-and-paste work.
640
641 =cut
642
643 =head2 GetItemStatus
644
645 =over 4
646
647 $itemstatushash = GetItemStatus($fwkcode);
648
649 =back
650
651 Returns a list of valid values for the
652 C<items.notforloan> field.
653
654 NOTE: does B<not> return an individual item's
655 status.
656
657 Can be MARC dependant.
658 fwkcode is optional.
659 But basically could be can be loan or not
660 Create a status selector with the following code
661
662 =head3 in PERL SCRIPT
663
664 =over 4
665
666 my $itemstatushash = getitemstatus;
667 my @itemstatusloop;
668 foreach my $thisstatus (keys %$itemstatushash) {
669     my %row =(value => $thisstatus,
670                 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
671             );
672     push @itemstatusloop, \%row;
673 }
674 $template->param(statusloop=>\@itemstatusloop);
675
676 =back
677
678 =head3 in TEMPLATE
679
680 =over 4
681
682 <select name="statusloop">
683     <option value="">Default</option>
684 <!-- TMPL_LOOP name="statusloop" -->
685     <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
686 <!-- /TMPL_LOOP -->
687 </select>
688
689 =back
690
691 =cut
692
693 sub GetItemStatus {
694
695     # returns a reference to a hash of references to status...
696     my ($fwk) = @_;
697     my %itemstatus;
698     my $dbh = C4::Context->dbh;
699     my $sth;
700     $fwk = '' unless ($fwk);
701     my ( $tag, $subfield ) =
702       GetMarcFromKohaField( "items.notforloan", $fwk );
703     if ( $tag and $subfield ) {
704         my $sth =
705           $dbh->prepare(
706             "SELECT authorised_value
707             FROM marc_subfield_structure
708             WHERE tagfield=?
709                 AND tagsubfield=?
710                 AND frameworkcode=?
711             "
712           );
713         $sth->execute( $tag, $subfield, $fwk );
714         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
715             my $authvalsth =
716               $dbh->prepare(
717                 "SELECT authorised_value,lib
718                 FROM authorised_values 
719                 WHERE category=? 
720                 ORDER BY lib
721                 "
722               );
723             $authvalsth->execute($authorisedvaluecat);
724             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
725                 $itemstatus{$authorisedvalue} = $lib;
726             }
727             $authvalsth->finish;
728             return \%itemstatus;
729             exit 1;
730         }
731         else {
732
733             #No authvalue list
734             # build default
735         }
736         $sth->finish;
737     }
738
739     #No authvalue list
740     #build default
741     $itemstatus{"1"} = "Not For Loan";
742     return \%itemstatus;
743 }
744
745 =head2 GetItemLocation
746
747 =over 4
748
749 $itemlochash = GetItemLocation($fwk);
750
751 =back
752
753 Returns a list of valid values for the
754 C<items.location> field.
755
756 NOTE: does B<not> return an individual item's
757 location.
758
759 where fwk stands for an optional framework code.
760 Create a location selector with the following code
761
762 =head3 in PERL SCRIPT
763
764 =over 4
765
766 my $itemlochash = getitemlocation;
767 my @itemlocloop;
768 foreach my $thisloc (keys %$itemlochash) {
769     my $selected = 1 if $thisbranch eq $branch;
770     my %row =(locval => $thisloc,
771                 selected => $selected,
772                 locname => $itemlochash->{$thisloc},
773             );
774     push @itemlocloop, \%row;
775 }
776 $template->param(itemlocationloop => \@itemlocloop);
777
778 =back
779
780 =head3 in TEMPLATE
781
782 =over 4
783
784 <select name="location">
785     <option value="">Default</option>
786 <!-- TMPL_LOOP name="itemlocationloop" -->
787     <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
788 <!-- /TMPL_LOOP -->
789 </select>
790
791 =back
792
793 =cut
794
795 sub GetItemLocation {
796
797     # returns a reference to a hash of references to location...
798     my ($fwk) = @_;
799     my %itemlocation;
800     my $dbh = C4::Context->dbh;
801     my $sth;
802     $fwk = '' unless ($fwk);
803     my ( $tag, $subfield ) =
804       GetMarcFromKohaField( "items.location", $fwk );
805     if ( $tag and $subfield ) {
806         my $sth =
807           $dbh->prepare(
808             "SELECT authorised_value
809             FROM marc_subfield_structure 
810             WHERE tagfield=? 
811                 AND tagsubfield=? 
812                 AND frameworkcode=?"
813           );
814         $sth->execute( $tag, $subfield, $fwk );
815         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
816             my $authvalsth =
817               $dbh->prepare(
818                 "SELECT authorised_value,lib
819                 FROM authorised_values
820                 WHERE category=?
821                 ORDER BY lib"
822               );
823             $authvalsth->execute($authorisedvaluecat);
824             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
825                 $itemlocation{$authorisedvalue} = $lib;
826             }
827             $authvalsth->finish;
828             return \%itemlocation;
829             exit 1;
830         }
831         else {
832
833             #No authvalue list
834             # build default
835         }
836         $sth->finish;
837     }
838
839     #No authvalue list
840     #build default
841     $itemlocation{"1"} = "Not For Loan";
842     return \%itemlocation;
843 }
844
845 =head2 GetLostItems
846
847 =over 4
848
849 $items = GetLostItems($where,$orderby);
850
851 =back
852
853 This function get the items lost into C<$items>.
854
855 =over 2
856
857 =item input:
858 C<$where> is a hashref. it containts a field of the items table as key
859 and the value to match as value.
860 C<$orderby> is a field of the items table.
861
862 =item return:
863 C<$items> is a reference to an array full of hasref which keys are items' table column.
864
865 =item usage in the perl script:
866
867 my %where;
868 $where{barcode} = 0001548;
869 my $items = GetLostItems( \%where, "homebranch" );
870 $template->param(itemsloop => $items);
871
872 =back
873
874 =cut
875
876 sub GetLostItems {
877     # Getting input args.
878     my $where   = shift;
879     my $orderby = shift;
880     my $dbh     = C4::Context->dbh;
881
882     my $query   = "
883         SELECT *
884         FROM   items
885         WHERE  itemlost IS NOT NULL
886           AND  itemlost <> 0
887     ";
888     foreach my $key (keys %$where) {
889         $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
890     }
891     $query .= " ORDER BY ".$orderby if defined $orderby;
892
893     my $sth = $dbh->prepare($query);
894     $sth->execute;
895     my @items;
896     while ( my $row = $sth->fetchrow_hashref ){
897         push @items, $row;
898     }
899     return \@items;
900 }
901
902 =head2 GetItemsForInventory
903
904 =over 4
905
906 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
907
908 =back
909
910 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
911
912 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
913 It is ordered by callnumber,title.
914
915 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
916 the datelastseen can be used to specify that you want to see items not seen since a past date only.
917 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
918
919 =cut
920
921 sub GetItemsForInventory {
922     my ( $minlocation, $maxlocation,$location, $itemtype, $datelastseen, $branch, $offset, $size ) = @_;
923     my $dbh = C4::Context->dbh;
924     my $sth;
925     if ($datelastseen) {
926         $datelastseen=format_date_in_iso($datelastseen);  
927         my $query =
928                 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
929                  FROM items
930                    LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
931                    LEFT JOIN biblioitems on items.biblionumber=biblioitems.biblionumber
932                  WHERE itemcallnumber>= ?
933                    AND itemcallnumber <=?
934                    AND (datelastseen< ? OR datelastseen IS NULL)";
935         $query.= " AND items.location=".$dbh->quote($location) if $location;
936         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
937         $query.= " AND biblioitems.itemtype=".$dbh->quote($itemtype) if $itemtype;
938         $query .= " ORDER BY itemcallnumber,title";
939         $sth = $dbh->prepare($query);
940         $sth->execute( $minlocation, $maxlocation, $datelastseen );
941     }
942     else {
943         my $query ="
944                 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
945                 FROM items 
946                     LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber 
947                    LEFT JOIN biblioitems on items.biblionumber=biblioitems.biblionumber
948                 WHERE itemcallnumber>= ?
949                   AND itemcallnumber <=?";
950         $query.= " AND items.location=".$dbh->quote($location) if $location;
951         $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
952         $query.= " AND biblioitems.itemtype=".$dbh->quote($itemtype) if $itemtype;
953         $query .= " ORDER BY itemcallnumber,title";
954         $sth = $dbh->prepare($query);
955         $sth->execute( $minlocation, $maxlocation );
956     }
957     my @results;
958     $size--;
959     while ( my $row = $sth->fetchrow_hashref ) {
960         $offset-- if ($offset);
961         $row->{datelastseen}=format_date($row->{datelastseen});
962         if ( ( !$offset ) && $size ) {
963             push @results, $row;
964             $size--;
965         }
966     }
967     return \@results;
968 }
969
970 =head2 GetItemsCount
971
972 =over 4
973 $count = &GetItemsCount( $biblionumber);
974
975 =back
976
977 This function return count of item with $biblionumber
978
979 =cut
980
981 sub GetItemsCount {
982     my ( $biblionumber ) = @_;
983     my $dbh = C4::Context->dbh;
984     my $query = "SELECT count(*)
985           FROM  items 
986           WHERE biblionumber=?";
987     my $sth = $dbh->prepare($query);
988     $sth->execute($biblionumber);
989     my $count = $sth->fetchrow;  
990     $sth->finish;
991     return ($count);
992 }
993
994 =head2 GetItemInfosOf
995
996 =over 4
997
998 GetItemInfosOf(@itemnumbers);
999
1000 =back
1001
1002 =cut
1003
1004 sub GetItemInfosOf {
1005     my @itemnumbers = @_;
1006
1007     my $query = '
1008         SELECT *
1009         FROM items
1010         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1011     ';
1012     return get_infos_of( $query, 'itemnumber' );
1013 }
1014
1015 =head2 GetItemsByBiblioitemnumber
1016
1017 =over 4
1018
1019 GetItemsByBiblioitemnumber($biblioitemnumber);
1020
1021 =back
1022
1023 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1024 Called by C<C4::XISBN>
1025
1026 =cut
1027
1028 sub GetItemsByBiblioitemnumber {
1029     my ( $bibitem ) = @_;
1030     my $dbh = C4::Context->dbh;
1031     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1032     # Get all items attached to a biblioitem
1033     my $i = 0;
1034     my @results; 
1035     $sth->execute($bibitem) || die $sth->errstr;
1036     while ( my $data = $sth->fetchrow_hashref ) {  
1037         # Foreach item, get circulation information
1038         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1039                                    WHERE itemnumber = ?
1040                                    AND returndate is NULL
1041                                    AND issues.borrowernumber = borrowers.borrowernumber"
1042         );
1043         $sth2->execute( $data->{'itemnumber'} );
1044         if ( my $data2 = $sth2->fetchrow_hashref ) {
1045             # if item is out, set the due date and who it is out too
1046             $data->{'date_due'}   = $data2->{'date_due'};
1047             $data->{'cardnumber'} = $data2->{'cardnumber'};
1048             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1049         }
1050         else {
1051             # set date_due to blank, so in the template we check itemlost, and wthdrawn 
1052             $data->{'date_due'} = '';                                                                                                         
1053         }    # else         
1054         $sth2->finish;
1055         # Find the last 3 people who borrowed this item.                  
1056         my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1057                       AND issues.borrowernumber = borrowers.borrowernumber
1058                       AND returndate is not NULL
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             AND returndate IS NULL"
1148        );
1149         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
1150         while ( my $data = $sth->fetchrow_hashref ) {
1151         my $datedue = '';
1152         $isth->execute( $data->{'itemnumber'} );
1153         if ( my $idata = $isth->fetchrow_hashref ) {
1154             $data->{borrowernumber} = $idata->{borrowernumber};
1155             $data->{cardnumber}     = $idata->{cardnumber};
1156             $data->{surname}     = $idata->{surname};
1157             $data->{firstname}     = $idata->{firstname};
1158             $datedue                = $idata->{'date_due'};
1159         if (C4::Context->preference("IndependantBranches")){
1160         my $userenv = C4::Context->userenv;
1161         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) { 
1162             $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1163         }
1164         }
1165         }
1166                 if ( $data->{'serial'}) {       
1167                         $ssth->execute($data->{'itemnumber'}) ;
1168                         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1169                         $serial = 1;
1170         }
1171                 if ( $datedue eq '' ) {
1172             my ( $restype, $reserves ) =
1173               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1174             if ($restype) {
1175                 $count_reserves = $restype;
1176             }
1177         }
1178         $isth->finish;
1179         $ssth->finish;
1180         #get branch information.....
1181         my $bsth = $dbh->prepare(
1182             "SELECT * FROM branches WHERE branchcode = ?
1183         "
1184         );
1185         $bsth->execute( $data->{'holdingbranch'} );
1186         if ( my $bdata = $bsth->fetchrow_hashref ) {
1187             $data->{'branchname'} = $bdata->{'branchname'};
1188         }
1189         $data->{'datedue'}        = $datedue;
1190         $data->{'count_reserves'} = $count_reserves;
1191
1192         # get notforloan complete status if applicable
1193         my $sthnflstatus = $dbh->prepare(
1194             'SELECT authorised_value
1195             FROM   marc_subfield_structure
1196             WHERE  kohafield="items.notforloan"
1197         '
1198         );
1199
1200         $sthnflstatus->execute;
1201         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1202         if ($authorised_valuecode) {
1203             $sthnflstatus = $dbh->prepare(
1204                 "SELECT lib FROM authorised_values
1205                  WHERE  category=?
1206                  AND authorised_value=?"
1207             );
1208             $sthnflstatus->execute( $authorised_valuecode,
1209                 $data->{itemnotforloan} );
1210             my ($lib) = $sthnflstatus->fetchrow;
1211             $data->{notforloanvalue} = $lib;
1212         }
1213
1214         # my stack procedures
1215         my $stackstatus = $dbh->prepare(
1216             'SELECT authorised_value
1217              FROM   marc_subfield_structure
1218              WHERE  kohafield="items.stack"
1219         '
1220         );
1221         $stackstatus->execute;
1222
1223         ($authorised_valuecode) = $stackstatus->fetchrow;
1224         if ($authorised_valuecode) {
1225             $stackstatus = $dbh->prepare(
1226                 "SELECT lib
1227                  FROM   authorised_values
1228                  WHERE  category=?
1229                  AND    authorised_value=?
1230             "
1231             );
1232             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1233             my ($lib) = $stackstatus->fetchrow;
1234             $data->{stack} = $lib;
1235         }
1236         # Find the last 3 people who borrowed this item.
1237         my $sth2 = $dbh->prepare("SELECT * FROM issues,borrowers
1238                                     WHERE itemnumber = ?
1239                                     AND issues.borrowernumber = borrowers.borrowernumber
1240                                     AND returndate IS NOT NULL LIMIT 3");
1241         $sth2->execute($data->{'itemnumber'});
1242         my $ii = 0;
1243         while (my $data2 = $sth2->fetchrow_hashref()) {
1244             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1245             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1246             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1247             $ii++;
1248         }
1249
1250         $results[$i] = $data;
1251         $i++;
1252     }
1253     $sth->finish;
1254         if($serial) {
1255                 return( sort { $b->{'publisheddate'} cmp $a->{'publisheddate'} } @results );
1256         } else {
1257         return (@results);
1258         }
1259 }
1260
1261 =head2 get_itemnumbers_of
1262
1263 =over 4
1264
1265 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1266
1267 =back
1268
1269 Given a list of biblionumbers, return the list of corresponding itemnumbers
1270 for each biblionumber.
1271
1272 Return a reference on a hash where keys are biblionumbers and values are
1273 references on array of itemnumbers.
1274
1275 =cut
1276
1277 sub get_itemnumbers_of {
1278     my @biblionumbers = @_;
1279
1280     my $dbh = C4::Context->dbh;
1281
1282     my $query = '
1283         SELECT itemnumber,
1284             biblionumber
1285         FROM items
1286         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1287     ';
1288     my $sth = $dbh->prepare($query);
1289     $sth->execute(@biblionumbers);
1290
1291     my %itemnumbers_of;
1292
1293     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1294         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1295     }
1296
1297     return \%itemnumbers_of;
1298 }
1299
1300 =head2 GetItemnumberFromBarcode
1301
1302 =over 4
1303
1304 $result = GetItemnumberFromBarcode($barcode);
1305
1306 =back
1307
1308 =cut
1309
1310 sub GetItemnumberFromBarcode {
1311     my ($barcode) = @_;
1312     my $dbh = C4::Context->dbh;
1313
1314     my $rq =
1315       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1316     $rq->execute($barcode);
1317     my ($result) = $rq->fetchrow;
1318     return ($result);
1319 }
1320
1321 =head1 LIMITED USE FUNCTIONS
1322
1323 The following functions, while part of the public API,
1324 are not exported.  This is generally because they are
1325 meant to be used by only one script for a specific
1326 purpose, and should not be used in any other context
1327 without careful thought.
1328
1329 =cut
1330
1331 =head2 GetMarcItem
1332
1333 =over 4
1334
1335 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1336
1337 =back
1338
1339 Returns MARC::Record of the item passed in parameter.
1340 This function is meant for use only in C<cataloguing/additem.pl>,
1341 where it is needed to support that script's MARC-like
1342 editor.
1343
1344 =cut
1345
1346 sub GetMarcItem {
1347     my ( $biblionumber, $itemnumber ) = @_;
1348
1349     # GetMarcItem has been revised so that it does the following:
1350     #  1. Gets the item information from the items table.
1351     #  2. Converts it to a MARC field for storage in the bib record.
1352     #
1353     # The previous behavior was:
1354     #  1. Get the bib record.
1355     #  2. Return the MARC tag corresponding to the item record.
1356     #
1357     # The difference is that one treats the items row as authoritative,
1358     # while the other treats the MARC representation as authoritative
1359     # under certain circumstances.
1360
1361     my $itemrecord = GetItem($itemnumber);
1362
1363     # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1364     # Also, don't emit a subfield if the underlying field is blank.
1365     my $mungeditem = { map {  $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  } keys %{ $itemrecord } };
1366     my $itemmarc = TransformKohaToMarc($mungeditem);
1367
1368     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1369     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1370         my @fields = $itemmarc->fields();
1371         if ($#fields > -1) {
1372             $fields[0]->add_subfields(@$unlinked_item_subfields);
1373         }
1374     }
1375     
1376     return $itemmarc;
1377
1378 }
1379
1380 =head1 PRIVATE FUNCTIONS AND VARIABLES
1381
1382 The following functions are not meant to be called
1383 directly, but are documented in order to explain
1384 the inner workings of C<C4::Items>.
1385
1386 =cut
1387
1388 =head2 %derived_columns
1389
1390 This hash keeps track of item columns that
1391 are strictly derived from other columns in
1392 the item record and are not meant to be set
1393 independently.
1394
1395 Each key in the hash should be the name of a
1396 column (as named by TransformMarcToKoha).  Each
1397 value should be hashref whose keys are the
1398 columns on which the derived column depends.  The
1399 hashref should also contain a 'BUILDER' key
1400 that is a reference to a sub that calculates
1401 the derived value.
1402
1403 =cut
1404
1405 my %derived_columns = (
1406     'items.cn_sort' => {
1407         'itemcallnumber' => 1,
1408         'items.cn_source' => 1,
1409         'BUILDER' => \&_calc_items_cn_sort,
1410     }
1411 );
1412
1413 =head2 _set_derived_columns_for_add 
1414
1415 =over 4
1416
1417 _set_derived_column_for_add($item);
1418
1419 =back
1420
1421 Given an item hash representing a new item to be added,
1422 calculate any derived columns.  Currently the only
1423 such column is C<items.cn_sort>.
1424
1425 =cut
1426
1427 sub _set_derived_columns_for_add {
1428     my $item = shift;
1429
1430     foreach my $column (keys %derived_columns) {
1431         my $builder = $derived_columns{$column}->{'BUILDER'};
1432         my $source_values = {};
1433         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1434             next if $source_column eq 'BUILDER';
1435             $source_values->{$source_column} = $item->{$source_column};
1436         }
1437         $builder->($item, $source_values);
1438     }
1439 }
1440
1441 =head2 _set_derived_columns_for_mod 
1442
1443 =over 4
1444
1445 _set_derived_column_for_mod($item);
1446
1447 =back
1448
1449 Given an item hash representing a new item to be modified.
1450 calculate any derived columns.  Currently the only
1451 such column is C<items.cn_sort>.
1452
1453 This routine differs from C<_set_derived_columns_for_add>
1454 in that it needs to handle partial item records.  In other
1455 words, the caller of C<ModItem> may have supplied only one
1456 or two columns to be changed, so this function needs to
1457 determine whether any of the columns to be changed affect
1458 any of the derived columns.  Also, if a derived column
1459 depends on more than one column, but the caller is not
1460 changing all of then, this routine retrieves the unchanged
1461 values from the database in order to ensure a correct
1462 calculation.
1463
1464 =cut
1465
1466 sub _set_derived_columns_for_mod {
1467     my $item = shift;
1468
1469     foreach my $column (keys %derived_columns) {
1470         my $builder = $derived_columns{$column}->{'BUILDER'};
1471         my $source_values = {};
1472         my %missing_sources = ();
1473         my $must_recalc = 0;
1474         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1475             next if $source_column eq 'BUILDER';
1476             if (exists $item->{$source_column}) {
1477                 $must_recalc = 1;
1478                 $source_values->{$source_column} = $item->{$source_column};
1479             } else {
1480                 $missing_sources{$source_column} = 1;
1481             }
1482         }
1483         if ($must_recalc) {
1484             foreach my $source_column (keys %missing_sources) {
1485                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1486             }
1487             $builder->($item, $source_values);
1488         }
1489     }
1490 }
1491
1492 =head2 _do_column_fixes_for_mod
1493
1494 =over 4
1495
1496 _do_column_fixes_for_mod($item);
1497
1498 =back
1499
1500 Given an item hashref containing one or more
1501 columns to modify, fix up certain values.
1502 Specifically, set to 0 any passed value
1503 of C<notforloan>, C<damaged>, C<itemlost>, or
1504 C<wthdrawn> that is either undefined or
1505 contains the empty string.
1506
1507 =cut
1508
1509 sub _do_column_fixes_for_mod {
1510     my $item = shift;
1511
1512     if (exists $item->{'notforloan'} and
1513         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1514         $item->{'notforloan'} = 0;
1515     }
1516     if (exists $item->{'damaged'} and
1517         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1518         $item->{'damaged'} = 0;
1519     }
1520     if (exists $item->{'itemlost'} and
1521         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1522         $item->{'itemlost'} = 0;
1523     }
1524     if (exists $item->{'wthdrawn'} and
1525         (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1526         $item->{'wthdrawn'} = 0;
1527     }
1528 }
1529
1530 =head2 _get_single_item_column
1531
1532 =over 4
1533
1534 _get_single_item_column($column, $itemnumber);
1535
1536 =back
1537
1538 Retrieves the value of a single column from an C<items>
1539 row specified by C<$itemnumber>.
1540
1541 =cut
1542
1543 sub _get_single_item_column {
1544     my $column = shift;
1545     my $itemnumber = shift;
1546     
1547     my $dbh = C4::Context->dbh;
1548     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1549     $sth->execute($itemnumber);
1550     my ($value) = $sth->fetchrow();
1551     return $value; 
1552 }
1553
1554 =head2 _calc_items_cn_sort
1555
1556 =over 4
1557
1558 _calc_items_cn_sort($item, $source_values);
1559
1560 =back
1561
1562 Helper routine to calculate C<items.cn_sort>.
1563
1564 =cut
1565
1566 sub _calc_items_cn_sort {
1567     my $item = shift;
1568     my $source_values = shift;
1569
1570     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1571 }
1572
1573 =head2 _set_defaults_for_add 
1574
1575 =over 4
1576
1577 _set_defaults_for_add($item_hash);
1578
1579 =back
1580
1581 Given an item hash representing an item to be added, set
1582 correct default values for columns whose default value
1583 is not handled by the DBMS.  This includes the following
1584 columns:
1585
1586 =over 2
1587
1588 =item * 
1589
1590 C<items.dateaccessioned>
1591
1592 =item *
1593
1594 C<items.notforloan>
1595
1596 =item *
1597
1598 C<items.damaged>
1599
1600 =item *
1601
1602 C<items.itemlost>
1603
1604 =item *
1605
1606 C<items.wthdrawn>
1607
1608 =back
1609
1610 =cut
1611
1612 sub _set_defaults_for_add {
1613     my $item = shift;
1614
1615     # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1616     if (!(exists $item->{'dateaccessioned'}) || 
1617          ($item->{'dateaccessioned'} eq '')) {
1618         # FIXME add check for invalid date
1619         my $today = C4::Dates->new();    
1620         $item->{'dateaccessioned'} =  $today->output("iso"); #TODO: check time issues
1621     }
1622
1623     # various item status fields cannot be null
1624     $item->{'notforloan'} = 0 unless exists $item->{'notforloan'} and defined $item->{'notforloan'} and $item->{'notforloan'} ne '';
1625     $item->{'damaged'}    = 0 unless exists $item->{'damaged'}    and defined $item->{'damaged'}    and $item->{'damaged'} ne '';
1626     $item->{'itemlost'}   = 0 unless exists $item->{'itemlost'}   and defined $item->{'itemlost'}   and $item->{'itemlost'} ne '';
1627     $item->{'wthdrawn'}   = 0 unless exists $item->{'wthdrawn'}   and defined $item->{'wthdrawn'}   and $item->{'wthdrawn'} ne '';
1628 }
1629
1630 =head2 _koha_new_item
1631
1632 =over 4
1633
1634 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1635
1636 =back
1637
1638 Perform the actual insert into the C<items> table.
1639
1640 =cut
1641
1642 sub _koha_new_item {
1643     my ( $item, $barcode ) = @_;
1644     my $dbh=C4::Context->dbh;  
1645     my $error;
1646     my $query =
1647            "INSERT INTO items SET
1648             biblionumber        = ?,
1649             biblioitemnumber    = ?,
1650             barcode             = ?,
1651             dateaccessioned     = ?,
1652             booksellerid        = ?,
1653             homebranch          = ?,
1654             price               = ?,
1655             replacementprice    = ?,
1656             replacementpricedate = NOW(),
1657             datelastborrowed    = ?,
1658             datelastseen        = NOW(),
1659             stack               = ?,
1660             notforloan          = ?,
1661             damaged             = ?,
1662             itemlost            = ?,
1663             wthdrawn            = ?,
1664             itemcallnumber      = ?,
1665             restricted          = ?,
1666             itemnotes           = ?,
1667             holdingbranch       = ?,
1668             paidfor             = ?,
1669             location            = ?,
1670             onloan              = ?,
1671             issues              = ?,
1672             renewals            = ?,
1673             reserves            = ?,
1674             cn_source           = ?,
1675             cn_sort             = ?,
1676             ccode               = ?,
1677             itype               = ?,
1678             materials           = ?,
1679                         uri                 = ?,
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->{'more_subfields_xml'},
1715     );
1716     my $itemnumber = $dbh->{'mysql_insertid'};
1717     if ( defined $sth->errstr ) {
1718         $error.="ERROR in _koha_new_item $query".$sth->errstr;
1719     }
1720     $sth->finish();
1721     return ( $itemnumber, $error );
1722 }
1723
1724 =head2 _koha_modify_item
1725
1726 =over 4
1727
1728 my ($itemnumber,$error) =_koha_modify_item( $item );
1729
1730 =back
1731
1732 Perform the actual update of the C<items> row.  Note that this
1733 routine accepts a hashref specifying the columns to update.
1734
1735 =cut
1736
1737 sub _koha_modify_item {
1738     my ( $item ) = @_;
1739     my $dbh=C4::Context->dbh;  
1740     my $error;
1741
1742     my $query = "UPDATE items SET ";
1743     my @bind;
1744     for my $key ( keys %$item ) {
1745         $query.="$key=?,";
1746         push @bind, $item->{$key};
1747     }
1748     $query =~ s/,$//;
1749     $query .= " WHERE itemnumber=?";
1750     push @bind, $item->{'itemnumber'};
1751     my $sth = C4::Context->dbh->prepare($query);
1752     $sth->execute(@bind);
1753     if ( C4::Context->dbh->errstr ) {
1754         $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1755         warn $error;
1756     }
1757     $sth->finish();
1758     return ($item->{'itemnumber'},$error);
1759 }
1760
1761 =head2 _koha_delete_item
1762
1763 =over 4
1764
1765 _koha_delete_item( $dbh, $itemnum );
1766
1767 =back
1768
1769 Internal function to delete an item record from the koha tables
1770
1771 =cut
1772
1773 sub _koha_delete_item {
1774     my ( $dbh, $itemnum ) = @_;
1775
1776     # save the deleted item to deleteditems table
1777     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1778     $sth->execute($itemnum);
1779     my $data = $sth->fetchrow_hashref();
1780     $sth->finish();
1781     my $query = "INSERT INTO deleteditems SET ";
1782     my @bind  = ();
1783     foreach my $key ( keys %$data ) {
1784         $query .= "$key = ?,";
1785         push( @bind, $data->{$key} );
1786     }
1787     $query =~ s/\,$//;
1788     $sth = $dbh->prepare($query);
1789     $sth->execute(@bind);
1790     $sth->finish();
1791
1792     # delete from items table
1793     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1794     $sth->execute($itemnum);
1795     $sth->finish();
1796     return undef;
1797 }
1798
1799 =head2 _marc_from_item_hash
1800
1801 =over 4
1802
1803 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1804
1805 =back
1806
1807 Given an item hash representing a complete item record,
1808 create a C<MARC::Record> object containing an embedded
1809 tag representing that item.
1810
1811 The third, optional parameter C<$unlinked_item_subfields> is
1812 an arrayref of subfields (not mapped to C<items> fields per the
1813 framework) to be added to the MARC representation
1814 of the item.
1815
1816 =cut
1817
1818 sub _marc_from_item_hash {
1819     my $item = shift;
1820     my $frameworkcode = shift;
1821     my $unlinked_item_subfields;
1822     if (@_) {
1823         $unlinked_item_subfields = shift;
1824     }
1825    
1826     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1827     # Also, don't emit a subfield if the underlying field is blank.
1828     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
1829                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
1830                                 : ()  } keys %{ $item } }; 
1831
1832     my $item_marc = MARC::Record->new();
1833     foreach my $item_field (keys %{ $mungeditem }) {
1834         my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
1835         next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1836         if (my $field = $item_marc->field($tag)) {
1837             $field->add_subfields($subfield => $mungeditem->{$item_field});
1838         } else {
1839             my $add_subfields = [];
1840             if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1841                 $add_subfields = $unlinked_item_subfields;
1842             }
1843             $item_marc->add_fields( $tag, " ", " ", $subfield =>  $mungeditem->{$item_field}, @$add_subfields);
1844         }
1845     }
1846
1847     return $item_marc;
1848 }
1849
1850 =head2 _add_item_field_to_biblio
1851
1852 =over 4
1853
1854 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
1855
1856 =back
1857
1858 Adds the fields from a MARC record containing the
1859 representation of a Koha item record to the MARC
1860 biblio record.  The input C<$item_marc> record
1861 is expect to contain just one field, the embedded
1862 item information field.
1863
1864 =cut
1865
1866 sub _add_item_field_to_biblio {
1867     my ($item_marc, $biblionumber, $frameworkcode) = @_;
1868
1869     my $biblio_marc = GetMarcBiblio($biblionumber);
1870
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         $xml = $marc->as_xml();
2001     }
2002
2003     return $xml;
2004 }
2005
2006 =head2 _parse_unlinked_item_subfields_from_xml
2007
2008 =over 4
2009
2010 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2011
2012 =back
2013
2014 =cut
2015
2016 sub  _parse_unlinked_item_subfields_from_xml {
2017     my $xml = shift;
2018
2019     return unless defined $xml and $xml ne "";
2020     my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml), 'UTF-8', C4::Context->preference("marcflavour"));
2021     my $unlinked_subfields = [];
2022     my @fields = $marc->fields();
2023     if ($#fields > -1) {
2024         foreach my $subfield ($fields[0]->subfields()) {
2025             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2026         }
2027     }
2028     return $unlinked_subfields;
2029 }
2030
2031 1;