Bug 21650: Remove the subroutine C4::Items::GetLastAcquisitions
[koha.git] / C4 / Items.pm
1 package C4::Items;
2
3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23
24 use vars qw(@ISA @EXPORT);
25 BEGIN {
26     require Exporter;
27     @ISA = qw(Exporter);
28
29     @EXPORT = qw(
30         GetItem
31         AddItemFromMarc
32         AddItem
33         AddItemBatchFromMarc
34         ModItemFromMarc
35         Item2Marc
36         ModItem
37         ModDateLastSeen
38         ModItemTransfer
39         DelItem
40         CheckItemPreSave
41         GetItemsForInventory
42         GetItemsInfo
43         GetItemsLocationInfo
44         GetHostItemsInfo
45         get_hostitemnumbers_of
46         GetHiddenItemnumbers
47         ItemSafeToDelete
48         DelItemCheck
49         MoveItemFromBiblio
50         CartToShelf
51         ShelfToCart
52         GetAnalyticsCount
53         SearchItemsByField
54         SearchItems
55         PrepareItemrecordDisplay
56     );
57 }
58
59 use Carp;
60 use C4::Context;
61 use C4::Koha;
62 use C4::Biblio;
63 use Koha::DateUtils;
64 use MARC::Record;
65 use C4::ClassSource;
66 use C4::Log;
67 use List::MoreUtils qw(any);
68 use YAML qw(Load);
69 use DateTime::Format::MySQL;
70 use Data::Dumper; # used as part of logging item record changes, not just for
71                   # debugging; so please don't remove this
72
73 use Koha::AuthorisedValues;
74 use Koha::DateUtils qw(dt_from_string);
75 use Koha::Database;
76
77 use Koha::Biblioitems;
78 use Koha::Items;
79 use Koha::ItemTypes;
80 use Koha::SearchEngine;
81 use Koha::SearchEngine::Search;
82 use Koha::Libraries;
83
84 =head1 NAME
85
86 C4::Items - item management functions
87
88 =head1 DESCRIPTION
89
90 This module contains an API for manipulating item 
91 records in Koha, and is used by cataloguing, circulation,
92 acquisitions, and serials management.
93
94 # FIXME This POD is not up-to-date
95 A Koha item record is stored in two places: the
96 items table and embedded in a MARC tag in the XML
97 version of the associated bib record in C<biblioitems.marcxml>.
98 This is done to allow the item information to be readily
99 indexed (e.g., by Zebra), but means that each item
100 modification transaction must keep the items table
101 and the MARC XML in sync at all times.
102
103 Consequently, all code that creates, modifies, or deletes
104 item records B<must> use an appropriate function from 
105 C<C4::Items>.  If no existing function is suitable, it is
106 better to add one to C<C4::Items> than to use add
107 one-off SQL statements to add or modify items.
108
109 The items table will be considered authoritative.  In other
110 words, if there is ever a discrepancy between the items
111 table and the MARC XML, the items table should be considered
112 accurate.
113
114 =head1 HISTORICAL NOTE
115
116 Most of the functions in C<C4::Items> were originally in
117 the C<C4::Biblio> module.
118
119 =head1 CORE EXPORTED FUNCTIONS
120
121 The following functions are meant for use by users
122 of C<C4::Items>
123
124 =cut
125
126 =head2 GetItem
127
128   $item = GetItem($itemnumber,$barcode,$serial);
129
130 Return item information, for a given itemnumber or barcode.
131 The return value is a hashref mapping item column
132 names to values.  If C<$serial> is true, include serial publication data.
133
134 =cut
135
136 sub GetItem {
137     my ($itemnumber,$barcode, $serial) = @_;
138     my $dbh = C4::Context->dbh;
139
140     my $item;
141     if ($itemnumber) {
142         $item = Koha::Items->find( $itemnumber );
143     } else {
144         $item = Koha::Items->find( { barcode => $barcode } );
145     }
146
147     return unless ( $item );
148
149     my $data = $item->unblessed();
150     $data->{itype} = $item->effective_itemtype(); # set the correct itype
151
152     if ($serial) {
153         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
154         $ssth->execute( $data->{'itemnumber'} );
155         ( $data->{'serialseq'}, $data->{'publisheddate'} ) = $ssth->fetchrow_array();
156     }
157
158     return $data;
159 }    # sub GetItem
160
161 =head2 CartToShelf
162
163   CartToShelf($itemnumber);
164
165 Set the current shelving location of the item record
166 to its stored permanent shelving location.  This is
167 primarily used to indicate when an item whose current
168 location is a special processing ('PROC') or shelving cart
169 ('CART') location is back in the stacks.
170
171 =cut
172
173 sub CartToShelf {
174     my ( $itemnumber ) = @_;
175
176     unless ( $itemnumber ) {
177         croak "FAILED CartToShelf() - no itemnumber supplied";
178     }
179
180     my $item = GetItem($itemnumber);
181     if ( $item->{location} eq 'CART' ) {
182         $item->{location} = $item->{permanent_location};
183         ModItem($item, undef, $itemnumber);
184     }
185 }
186
187 =head2 ShelfToCart
188
189   ShelfToCart($itemnumber);
190
191 Set the current shelving location of the item
192 to shelving cart ('CART').
193
194 =cut
195
196 sub ShelfToCart {
197     my ( $itemnumber ) = @_;
198
199     unless ( $itemnumber ) {
200         croak "FAILED ShelfToCart() - no itemnumber supplied";
201     }
202
203     my $item = GetItem($itemnumber);
204     $item->{'location'} = 'CART';
205     ModItem($item, undef, $itemnumber);
206 }
207
208 =head2 AddItemFromMarc
209
210   my ($biblionumber, $biblioitemnumber, $itemnumber) 
211       = AddItemFromMarc($source_item_marc, $biblionumber);
212
213 Given a MARC::Record object containing an embedded item
214 record and a biblionumber, create a new item record.
215
216 =cut
217
218 sub AddItemFromMarc {
219     my ( $source_item_marc, $biblionumber ) = @_;
220     my $dbh = C4::Context->dbh;
221
222     # parse item hash from MARC
223     my $frameworkcode = C4::Biblio::GetFrameworkCode( $biblionumber );
224     my ($itemtag,$itemsubfield)=C4::Biblio::GetMarcFromKohaField("items.itemnumber",$frameworkcode);
225
226     my $localitemmarc=MARC::Record->new;
227     $localitemmarc->append_fields($source_item_marc->field($itemtag));
228     my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode ,'items');
229     my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
230     return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
231 }
232
233 =head2 AddItem
234
235   my ($biblionumber, $biblioitemnumber, $itemnumber) 
236       = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
237
238 Given a hash containing item column names as keys,
239 create a new Koha item record.
240
241 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
242 do not need to be supplied for general use; they exist
243 simply to allow them to be picked up from AddItemFromMarc.
244
245 The final optional parameter, C<$unlinked_item_subfields>, contains
246 an arrayref containing subfields present in the original MARC
247 representation of the item (e.g., from the item editor) that are
248 not mapped to C<items> columns directly but should instead
249 be stored in C<items.more_subfields_xml> and included in 
250 the biblio items tag for display and indexing.
251
252 =cut
253
254 sub AddItem {
255     my $item         = shift;
256     my $biblionumber = shift;
257
258     my $dbh           = @_ ? shift : C4::Context->dbh;
259     my $frameworkcode = @_ ? shift : C4::Biblio::GetFrameworkCode($biblionumber);
260     my $unlinked_item_subfields;
261     if (@_) {
262         $unlinked_item_subfields = shift;
263     }
264
265     # needs old biblionumber and biblioitemnumber
266     $item->{'biblionumber'} = $biblionumber;
267     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
268     $sth->execute( $item->{'biblionumber'} );
269     ( $item->{'biblioitemnumber'} ) = $sth->fetchrow;
270
271     _set_defaults_for_add($item);
272     _set_derived_columns_for_add($item);
273     $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
274
275     # FIXME - checks here
276     unless ( $item->{itype} ) {    # default to biblioitem.itemtype if no itype
277         my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
278         $itype_sth->execute( $item->{'biblionumber'} );
279         ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
280     }
281
282     my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
283     return if $error;
284
285     $item->{'itemnumber'} = $itemnumber;
286
287     ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
288
289     logaction( "CATALOGUING", "ADD", $itemnumber, "item" )
290       if C4::Context->preference("CataloguingLog");
291
292     return ( $item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber );
293 }
294
295 =head2 AddItemBatchFromMarc
296
297   ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
298              $biblionumber, $biblioitemnumber, $frameworkcode);
299
300 Efficiently create item records from a MARC biblio record with
301 embedded item fields.  This routine is suitable for batch jobs.
302
303 This API assumes that the bib record has already been
304 saved to the C<biblio> and C<biblioitems> tables.  It does
305 not expect that C<biblio_metadata.metadata> is populated, but it
306 will do so via a call to ModBibiloMarc.
307
308 The goal of this API is to have a similar effect to using AddBiblio
309 and AddItems in succession, but without inefficient repeated
310 parsing of the MARC XML bib record.
311
312 This function returns an arrayref of new itemsnumbers and an arrayref of item
313 errors encountered during the processing.  Each entry in the errors
314 list is a hashref containing the following keys:
315
316 =over
317
318 =item item_sequence
319
320 Sequence number of original item tag in the MARC record.
321
322 =item item_barcode
323
324 Item barcode, provide to assist in the construction of
325 useful error messages.
326
327 =item error_code
328
329 Code representing the error condition.  Can be 'duplicate_barcode',
330 'invalid_homebranch', or 'invalid_holdingbranch'.
331
332 =item error_information
333
334 Additional information appropriate to the error condition.
335
336 =back
337
338 =cut
339
340 sub AddItemBatchFromMarc {
341     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
342     my $error;
343     my @itemnumbers = ();
344     my @errors = ();
345     my $dbh = C4::Context->dbh;
346
347     # We modify the record, so lets work on a clone so we don't change the
348     # original.
349     $record = $record->clone();
350     # loop through the item tags and start creating items
351     my @bad_item_fields = ();
352     my ($itemtag, $itemsubfield) = C4::Biblio::GetMarcFromKohaField("items.itemnumber",'');
353     my $item_sequence_num = 0;
354     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
355         $item_sequence_num++;
356         # we take the item field and stick it into a new
357         # MARC record -- this is required so far because (FIXME)
358         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
359         # and there is no TransformMarcFieldToKoha
360         my $temp_item_marc = MARC::Record->new();
361         $temp_item_marc->append_fields($item_field);
362     
363         # add biblionumber and biblioitemnumber
364         my $item = TransformMarcToKoha( $temp_item_marc, $frameworkcode, 'items' );
365         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
366         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
367         $item->{'biblionumber'} = $biblionumber;
368         $item->{'biblioitemnumber'} = $biblioitemnumber;
369
370         # check for duplicate barcode
371         my %item_errors = CheckItemPreSave($item);
372         if (%item_errors) {
373             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
374             push @bad_item_fields, $item_field;
375             next ITEMFIELD;
376         }
377
378         _set_defaults_for_add($item);
379         _set_derived_columns_for_add($item);
380         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
381         warn $error if $error;
382         push @itemnumbers, $itemnumber; # FIXME not checking error
383         $item->{'itemnumber'} = $itemnumber;
384
385         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
386
387         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
388         $item_field->replace_with($new_item_marc->field($itemtag));
389     }
390
391     # remove any MARC item fields for rejected items
392     foreach my $item_field (@bad_item_fields) {
393         $record->delete_field($item_field);
394     }
395
396     # update the MARC biblio
397  #   $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
398
399     return (\@itemnumbers, \@errors);
400 }
401
402 =head2 ModItemFromMarc
403
404   ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
405
406 This function updates an item record based on a supplied
407 C<MARC::Record> object containing an embedded item field.
408 This API is meant for the use of C<additem.pl>; for 
409 other purposes, C<ModItem> should be used.
410
411 This function uses the hash %default_values_for_mod_from_marc,
412 which contains default values for item fields to
413 apply when modifying an item.  This is needed because
414 if an item field's value is cleared, TransformMarcToKoha
415 does not include the column in the
416 hash that's passed to ModItem, which without
417 use of this hash makes it impossible to clear
418 an item field's value.  See bug 2466.
419
420 Note that only columns that can be directly
421 changed from the cataloging and serials
422 item editors are included in this hash.
423
424 Returns item record
425
426 =cut
427
428 sub _build_default_values_for_mod_marc {
429     # Has no framework parameter anymore, since Default is authoritative
430     # for Koha to MARC mappings.
431
432     my $cache     = Koha::Caches->get_instance();
433     my $cache_key = "default_value_for_mod_marc-";
434     my $cached    = $cache->get_from_cache($cache_key);
435     return $cached if $cached;
436
437     my $default_values = {
438         barcode                  => undef,
439         booksellerid             => undef,
440         ccode                    => undef,
441         'items.cn_source'        => undef,
442         coded_location_qualifier => undef,
443         copynumber               => undef,
444         damaged                  => 0,
445         enumchron                => undef,
446         holdingbranch            => undef,
447         homebranch               => undef,
448         itemcallnumber           => undef,
449         itemlost                 => 0,
450         itemnotes                => undef,
451         itemnotes_nonpublic      => undef,
452         itype                    => undef,
453         location                 => undef,
454         permanent_location       => undef,
455         materials                => undef,
456         new_status               => undef,
457         notforloan               => 0,
458         # paidfor => undef, # commented, see bug 12817
459         price                    => undef,
460         replacementprice         => undef,
461         replacementpricedate     => undef,
462         restricted               => undef,
463         stack                    => undef,
464         stocknumber              => undef,
465         uri                      => undef,
466         withdrawn                => 0,
467     };
468     my %default_values_for_mod_from_marc;
469     while ( my ( $field, $default_value ) = each %$default_values ) {
470         my $kohafield = $field;
471         $kohafield =~ s|^([^\.]+)$|items.$1|;
472         $default_values_for_mod_from_marc{$field} = $default_value
473             if C4::Biblio::GetMarcFromKohaField( $kohafield );
474     }
475
476     $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
477     return \%default_values_for_mod_from_marc;
478 }
479
480 sub ModItemFromMarc {
481     my $item_marc = shift;
482     my $biblionumber = shift;
483     my $itemnumber = shift;
484
485     my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
486     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
487
488     my $localitemmarc = MARC::Record->new;
489     $localitemmarc->append_fields( $item_marc->field($itemtag) );
490     my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
491     my $default_values = _build_default_values_for_mod_marc();
492     foreach my $item_field ( keys %$default_values ) {
493         $item->{$item_field} = $default_values->{$item_field}
494           unless exists $item->{$item_field};
495     }
496     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
497
498     ModItem( $item, $biblionumber, $itemnumber, { unlinked_item_subfields => $unlinked_item_subfields } );
499     return $item;
500 }
501
502 =head2 ModItem
503
504 ModItem(
505     { column => $newvalue },
506     $biblionumber,
507     $itemnumber,
508     {
509         [ unlinked_item_subfields => $unlinked_item_subfields, ]
510         [ log_action => 1, ]
511     }
512 );
513
514 Change one or more columns in an item record and update
515 the MARC representation of the item.
516
517 The first argument is a hashref mapping from item column
518 names to the new values.  The second and third arguments
519 are the biblionumber and itemnumber, respectively.
520 The fourth, optional parameter (additional_params) may contain the keys
521 unlinked_item_subfields and log_action.
522
523 C<$unlinked_item_subfields> contains an arrayref containing
524 subfields present in the original MARC
525 representation of the item (e.g., from the item editor) that are
526 not mapped to C<items> columns directly but should instead
527 be stored in C<items.more_subfields_xml> and included in 
528 the biblio items tag for display and indexing.
529
530 If one of the changed columns is used to calculate
531 the derived value of a column such as C<items.cn_sort>, 
532 this routine will perform the necessary calculation
533 and set the value.
534
535 If log_action is set to false, the action will not be logged.
536 If log_action is true or undefined, the action will be logged.
537
538 =cut
539
540 sub ModItem {
541     my ( $item, $biblionumber, $itemnumber, $additional_params ) = @_;
542     my $log_action = $additional_params->{log_action} // 1;
543     my $unlinked_item_subfields = $additional_params->{unlinked_item_subfields};
544
545     return unless %$item;
546     $item->{'itemnumber'} = $itemnumber or return;
547
548     # if $biblionumber is undefined, get it from the current item
549     unless (defined $biblionumber) {
550         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
551     }
552
553     if ($unlinked_item_subfields) {
554         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
555     };
556
557     my @fields = qw( itemlost withdrawn damaged );
558
559     # Only call GetItem if we need to set an "on" date field
560     if ( $item->{itemlost} || $item->{withdrawn} || $item->{damaged} ) {
561         my $pre_mod_item = GetItem( $item->{'itemnumber'} );
562         for my $field (@fields) {
563             if (    defined( $item->{$field} )
564                 and not $pre_mod_item->{$field}
565                 and $item->{$field} )
566             {
567                 $item->{ $field . '_on' } =
568                   DateTime::Format::MySQL->format_datetime( dt_from_string() );
569             }
570         }
571     }
572
573     # If the field is defined but empty, we are removing and,
574     # and thus need to clear out the 'on' field as well
575     for my $field (@fields) {
576         if ( defined( $item->{$field} ) && !$item->{$field} ) {
577             $item->{ $field . '_on' } = undef;
578         }
579     }
580
581
582     _set_derived_columns_for_mod($item);
583     _do_column_fixes_for_mod($item);
584     # FIXME add checks
585     # duplicate barcode
586     # attempt to change itemnumber
587     # attempt to change biblionumber (if we want
588     # an API to relink an item to a different bib,
589     # it should be a separate function)
590
591     # update items table
592     _koha_modify_item($item);
593
594     # request that bib be reindexed so that searching on current
595     # item status is possible
596     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
597
598     logaction( "CATALOGUING", "MODIFY", $itemnumber, "item " . Dumper($item) )
599       if $log_action && C4::Context->preference("CataloguingLog");
600 }
601
602 =head2 ModItemTransfer
603
604   ModItemTransfer($itenumber, $frombranch, $tobranch);
605
606 Marks an item as being transferred from one branch
607 to another.
608
609 =cut
610
611 sub ModItemTransfer {
612     my ( $itemnumber, $frombranch, $tobranch ) = @_;
613
614     my $dbh = C4::Context->dbh;
615
616     # Remove the 'shelving cart' location status if it is being used.
617     CartToShelf( $itemnumber ) if ( C4::Context->preference("ReturnToShelvingCart") );
618
619     $dbh->do("UPDATE branchtransfers SET datearrived = NOW(), comments = ? WHERE itemnumber = ? AND datearrived IS NULL", undef, "Canceled, new transfer from $frombranch to $tobranch created", $itemnumber);
620
621     #new entry in branchtransfers....
622     my $sth = $dbh->prepare(
623         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
624         VALUES (?, ?, NOW(), ?)");
625     $sth->execute($itemnumber, $frombranch, $tobranch);
626
627     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
628     ModDateLastSeen($itemnumber);
629     return;
630 }
631
632 =head2 ModDateLastSeen
633
634 ModDateLastSeen( $itemnumber, $leave_item_lost );
635
636 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
637 C<$itemnumber> is the item number
638 C<$leave_item_lost> determines if a lost item will be found or remain lost
639
640 =cut
641
642 sub ModDateLastSeen {
643     my ( $itemnumber, $leave_item_lost ) = @_;
644
645     my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
646
647     my $params;
648     $params->{datelastseen} = $today;
649     $params->{itemlost} = 0 unless $leave_item_lost;
650
651     ModItem( $params, undef, $itemnumber, { log_action => 0 } );
652 }
653
654 =head2 DelItem
655
656   DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
657
658 Exported function (core API) for deleting an item record in Koha.
659
660 =cut
661
662 sub DelItem {
663     my ( $params ) = @_;
664
665     my $itemnumber   = $params->{itemnumber};
666     my $biblionumber = $params->{biblionumber};
667
668     unless ($biblionumber) {
669         my $item = Koha::Items->find( $itemnumber );
670         $biblionumber = $item ? $item->biblio->biblionumber : undef;
671     }
672
673     # If there is no biblionumber for the given itemnumber, there is nothing to delete
674     return 0 unless $biblionumber;
675
676     # FIXME check the item has no current issues
677     my $deleted = _koha_delete_item( $itemnumber );
678
679     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
680
681     #search item field code
682     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
683     return $deleted;
684 }
685
686 =head2 CheckItemPreSave
687
688     my $item_ref = TransformMarcToKoha($marc, 'items');
689     # do stuff
690     my %errors = CheckItemPreSave($item_ref);
691     if (exists $errors{'duplicate_barcode'}) {
692         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
693     } elsif (exists $errors{'invalid_homebranch'}) {
694         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
695     } elsif (exists $errors{'invalid_holdingbranch'}) {
696         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
697     } else {
698         print "item is OK";
699     }
700
701 Given a hashref containing item fields, determine if it can be
702 inserted or updated in the database.  Specifically, checks for
703 database integrity issues, and returns a hash containing any
704 of the following keys, if applicable.
705
706 =over 2
707
708 =item duplicate_barcode
709
710 Barcode, if it duplicates one already found in the database.
711
712 =item invalid_homebranch
713
714 Home branch, if not defined in branches table.
715
716 =item invalid_holdingbranch
717
718 Holding branch, if not defined in branches table.
719
720 =back
721
722 This function does NOT implement any policy-related checks,
723 e.g., whether current operator is allowed to save an
724 item that has a given branch code.
725
726 =cut
727
728 sub CheckItemPreSave {
729     my $item_ref = shift;
730
731     my %errors = ();
732
733     # check for duplicate barcode
734     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
735         my $existing_item= Koha::Items->find({barcode => $item_ref->{'barcode'}});
736         if ($existing_item) {
737             if (!exists $item_ref->{'itemnumber'}                       # new item
738                 or $item_ref->{'itemnumber'} != $existing_item->itemnumber) { # existing item
739                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
740             }
741         }
742     }
743
744     # check for valid home branch
745     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
746         my $home_library = Koha::Libraries->find( $item_ref->{homebranch} );
747         unless (defined $home_library) {
748             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
749         }
750     }
751
752     # check for valid holding branch
753     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
754         my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} );
755         unless (defined $holding_library) {
756             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
757         }
758     }
759
760     return %errors;
761
762 }
763
764 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
765
766 The following functions provide various ways of 
767 getting an item record, a set of item records, or
768 lists of authorized values for certain item fields.
769
770 =cut
771
772 =head2 GetItemsForInventory
773
774 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
775   minlocation  => $minlocation,
776   maxlocation  => $maxlocation,
777   location     => $location,
778   itemtype     => $itemtype,
779   ignoreissued => $ignoreissued,
780   datelastseen => $datelastseen,
781   branchcode   => $branchcode,
782   branch       => $branch,
783   offset       => $offset,
784   size         => $size,
785   statushash   => $statushash,
786 } );
787
788 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
789
790 The sub returns a reference to a list of hashes, each containing
791 itemnumber, author, title, barcode, item callnumber, and date last
792 seen. It is ordered by callnumber then title.
793
794 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
795 the datelastseen can be used to specify that you want to see items not seen since a past date only.
796 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
797 $statushash requires a hashref that has the authorized values fieldname (intems.notforloan, etc...) as keys, and an arrayref of statuscodes we are searching for as values.
798
799 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
800
801 =cut
802
803 sub GetItemsForInventory {
804     my ( $parameters ) = @_;
805     my $minlocation  = $parameters->{'minlocation'}  // '';
806     my $maxlocation  = $parameters->{'maxlocation'}  // '';
807     my $location     = $parameters->{'location'}     // '';
808     my $itemtype     = $parameters->{'itemtype'}     // '';
809     my $ignoreissued = $parameters->{'ignoreissued'} // '';
810     my $datelastseen = $parameters->{'datelastseen'} // '';
811     my $branchcode   = $parameters->{'branchcode'}   // '';
812     my $branch       = $parameters->{'branch'}       // '';
813     my $offset       = $parameters->{'offset'}       // '';
814     my $size         = $parameters->{'size'}         // '';
815     my $statushash   = $parameters->{'statushash'}   // '';
816
817     my $dbh = C4::Context->dbh;
818     my ( @bind_params, @where_strings );
819
820     my $select_columns = q{
821         SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
822     };
823     my $select_count = q{SELECT COUNT(*)};
824     my $query = q{
825         FROM items
826         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
827         LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
828     };
829     if ($statushash){
830         for my $authvfield (keys %$statushash){
831             if ( scalar @{$statushash->{$authvfield}} > 0 ){
832                 my $joinedvals = join ',', @{$statushash->{$authvfield}};
833                 push @where_strings, "$authvfield in (" . $joinedvals . ")";
834             }
835         }
836     }
837
838     if ($minlocation) {
839         push @where_strings, 'itemcallnumber >= ?';
840         push @bind_params, $minlocation;
841     }
842
843     if ($maxlocation) {
844         push @where_strings, 'itemcallnumber <= ?';
845         push @bind_params, $maxlocation;
846     }
847
848     if ($datelastseen) {
849         $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
850         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
851         push @bind_params, $datelastseen;
852     }
853
854     if ( $location ) {
855         push @where_strings, 'items.location = ?';
856         push @bind_params, $location;
857     }
858
859     if ( $branchcode ) {
860         if($branch eq "homebranch"){
861         push @where_strings, 'items.homebranch = ?';
862         }else{
863             push @where_strings, 'items.holdingbranch = ?';
864         }
865         push @bind_params, $branchcode;
866     }
867
868     if ( $itemtype ) {
869         push @where_strings, 'biblioitems.itemtype = ?';
870         push @bind_params, $itemtype;
871     }
872
873     if ( $ignoreissued) {
874         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
875         push @where_strings, 'issues.date_due IS NULL';
876     }
877
878     if ( @where_strings ) {
879         $query .= 'WHERE ';
880         $query .= join ' AND ', @where_strings;
881     }
882     my $count_query = $select_count . $query;
883     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
884     $query .= " LIMIT $offset, $size" if ($offset and $size);
885     $query = $select_columns . $query;
886     my $sth = $dbh->prepare($query);
887     $sth->execute( @bind_params );
888
889     my @results = ();
890     my $tmpresults = $sth->fetchall_arrayref({});
891     $sth = $dbh->prepare( $count_query );
892     $sth->execute( @bind_params );
893     my ($iTotalRecords) = $sth->fetchrow_array();
894
895     my @avs = Koha::AuthorisedValues->search(
896         {   'marc_subfield_structures.kohafield' => { '>' => '' },
897             'me.authorised_value'                => { '>' => '' },
898         },
899         {   join     => { category => 'marc_subfield_structures' },
900             distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'],
901             '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ],
902             '+as'     => [ 'kohafield',                          'frameworkcode',                          'authorised_value',    'lib' ],
903         }
904     );
905
906     my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
907
908     foreach my $row (@$tmpresults) {
909
910         # Auth values
911         foreach (keys %$row) {
912             if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
913                 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
914             }
915         }
916         push @results, $row;
917     }
918
919     return (\@results, $iTotalRecords);
920 }
921
922 =head2 GetItemsInfo
923
924   @results = GetItemsInfo($biblionumber);
925
926 Returns information about items with the given biblionumber.
927
928 C<GetItemsInfo> returns a list of references-to-hash. Each element
929 contains a number of keys. Most of them are attributes from the
930 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
931 Koha database. Other keys include:
932
933 =over 2
934
935 =item C<$data-E<gt>{branchname}>
936
937 The name (not the code) of the branch to which the book belongs.
938
939 =item C<$data-E<gt>{datelastseen}>
940
941 This is simply C<items.datelastseen>, except that while the date is
942 stored in YYYY-MM-DD format in the database, here it is converted to
943 DD/MM/YYYY format. A NULL date is returned as C<//>.
944
945 =item C<$data-E<gt>{datedue}>
946
947 =item C<$data-E<gt>{class}>
948
949 This is the concatenation of C<biblioitems.classification>, the book's
950 Dewey code, and C<biblioitems.subclass>.
951
952 =item C<$data-E<gt>{ocount}>
953
954 I think this is the number of copies of the book available.
955
956 =item C<$data-E<gt>{order}>
957
958 If this is set, it is set to C<One Order>.
959
960 =back
961
962 =cut
963
964 sub GetItemsInfo {
965     my ( $biblionumber ) = @_;
966     my $dbh   = C4::Context->dbh;
967     require C4::Languages;
968     my $language = C4::Languages::getlanguage();
969     my $query = "
970     SELECT items.*,
971            biblio.*,
972            biblioitems.volume,
973            biblioitems.number,
974            biblioitems.itemtype,
975            biblioitems.isbn,
976            biblioitems.issn,
977            biblioitems.publicationyear,
978            biblioitems.publishercode,
979            biblioitems.volumedate,
980            biblioitems.volumedesc,
981            biblioitems.lccn,
982            biblioitems.url,
983            items.notforloan as itemnotforloan,
984            issues.borrowernumber,
985            issues.date_due as datedue,
986            issues.onsite_checkout,
987            borrowers.cardnumber,
988            borrowers.surname,
989            borrowers.firstname,
990            borrowers.branchcode as bcode,
991            serial.serialseq,
992            serial.publisheddate,
993            itemtypes.description,
994            COALESCE( localization.translation, itemtypes.description ) AS translated_description,
995            itemtypes.notforloan as notforloan_per_itemtype,
996            holding.branchurl,
997            holding.branchcode,
998            holding.branchname,
999            holding.opac_info as holding_branch_opac_info,
1000            home.opac_info as home_branch_opac_info
1001     ";
1002     $query .= "
1003      FROM items
1004      LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1005      LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1006      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
1007      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1008      LEFT JOIN issues USING (itemnumber)
1009      LEFT JOIN borrowers USING (borrowernumber)
1010      LEFT JOIN serialitems USING (itemnumber)
1011      LEFT JOIN serial USING (serialid)
1012      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
1013      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1014     $query .= q|
1015     LEFT JOIN localization ON itemtypes.itemtype = localization.code
1016         AND localization.entity = 'itemtypes'
1017         AND localization.lang = ?
1018     |;
1019
1020     $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1021     my $sth = $dbh->prepare($query);
1022     $sth->execute($language, $biblionumber);
1023     my $i = 0;
1024     my @results;
1025     my $serial;
1026
1027     my $userenv = C4::Context->userenv;
1028     my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
1029     while ( my $data = $sth->fetchrow_hashref ) {
1030         if ( $data->{borrowernumber} && $want_not_same_branch) {
1031             $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
1032         }
1033
1034         $serial ||= $data->{'serial'};
1035
1036         my $descriptions;
1037         # get notforloan complete status if applicable
1038         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.notforloan', authorised_value => $data->{itemnotforloan} });
1039         $data->{notforloanvalue}     = $descriptions->{lib} // '';
1040         $data->{notforloanvalueopac} = $descriptions->{opac_description} // '';
1041
1042         # get restricted status and description if applicable
1043         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
1044         $data->{restricted}     = $descriptions->{lib} // '';
1045         $data->{restrictedopac} = $descriptions->{opac_description} // '';
1046
1047         # my stack procedures
1048         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
1049         $data->{stack}          = $descriptions->{lib} // '';
1050
1051         # Find the last 3 people who borrowed this item.
1052         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1053                                     WHERE itemnumber = ?
1054                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1055                                     ORDER BY returndate DESC
1056                                     LIMIT 3");
1057         $sth2->execute($data->{'itemnumber'});
1058         my $ii = 0;
1059         while (my $data2 = $sth2->fetchrow_hashref()) {
1060             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1061             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1062             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1063             $ii++;
1064         }
1065
1066         $results[$i] = $data;
1067         $i++;
1068     }
1069
1070     return $serial
1071         ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
1072         : @results;
1073 }
1074
1075 =head2 GetItemsLocationInfo
1076
1077   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1078
1079 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1080
1081 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1082
1083 =over 2
1084
1085 =item C<$data-E<gt>{homebranch}>
1086
1087 Branch Name of the item's homebranch
1088
1089 =item C<$data-E<gt>{holdingbranch}>
1090
1091 Branch Name of the item's holdingbranch
1092
1093 =item C<$data-E<gt>{location}>
1094
1095 Item's shelving location code
1096
1097 =item C<$data-E<gt>{location_intranet}>
1098
1099 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1100
1101 =item C<$data-E<gt>{location_opac}>
1102
1103 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
1104 description is set.
1105
1106 =item C<$data-E<gt>{itemcallnumber}>
1107
1108 Item's itemcallnumber
1109
1110 =item C<$data-E<gt>{cn_sort}>
1111
1112 Item's call number normalized for sorting
1113
1114 =back
1115   
1116 =cut
1117
1118 sub GetItemsLocationInfo {
1119         my $biblionumber = shift;
1120         my @results;
1121
1122         my $dbh = C4::Context->dbh;
1123         my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch, 
1124                             location, itemcallnumber, cn_sort
1125                      FROM items, branches as a, branches as b
1126                      WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode 
1127                      AND biblionumber = ?
1128                      ORDER BY cn_sort ASC";
1129         my $sth = $dbh->prepare($query);
1130         $sth->execute($biblionumber);
1131
1132         while ( my $data = $sth->fetchrow_hashref ) {
1133              my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $data->{location} });
1134              $av = $av->count ? $av->next : undef;
1135              $data->{location_intranet} = $av ? $av->lib : '';
1136              $data->{location_opac}     = $av ? $av->opac_description : '';
1137              push @results, $data;
1138         }
1139         return @results;
1140 }
1141
1142 =head2 GetHostItemsInfo
1143
1144     $hostiteminfo = GetHostItemsInfo($hostfield);
1145     Returns the iteminfo for items linked to records via a host field
1146
1147 =cut
1148
1149 sub GetHostItemsInfo {
1150     my ($record) = @_;
1151     my @returnitemsInfo;
1152
1153     if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1154         return @returnitemsInfo;
1155     }
1156
1157     my @fields;
1158     if( C4::Context->preference('marcflavour') eq 'MARC21' ||
1159       C4::Context->preference('marcflavour') eq 'NORMARC') {
1160         @fields = $record->field('773');
1161     } elsif( C4::Context->preference('marcflavour') eq 'UNIMARC') {
1162         @fields = $record->field('461');
1163     }
1164
1165     foreach my $hostfield ( @fields ) {
1166         my $hostbiblionumber = $hostfield->subfield("0");
1167         my $linkeditemnumber = $hostfield->subfield("9");
1168         my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1169         foreach my $hostitemInfo (@hostitemInfos) {
1170             if( $hostitemInfo->{itemnumber} eq $linkeditemnumber ) {
1171                 push @returnitemsInfo, $hostitemInfo;
1172                 last;
1173             }
1174         }
1175     }
1176     return @returnitemsInfo;
1177 }
1178
1179 =head2 get_hostitemnumbers_of
1180
1181   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1182
1183 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1184
1185 Return a reference on a hash where key is a biblionumber and values are
1186 references on array of itemnumbers.
1187
1188 =cut
1189
1190
1191 sub get_hostitemnumbers_of {
1192     my ($biblionumber) = @_;
1193     my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
1194
1195     return unless $marcrecord;
1196
1197     my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
1198
1199     my $marcflavor = C4::Context->preference('marcflavour');
1200     if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
1201         $tag      = '773';
1202         $biblio_s = '0';
1203         $item_s   = '9';
1204     }
1205     elsif ( $marcflavor eq 'UNIMARC' ) {
1206         $tag      = '461';
1207         $biblio_s = '0';
1208         $item_s   = '9';
1209     }
1210
1211     foreach my $hostfield ( $marcrecord->field($tag) ) {
1212         my $hostbiblionumber = $hostfield->subfield($biblio_s);
1213         next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield
1214         my $linkeditemnumber = $hostfield->subfield($item_s);
1215         if ( ! $linkeditemnumber ) {
1216             warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9";
1217             next;
1218         }
1219         my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber });
1220         push @returnhostitemnumbers, $linkeditemnumber
1221           if $is_from_biblio;
1222     }
1223
1224     return @returnhostitemnumbers;
1225 }
1226
1227 =head2 GetHiddenItemnumbers
1228
1229     my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
1230
1231 Given a list of items it checks which should be hidden from the OPAC given
1232 the current configuration. Returns a list of itemnumbers corresponding to
1233 those that should be hidden. Optionally takes a borcat parameter for certain borrower types
1234 to be excluded
1235
1236 =cut
1237
1238 sub GetHiddenItemnumbers {
1239     my $params = shift;
1240     my $items = $params->{items};
1241     if (my $exceptions = C4::Context->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
1242         foreach my $except (split(/\|/, $exceptions)){
1243             if ($params->{'borcat'} eq $except){
1244                 return; # we don't hide anything for this borrower category
1245             }
1246         }
1247     }
1248     my @resultitems;
1249
1250     my $yaml = C4::Context->preference('OpacHiddenItems');
1251     return () if (! $yaml =~ /\S/ );
1252     $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1253     my $hidingrules;
1254     eval {
1255         $hidingrules = YAML::Load($yaml);
1256     };
1257     if ($@) {
1258         warn "Unable to parse OpacHiddenItems syspref : $@";
1259         return ();
1260     }
1261     my $dbh = C4::Context->dbh;
1262
1263     # For each item
1264     foreach my $item (@$items) {
1265
1266         # We check each rule
1267         foreach my $field (keys %$hidingrules) {
1268             my $val;
1269             if (exists $item->{$field}) {
1270                 $val = $item->{$field};
1271             }
1272             else {
1273                 my $query = "SELECT $field from items where itemnumber = ?";
1274                 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1275             }
1276             $val = '' unless defined $val;
1277
1278             # If the results matches the values in the yaml file
1279             if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1280
1281                 # We add the itemnumber to the list
1282                 push @resultitems, $item->{'itemnumber'};
1283
1284                 # If at least one rule matched for an item, no need to test the others
1285                 last;
1286             }
1287         }
1288     }
1289     return @resultitems;
1290 }
1291
1292 =head1 LIMITED USE FUNCTIONS
1293
1294 The following functions, while part of the public API,
1295 are not exported.  This is generally because they are
1296 meant to be used by only one script for a specific
1297 purpose, and should not be used in any other context
1298 without careful thought.
1299
1300 =cut
1301
1302 =head2 GetMarcItem
1303
1304   my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1305
1306 Returns MARC::Record of the item passed in parameter.
1307 This function is meant for use only in C<cataloguing/additem.pl>,
1308 where it is needed to support that script's MARC-like
1309 editor.
1310
1311 =cut
1312
1313 sub GetMarcItem {
1314     my ( $biblionumber, $itemnumber ) = @_;
1315
1316     # GetMarcItem has been revised so that it does the following:
1317     #  1. Gets the item information from the items table.
1318     #  2. Converts it to a MARC field for storage in the bib record.
1319     #
1320     # The previous behavior was:
1321     #  1. Get the bib record.
1322     #  2. Return the MARC tag corresponding to the item record.
1323     #
1324     # The difference is that one treats the items row as authoritative,
1325     # while the other treats the MARC representation as authoritative
1326     # under certain circumstances.
1327
1328     my $itemrecord = GetItem($itemnumber);
1329
1330     # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
1331     # Also, don't emit a subfield if the underlying field is blank.
1332
1333     
1334     return Item2Marc($itemrecord,$biblionumber);
1335
1336 }
1337 sub Item2Marc {
1338         my ($itemrecord,$biblionumber)=@_;
1339     my $mungeditem = { 
1340         map {  
1341             defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  
1342         } keys %{ $itemrecord } 
1343     };
1344     my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
1345     my $itemmarc = C4::Biblio::TransformKohaToMarc(
1346         $mungeditem, { no_split => 1},
1347     );
1348     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
1349         "items.itemnumber", $framework,
1350     );
1351
1352     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1353     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1354                 foreach my $field ($itemmarc->field($itemtag)){
1355             $field->add_subfields(@$unlinked_item_subfields);
1356         }
1357     }
1358         return $itemmarc;
1359 }
1360
1361 =head1 PRIVATE FUNCTIONS AND VARIABLES
1362
1363 The following functions are not meant to be called
1364 directly, but are documented in order to explain
1365 the inner workings of C<C4::Items>.
1366
1367 =cut
1368
1369 =head2 %derived_columns
1370
1371 This hash keeps track of item columns that
1372 are strictly derived from other columns in
1373 the item record and are not meant to be set
1374 independently.
1375
1376 Each key in the hash should be the name of a
1377 column (as named by TransformMarcToKoha).  Each
1378 value should be hashref whose keys are the
1379 columns on which the derived column depends.  The
1380 hashref should also contain a 'BUILDER' key
1381 that is a reference to a sub that calculates
1382 the derived value.
1383
1384 =cut
1385
1386 my %derived_columns = (
1387     'items.cn_sort' => {
1388         'itemcallnumber' => 1,
1389         'items.cn_source' => 1,
1390         'BUILDER' => \&_calc_items_cn_sort,
1391     }
1392 );
1393
1394 =head2 _set_derived_columns_for_add 
1395
1396   _set_derived_column_for_add($item);
1397
1398 Given an item hash representing a new item to be added,
1399 calculate any derived columns.  Currently the only
1400 such column is C<items.cn_sort>.
1401
1402 =cut
1403
1404 sub _set_derived_columns_for_add {
1405     my $item = shift;
1406
1407     foreach my $column (keys %derived_columns) {
1408         my $builder = $derived_columns{$column}->{'BUILDER'};
1409         my $source_values = {};
1410         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1411             next if $source_column eq 'BUILDER';
1412             $source_values->{$source_column} = $item->{$source_column};
1413         }
1414         $builder->($item, $source_values);
1415     }
1416 }
1417
1418 =head2 _set_derived_columns_for_mod 
1419
1420   _set_derived_column_for_mod($item);
1421
1422 Given an item hash representing a new item to be modified.
1423 calculate any derived columns.  Currently the only
1424 such column is C<items.cn_sort>.
1425
1426 This routine differs from C<_set_derived_columns_for_add>
1427 in that it needs to handle partial item records.  In other
1428 words, the caller of C<ModItem> may have supplied only one
1429 or two columns to be changed, so this function needs to
1430 determine whether any of the columns to be changed affect
1431 any of the derived columns.  Also, if a derived column
1432 depends on more than one column, but the caller is not
1433 changing all of then, this routine retrieves the unchanged
1434 values from the database in order to ensure a correct
1435 calculation.
1436
1437 =cut
1438
1439 sub _set_derived_columns_for_mod {
1440     my $item = shift;
1441
1442     foreach my $column (keys %derived_columns) {
1443         my $builder = $derived_columns{$column}->{'BUILDER'};
1444         my $source_values = {};
1445         my %missing_sources = ();
1446         my $must_recalc = 0;
1447         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1448             next if $source_column eq 'BUILDER';
1449             if (exists $item->{$source_column}) {
1450                 $must_recalc = 1;
1451                 $source_values->{$source_column} = $item->{$source_column};
1452             } else {
1453                 $missing_sources{$source_column} = 1;
1454             }
1455         }
1456         if ($must_recalc) {
1457             foreach my $source_column (keys %missing_sources) {
1458                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1459             }
1460             $builder->($item, $source_values);
1461         }
1462     }
1463 }
1464
1465 =head2 _do_column_fixes_for_mod
1466
1467   _do_column_fixes_for_mod($item);
1468
1469 Given an item hashref containing one or more
1470 columns to modify, fix up certain values.
1471 Specifically, set to 0 any passed value
1472 of C<notforloan>, C<damaged>, C<itemlost>, or
1473 C<withdrawn> that is either undefined or
1474 contains the empty string.
1475
1476 =cut
1477
1478 sub _do_column_fixes_for_mod {
1479     my $item = shift;
1480
1481     if (exists $item->{'notforloan'} and
1482         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1483         $item->{'notforloan'} = 0;
1484     }
1485     if (exists $item->{'damaged'} and
1486         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1487         $item->{'damaged'} = 0;
1488     }
1489     if (exists $item->{'itemlost'} and
1490         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1491         $item->{'itemlost'} = 0;
1492     }
1493     if (exists $item->{'withdrawn'} and
1494         (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1495         $item->{'withdrawn'} = 0;
1496     }
1497     if (exists $item->{location}
1498         and $item->{location} ne 'CART'
1499         and $item->{location} ne 'PROC'
1500         and not $item->{permanent_location}
1501     ) {
1502         $item->{'permanent_location'} = $item->{'location'};
1503     }
1504     if (exists $item->{'timestamp'}) {
1505         delete $item->{'timestamp'};
1506     }
1507 }
1508
1509 =head2 _get_single_item_column
1510
1511   _get_single_item_column($column, $itemnumber);
1512
1513 Retrieves the value of a single column from an C<items>
1514 row specified by C<$itemnumber>.
1515
1516 =cut
1517
1518 sub _get_single_item_column {
1519     my $column = shift;
1520     my $itemnumber = shift;
1521     
1522     my $dbh = C4::Context->dbh;
1523     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1524     $sth->execute($itemnumber);
1525     my ($value) = $sth->fetchrow();
1526     return $value; 
1527 }
1528
1529 =head2 _calc_items_cn_sort
1530
1531   _calc_items_cn_sort($item, $source_values);
1532
1533 Helper routine to calculate C<items.cn_sort>.
1534
1535 =cut
1536
1537 sub _calc_items_cn_sort {
1538     my $item = shift;
1539     my $source_values = shift;
1540
1541     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1542 }
1543
1544 =head2 _set_defaults_for_add 
1545
1546   _set_defaults_for_add($item_hash);
1547
1548 Given an item hash representing an item to be added, set
1549 correct default values for columns whose default value
1550 is not handled by the DBMS.  This includes the following
1551 columns:
1552
1553 =over 2
1554
1555 =item * 
1556
1557 C<items.dateaccessioned>
1558
1559 =item *
1560
1561 C<items.notforloan>
1562
1563 =item *
1564
1565 C<items.damaged>
1566
1567 =item *
1568
1569 C<items.itemlost>
1570
1571 =item *
1572
1573 C<items.withdrawn>
1574
1575 =back
1576
1577 =cut
1578
1579 sub _set_defaults_for_add {
1580     my $item = shift;
1581     $item->{dateaccessioned} ||= output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1582     $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
1583 }
1584
1585 =head2 _koha_new_item
1586
1587   my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1588
1589 Perform the actual insert into the C<items> table.
1590
1591 =cut
1592
1593 sub _koha_new_item {
1594     my ( $item, $barcode ) = @_;
1595     my $dbh=C4::Context->dbh;  
1596     my $error;
1597     $item->{permanent_location} //= $item->{location};
1598     _mod_item_dates( $item );
1599     my $query =
1600            "INSERT INTO items SET
1601             biblionumber        = ?,
1602             biblioitemnumber    = ?,
1603             barcode             = ?,
1604             dateaccessioned     = ?,
1605             booksellerid        = ?,
1606             homebranch          = ?,
1607             price               = ?,
1608             replacementprice    = ?,
1609             replacementpricedate = ?,
1610             datelastborrowed    = ?,
1611             datelastseen        = ?,
1612             stack               = ?,
1613             notforloan          = ?,
1614             damaged             = ?,
1615             itemlost            = ?,
1616             withdrawn           = ?,
1617             itemcallnumber      = ?,
1618             coded_location_qualifier = ?,
1619             restricted          = ?,
1620             itemnotes           = ?,
1621             itemnotes_nonpublic = ?,
1622             holdingbranch       = ?,
1623             paidfor             = ?,
1624             location            = ?,
1625             permanent_location  = ?,
1626             onloan              = ?,
1627             issues              = ?,
1628             renewals            = ?,
1629             reserves            = ?,
1630             cn_source           = ?,
1631             cn_sort             = ?,
1632             ccode               = ?,
1633             itype               = ?,
1634             materials           = ?,
1635             uri                 = ?,
1636             enumchron           = ?,
1637             more_subfields_xml  = ?,
1638             copynumber          = ?,
1639             stocknumber         = ?,
1640             new_status          = ?
1641           ";
1642     my $sth = $dbh->prepare($query);
1643     my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1644    $sth->execute(
1645             $item->{'biblionumber'},
1646             $item->{'biblioitemnumber'},
1647             $barcode,
1648             $item->{'dateaccessioned'},
1649             $item->{'booksellerid'},
1650             $item->{'homebranch'},
1651             $item->{'price'},
1652             $item->{'replacementprice'},
1653             $item->{'replacementpricedate'} || $today,
1654             $item->{datelastborrowed},
1655             $item->{datelastseen} || $today,
1656             $item->{stack},
1657             $item->{'notforloan'},
1658             $item->{'damaged'},
1659             $item->{'itemlost'},
1660             $item->{'withdrawn'},
1661             $item->{'itemcallnumber'},
1662             $item->{'coded_location_qualifier'},
1663             $item->{'restricted'},
1664             $item->{'itemnotes'},
1665             $item->{'itemnotes_nonpublic'},
1666             $item->{'holdingbranch'},
1667             $item->{'paidfor'},
1668             $item->{'location'},
1669             $item->{'permanent_location'},
1670             $item->{'onloan'},
1671             $item->{'issues'},
1672             $item->{'renewals'},
1673             $item->{'reserves'},
1674             $item->{'items.cn_source'},
1675             $item->{'items.cn_sort'},
1676             $item->{'ccode'},
1677             $item->{'itype'},
1678             $item->{'materials'},
1679             $item->{'uri'},
1680             $item->{'enumchron'},
1681             $item->{'more_subfields_xml'},
1682             $item->{'copynumber'},
1683             $item->{'stocknumber'},
1684             $item->{'new_status'},
1685     );
1686
1687     my $itemnumber;
1688     if ( defined $sth->errstr ) {
1689         $error.="ERROR in _koha_new_item $query".$sth->errstr;
1690     }
1691     else {
1692         $itemnumber = $dbh->{'mysql_insertid'};
1693     }
1694
1695     return ( $itemnumber, $error );
1696 }
1697
1698 =head2 MoveItemFromBiblio
1699
1700   MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1701
1702 Moves an item from a biblio to another
1703
1704 Returns undef if the move failed or the biblionumber of the destination record otherwise
1705
1706 =cut
1707
1708 sub MoveItemFromBiblio {
1709     my ($itemnumber, $frombiblio, $tobiblio) = @_;
1710     my $dbh = C4::Context->dbh;
1711     my ( $tobiblioitem ) = $dbh->selectrow_array(q|
1712         SELECT biblioitemnumber
1713         FROM biblioitems
1714         WHERE biblionumber = ?
1715     |, undef, $tobiblio );
1716     my $return = $dbh->do(q|
1717         UPDATE items
1718         SET biblioitemnumber = ?,
1719             biblionumber = ?
1720         WHERE itemnumber = ?
1721             AND biblionumber = ?
1722     |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
1723     if ($return == 1) {
1724         ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
1725         ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
1726             # Checking if the item we want to move is in an order 
1727         require C4::Acquisition;
1728         my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
1729             if ($order) {
1730                     # Replacing the biblionumber within the order if necessary
1731                     $order->{'biblionumber'} = $tobiblio;
1732                 C4::Acquisition::ModOrder($order);
1733             }
1734
1735         # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
1736         for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
1737             $dbh->do( qq|
1738                 UPDATE $table_name
1739                 SET biblionumber = ?
1740                 WHERE itemnumber = ?
1741             |, undef, $tobiblio, $itemnumber );
1742         }
1743         return $tobiblio;
1744         }
1745     return;
1746 }
1747
1748 =head2 ItemSafeToDelete
1749
1750    ItemSafeToDelete( $biblionumber, $itemnumber);
1751
1752 Exported function (core API) for checking whether an item record is safe to delete.
1753
1754 returns 1 if the item is safe to delete,
1755
1756 "book_on_loan" if the item is checked out,
1757
1758 "not_same_branch" if the item is blocked by independent branches,
1759
1760 "book_reserved" if the there are holds aganst the item, or
1761
1762 "linked_analytics" if the item has linked analytic records.
1763
1764 =cut
1765
1766 sub ItemSafeToDelete {
1767     my ( $biblionumber, $itemnumber ) = @_;
1768     my $status;
1769     my $dbh = C4::Context->dbh;
1770
1771     my $error;
1772
1773     my $countanalytics = GetAnalyticsCount($itemnumber);
1774
1775     # check that there is no issue on this item before deletion.
1776     my $sth = $dbh->prepare(
1777         q{
1778         SELECT COUNT(*) FROM issues
1779         WHERE itemnumber = ?
1780     }
1781     );
1782     $sth->execute($itemnumber);
1783     my ($onloan) = $sth->fetchrow;
1784
1785     my $item = GetItem($itemnumber);
1786
1787     if ($onloan) {
1788         $status = "book_on_loan";
1789     }
1790     elsif ( defined C4::Context->userenv
1791         and !C4::Context->IsSuperLibrarian()
1792         and C4::Context->preference("IndependentBranches")
1793         and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
1794     {
1795         $status = "not_same_branch";
1796     }
1797     else {
1798         # check it doesn't have a waiting reserve
1799         $sth = $dbh->prepare(
1800             q{
1801             SELECT COUNT(*) FROM reserves
1802             WHERE (found = 'W' OR found = 'T')
1803             AND itemnumber = ?
1804         }
1805         );
1806         $sth->execute($itemnumber);
1807         my ($reserve) = $sth->fetchrow;
1808         if ($reserve) {
1809             $status = "book_reserved";
1810         }
1811         elsif ( $countanalytics > 0 ) {
1812             $status = "linked_analytics";
1813         }
1814         else {
1815             $status = 1;
1816         }
1817     }
1818     return $status;
1819 }
1820
1821 =head2 DelItemCheck
1822
1823    DelItemCheck( $biblionumber, $itemnumber);
1824
1825 Exported function (core API) for deleting an item record in Koha if there no current issue.
1826
1827 DelItemCheck wraps ItemSafeToDelete around DelItem.
1828
1829 =cut
1830
1831 sub DelItemCheck {
1832     my ( $biblionumber, $itemnumber ) = @_;
1833     my $status = ItemSafeToDelete( $biblionumber, $itemnumber );
1834
1835     if ( $status == 1 ) {
1836         DelItem(
1837             {
1838                 biblionumber => $biblionumber,
1839                 itemnumber   => $itemnumber
1840             }
1841         );
1842     }
1843     return $status;
1844 }
1845
1846 =head2 _koha_modify_item
1847
1848   my ($itemnumber,$error) =_koha_modify_item( $item );
1849
1850 Perform the actual update of the C<items> row.  Note that this
1851 routine accepts a hashref specifying the columns to update.
1852
1853 =cut
1854
1855 sub _koha_modify_item {
1856     my ( $item ) = @_;
1857     my $dbh=C4::Context->dbh;  
1858     my $error;
1859
1860     my $query = "UPDATE items SET ";
1861     my @bind;
1862     _mod_item_dates( $item );
1863     for my $key ( keys %$item ) {
1864         next if ( $key eq 'itemnumber' );
1865         $query.="$key=?,";
1866         push @bind, $item->{$key};
1867     }
1868     $query =~ s/,$//;
1869     $query .= " WHERE itemnumber=?";
1870     push @bind, $item->{'itemnumber'};
1871     my $sth = $dbh->prepare($query);
1872     $sth->execute(@bind);
1873     if ( $sth->err ) {
1874         $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
1875         warn $error;
1876     }
1877     return ($item->{'itemnumber'},$error);
1878 }
1879
1880 sub _mod_item_dates { # date formatting for date fields in item hash
1881     my ( $item ) = @_;
1882     return if !$item || ref($item) ne 'HASH';
1883
1884     my @keys = grep
1885         { $_ =~ /^onloan$|^date|date$|datetime$/ }
1886         keys %$item;
1887     # Incl. dateaccessioned,replacementpricedate,datelastborrowed,datelastseen
1888     # NOTE: We do not (yet) have items fields ending with datetime
1889     # Fields with _on$ have been handled already
1890
1891     foreach my $key ( @keys ) {
1892         next if !defined $item->{$key}; # skip undefs
1893         my $dt = eval { dt_from_string( $item->{$key} ) };
1894             # eval: dt_from_string will die on us if we pass illegal dates
1895
1896         my $newstr;
1897         if( defined $dt  && ref($dt) eq 'DateTime' ) {
1898             if( $key =~ /datetime/ ) {
1899                 $newstr = DateTime::Format::MySQL->format_datetime($dt);
1900             } else {
1901                 $newstr = DateTime::Format::MySQL->format_date($dt);
1902             }
1903         }
1904         $item->{$key} = $newstr; # might be undef to clear garbage
1905     }
1906 }
1907
1908 =head2 _koha_delete_item
1909
1910   _koha_delete_item( $itemnum );
1911
1912 Internal function to delete an item record from the koha tables
1913
1914 =cut
1915
1916 sub _koha_delete_item {
1917     my ( $itemnum ) = @_;
1918
1919     my $dbh = C4::Context->dbh;
1920     # save the deleted item to deleteditems table
1921     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1922     $sth->execute($itemnum);
1923     my $data = $sth->fetchrow_hashref();
1924
1925     # There is no item to delete
1926     return 0 unless $data;
1927
1928     my $query = "INSERT INTO deleteditems SET ";
1929     my @bind  = ();
1930     foreach my $key ( keys %$data ) {
1931         next if ( $key eq 'timestamp' ); # timestamp will be set by db
1932         $query .= "$key = ?,";
1933         push( @bind, $data->{$key} );
1934     }
1935     $query =~ s/\,$//;
1936     $sth = $dbh->prepare($query);
1937     $sth->execute(@bind);
1938
1939     # delete from items table
1940     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1941     my $deleted = $sth->execute($itemnum);
1942     return ( $deleted == 1 ) ? 1 : 0;
1943 }
1944
1945 =head2 _marc_from_item_hash
1946
1947   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1948
1949 Given an item hash representing a complete item record,
1950 create a C<MARC::Record> object containing an embedded
1951 tag representing that item.
1952
1953 The third, optional parameter C<$unlinked_item_subfields> is
1954 an arrayref of subfields (not mapped to C<items> fields per the
1955 framework) to be added to the MARC representation
1956 of the item.
1957
1958 =cut
1959
1960 sub _marc_from_item_hash {
1961     my $item = shift;
1962     my $frameworkcode = shift;
1963     my $unlinked_item_subfields;
1964     if (@_) {
1965         $unlinked_item_subfields = shift;
1966     }
1967    
1968     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1969     # Also, don't emit a subfield if the underlying field is blank.
1970     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
1971                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
1972                                 : ()  } keys %{ $item } }; 
1973
1974     my $item_marc = MARC::Record->new();
1975     foreach my $item_field ( keys %{$mungeditem} ) {
1976         my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField( $item_field, $frameworkcode );
1977         next unless defined $tag and defined $subfield;    # skip if not mapped to MARC field
1978         my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
1979         foreach my $value (@values){
1980             if ( my $field = $item_marc->field($tag) ) {
1981                     $field->add_subfields( $subfield => $value );
1982             } else {
1983                 my $add_subfields = [];
1984                 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1985                     $add_subfields = $unlinked_item_subfields;
1986             }
1987             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
1988             }
1989         }
1990     }
1991
1992     return $item_marc;
1993 }
1994
1995 =head2 _repack_item_errors
1996
1997 Add an error message hash generated by C<CheckItemPreSave>
1998 to a list of errors.
1999
2000 =cut
2001
2002 sub _repack_item_errors {
2003     my $item_sequence_num = shift;
2004     my $item_ref = shift;
2005     my $error_ref = shift;
2006
2007     my @repacked_errors = ();
2008
2009     foreach my $error_code (sort keys %{ $error_ref }) {
2010         my $repacked_error = {};
2011         $repacked_error->{'item_sequence'} = $item_sequence_num;
2012         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2013         $repacked_error->{'error_code'} = $error_code;
2014         $repacked_error->{'error_information'} = $error_ref->{$error_code};
2015         push @repacked_errors, $repacked_error;
2016     } 
2017
2018     return @repacked_errors;
2019 }
2020
2021 =head2 _get_unlinked_item_subfields
2022
2023   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2024
2025 =cut
2026
2027 sub _get_unlinked_item_subfields {
2028     my $original_item_marc = shift;
2029     my $frameworkcode = shift;
2030
2031     my $marcstructure = GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
2032
2033     # assume that this record has only one field, and that that
2034     # field contains only the item information
2035     my $subfields = [];
2036     my @fields = $original_item_marc->fields();
2037     if ($#fields > -1) {
2038         my $field = $fields[0];
2039             my $tag = $field->tag();
2040         foreach my $subfield ($field->subfields()) {
2041             if (defined $subfield->[1] and
2042                 $subfield->[1] ne '' and
2043                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2044                 push @$subfields, $subfield->[0] => $subfield->[1];
2045             }
2046         }
2047     }
2048     return $subfields;
2049 }
2050
2051 =head2 _get_unlinked_subfields_xml
2052
2053   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2054
2055 =cut
2056
2057 sub _get_unlinked_subfields_xml {
2058     my $unlinked_item_subfields = shift;
2059
2060     my $xml;
2061     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2062         my $marc = MARC::Record->new();
2063         # use of tag 999 is arbitrary, and doesn't need to match the item tag
2064         # used in the framework
2065         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2066         $marc->encoding("UTF-8");    
2067         $xml = $marc->as_xml("USMARC");
2068     }
2069
2070     return $xml;
2071 }
2072
2073 =head2 _parse_unlinked_item_subfields_from_xml
2074
2075   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2076
2077 =cut
2078
2079 sub  _parse_unlinked_item_subfields_from_xml {
2080     my $xml = shift;
2081     require C4::Charset;
2082     return unless defined $xml and $xml ne "";
2083     my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2084     my $unlinked_subfields = [];
2085     my @fields = $marc->fields();
2086     if ($#fields > -1) {
2087         foreach my $subfield ($fields[0]->subfields()) {
2088             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2089         }
2090     }
2091     return $unlinked_subfields;
2092 }
2093
2094 =head2 GetAnalyticsCount
2095
2096   $count= &GetAnalyticsCount($itemnumber)
2097
2098 counts Usage of itemnumber in Analytical bibliorecords. 
2099
2100 =cut
2101
2102 sub GetAnalyticsCount {
2103     my ($itemnumber) = @_;
2104
2105     ### ZOOM search here
2106     my $query;
2107     $query= "hi=".$itemnumber;
2108     my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
2109     my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
2110     return ($result);
2111 }
2112
2113 =head2 SearchItemsByField
2114
2115     my $items = SearchItemsByField($field, $value);
2116
2117 SearchItemsByField will search for items on a specific given field.
2118 For instance you can search all items with a specific stocknumber like this:
2119
2120     my $items = SearchItemsByField('stocknumber', $stocknumber);
2121
2122 =cut
2123
2124 sub SearchItemsByField {
2125     my ($field, $value) = @_;
2126
2127     my $filters = {
2128         field => $field,
2129         query => $value,
2130     };
2131
2132     my ($results) = SearchItems($filters);
2133     return $results;
2134 }
2135
2136 sub _SearchItems_build_where_fragment {
2137     my ($filter) = @_;
2138
2139     my $dbh = C4::Context->dbh;
2140
2141     my $where_fragment;
2142     if (exists($filter->{conjunction})) {
2143         my (@where_strs, @where_args);
2144         foreach my $f (@{ $filter->{filters} }) {
2145             my $fragment = _SearchItems_build_where_fragment($f);
2146             if ($fragment) {
2147                 push @where_strs, $fragment->{str};
2148                 push @where_args, @{ $fragment->{args} };
2149             }
2150         }
2151         my $where_str = '';
2152         if (@where_strs) {
2153             $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
2154             $where_fragment = {
2155                 str => $where_str,
2156                 args => \@where_args,
2157             };
2158         }
2159     } else {
2160         my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2161         push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2162         push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2163         my @operators = qw(= != > < >= <= like);
2164         my $field = $filter->{field};
2165         if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
2166             my $op = $filter->{operator};
2167             my $query = $filter->{query};
2168
2169             if (!$op or (0 == grep /^$op$/, @operators)) {
2170                 $op = '='; # default operator
2171             }
2172
2173             my $column;
2174             if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
2175                 my $marcfield = $1;
2176                 my $marcsubfield = $2;
2177                 my ($kohafield) = $dbh->selectrow_array(q|
2178                     SELECT kohafield FROM marc_subfield_structure
2179                     WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
2180                 |, undef, $marcfield, $marcsubfield);
2181
2182                 if ($kohafield) {
2183                     $column = $kohafield;
2184                 } else {
2185                     # MARC field is not linked to a DB field so we need to use
2186                     # ExtractValue on marcxml from biblio_metadata or
2187                     # items.more_subfields_xml, depending on the MARC field.
2188                     my $xpath;
2189                     my $sqlfield;
2190                     my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber');
2191                     if ($marcfield eq $itemfield) {
2192                         $sqlfield = 'more_subfields_xml';
2193                         $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
2194                     } else {
2195                         $sqlfield = 'metadata'; # From biblio_metadata
2196                         if ($marcfield < 10) {
2197                             $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
2198                         } else {
2199                             $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
2200                         }
2201                     }
2202                     $column = "ExtractValue($sqlfield, '$xpath')";
2203                 }
2204             } else {
2205                 $column = $field;
2206             }
2207
2208             if (ref $query eq 'ARRAY') {
2209                 if ($op eq '=') {
2210                     $op = 'IN';
2211                 } elsif ($op eq '!=') {
2212                     $op = 'NOT IN';
2213                 }
2214                 $where_fragment = {
2215                     str => "$column $op (" . join (',', ('?') x @$query) . ")",
2216                     args => $query,
2217                 };
2218             } else {
2219                 $where_fragment = {
2220                     str => "$column $op ?",
2221                     args => [ $query ],
2222                 };
2223             }
2224         }
2225     }
2226
2227     return $where_fragment;
2228 }
2229
2230 =head2 SearchItems
2231
2232     my ($items, $total) = SearchItems($filter, $params);
2233
2234 Perform a search among items
2235
2236 $filter is a reference to a hash which can be a filter, or a combination of filters.
2237
2238 A filter has the following keys:
2239
2240 =over 2
2241
2242 =item * field: the name of a SQL column in table items
2243
2244 =item * query: the value to search in this column
2245
2246 =item * operator: comparison operator. Can be one of = != > < >= <= like
2247
2248 =back
2249
2250 A combination of filters hash the following keys:
2251
2252 =over 2
2253
2254 =item * conjunction: 'AND' or 'OR'
2255
2256 =item * filters: array ref of filters
2257
2258 =back
2259
2260 $params is a reference to a hash that can contain the following parameters:
2261
2262 =over 2
2263
2264 =item * rows: Number of items to return. 0 returns everything (default: 0)
2265
2266 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2267                (default: 1)
2268
2269 =item * sortby: A SQL column name in items table to sort on
2270
2271 =item * sortorder: 'ASC' or 'DESC'
2272
2273 =back
2274
2275 =cut
2276
2277 sub SearchItems {
2278     my ($filter, $params) = @_;
2279
2280     $filter //= {};
2281     $params //= {};
2282     return unless ref $filter eq 'HASH';
2283     return unless ref $params eq 'HASH';
2284
2285     # Default parameters
2286     $params->{rows} ||= 0;
2287     $params->{page} ||= 1;
2288     $params->{sortby} ||= 'itemnumber';
2289     $params->{sortorder} ||= 'ASC';
2290
2291     my ($where_str, @where_args);
2292     my $where_fragment = _SearchItems_build_where_fragment($filter);
2293     if ($where_fragment) {
2294         $where_str = $where_fragment->{str};
2295         @where_args = @{ $where_fragment->{args} };
2296     }
2297
2298     my $dbh = C4::Context->dbh;
2299     my $query = q{
2300         SELECT SQL_CALC_FOUND_ROWS items.*
2301         FROM items
2302           LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2303           LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2304           LEFT JOIN biblio_metadata ON biblio_metadata.biblionumber = biblio.biblionumber
2305           WHERE 1
2306     };
2307     if (defined $where_str and $where_str ne '') {
2308         $query .= qq{ AND $where_str };
2309     }
2310
2311     $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.marcflavour = ? };
2312     push @where_args, C4::Context->preference('marcflavour');
2313
2314     my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2315     push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2316     push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2317     my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
2318         ? $params->{sortby} : 'itemnumber';
2319     my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
2320     $query .= qq{ ORDER BY $sortby $sortorder };
2321
2322     my $rows = $params->{rows};
2323     my @limit_args;
2324     if ($rows > 0) {
2325         my $offset = $rows * ($params->{page}-1);
2326         $query .= qq { LIMIT ?, ? };
2327         push @limit_args, $offset, $rows;
2328     }
2329
2330     my $sth = $dbh->prepare($query);
2331     my $rv = $sth->execute(@where_args, @limit_args);
2332
2333     return unless ($rv);
2334     my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2335
2336     return ($sth->fetchall_arrayref({}), $total_rows);
2337 }
2338
2339
2340 =head1  OTHER FUNCTIONS
2341
2342 =head2 _find_value
2343
2344   ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2345
2346 Find the given $subfield in the given $tag in the given
2347 MARC::Record $record.  If the subfield is found, returns
2348 the (indicators, value) pair; otherwise, (undef, undef) is
2349 returned.
2350
2351 PROPOSITION :
2352 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2353 I suggest we export it from this module.
2354
2355 =cut
2356
2357 sub _find_value {
2358     my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2359     my @result;
2360     my $indicator;
2361     if ( $tagfield < 10 ) {
2362         if ( $record->field($tagfield) ) {
2363             push @result, $record->field($tagfield)->data();
2364         } else {
2365             push @result, "";
2366         }
2367     } else {
2368         foreach my $field ( $record->field($tagfield) ) {
2369             my @subfields = $field->subfields();
2370             foreach my $subfield (@subfields) {
2371                 if ( @$subfield[0] eq $insubfield ) {
2372                     push @result, @$subfield[1];
2373                     $indicator = $field->indicator(1) . $field->indicator(2);
2374                 }
2375             }
2376         }
2377     }
2378     return ( $indicator, @result );
2379 }
2380
2381
2382 =head2 PrepareItemrecordDisplay
2383
2384   PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2385
2386 Returns a hash with all the fields for Display a given item data in a template
2387
2388 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2389
2390 =cut
2391
2392 sub PrepareItemrecordDisplay {
2393
2394     my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2395
2396     my $dbh = C4::Context->dbh;
2397     $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum;
2398     my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2399
2400     # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
2401     # a shared data structure. No plugin (including custom ones) should change
2402     # its contents. See also GetMarcStructure.
2403     my $tagslib = GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
2404
2405     # return nothing if we don't have found an existing framework.
2406     return q{} unless $tagslib;
2407     my $itemrecord;
2408     if ($itemnum) {
2409         $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2410     }
2411     my @loop_data;
2412
2413     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2414     my $query = qq{
2415         SELECT authorised_value,lib FROM authorised_values
2416     };
2417     $query .= qq{
2418         LEFT JOIN authorised_values_branches ON ( id = av_id )
2419     } if $branch_limit;
2420     $query .= qq{
2421         WHERE category = ?
2422     };
2423     $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2424     $query .= qq{ ORDER BY lib};
2425     my $authorised_values_sth = $dbh->prepare( $query );
2426     foreach my $tag ( sort keys %{$tagslib} ) {
2427         if ( $tag ne '' ) {
2428
2429             # loop through each subfield
2430             my $cntsubf;
2431             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2432                 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
2433                 next unless ( $tagslib->{$tag}->{$subfield}->{'tab'} );
2434                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2435                 my %subfield_data;
2436                 $subfield_data{tag}           = $tag;
2437                 $subfield_data{subfield}      = $subfield;
2438                 $subfield_data{countsubfield} = $cntsubf++;
2439                 $subfield_data{kohafield}     = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2440                 $subfield_data{id}            = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2441
2442                 #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2443                 $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
2444                 $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
2445                 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2446                 $subfield_data{hidden}     = "display:none"
2447                   if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
2448                     || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
2449                 my ( $x, $defaultvalue );
2450                 if ($itemrecord) {
2451                     ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2452                 }
2453                 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2454                 if ( !defined $defaultvalue ) {
2455                     $defaultvalue = q||;
2456                 } else {
2457                     $defaultvalue =~ s/"/&quot;/g;
2458                 }
2459
2460                 # search for itemcallnumber if applicable
2461                 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2462                     && C4::Context->preference('itemcallnumber') ) {
2463                     my $CNtag      = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2464                     my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2465                     if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2466                         $defaultvalue = $field->subfield($CNsubfield);
2467                     }
2468                 }
2469                 if (   $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2470                     && $defaultvalues
2471                     && $defaultvalues->{'callnumber'} ) {
2472                     if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ){
2473                         # if the item record exists, only use default value if the item has no callnumber
2474                         $defaultvalue = $defaultvalues->{callnumber};
2475                     } elsif ( !$itemrecord and $defaultvalues ) {
2476                         # if the item record *doesn't* exists, always use the default value
2477                         $defaultvalue = $defaultvalues->{callnumber};
2478                     }
2479                 }
2480                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2481                     && $defaultvalues
2482                     && $defaultvalues->{'branchcode'} ) {
2483                     if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2484                         $defaultvalue = $defaultvalues->{branchcode};
2485                     }
2486                 }
2487                 if (   ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2488                     && $defaultvalues
2489                     && $defaultvalues->{'location'} ) {
2490
2491                     if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2492                         # if the item record exists, only use default value if the item has no locationr
2493                         $defaultvalue = $defaultvalues->{location};
2494                     } elsif ( !$itemrecord and $defaultvalues ) {
2495                         # if the item record *doesn't* exists, always use the default value
2496                         $defaultvalue = $defaultvalues->{location};
2497                     }
2498                 }
2499                 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2500                     my @authorised_values;
2501                     my %authorised_lib;
2502
2503                     # builds list, depending on authorised value...
2504                     #---- branch
2505                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2506                         if (   ( C4::Context->preference("IndependentBranches") )
2507                             && !C4::Context->IsSuperLibrarian() ) {
2508                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2509                             $sth->execute( C4::Context->userenv->{branch} );
2510                             push @authorised_values, ""
2511                               unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2512                             while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2513                                 push @authorised_values, $branchcode;
2514                                 $authorised_lib{$branchcode} = $branchname;
2515                             }
2516                         } else {
2517                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2518                             $sth->execute;
2519                             push @authorised_values, ""
2520                               unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2521                             while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2522                                 push @authorised_values, $branchcode;
2523                                 $authorised_lib{$branchcode} = $branchname;
2524                             }
2525                         }
2526
2527                         $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2528                         if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2529                             $defaultvalue = $defaultvalues->{branchcode};
2530                         }
2531
2532                         #----- itemtypes
2533                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2534                         my $itemtypes = Koha::ItemTypes->search_with_localization;
2535                         push @authorised_values, ""
2536                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2537                         while ( my $itemtype = $itemtypes->next ) {
2538                             push @authorised_values, $itemtype->itemtype;
2539                             $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
2540                         }
2541                         if ($defaultvalues && $defaultvalues->{'itemtype'}) {
2542                             $defaultvalue = $defaultvalues->{'itemtype'};
2543                         }
2544
2545                         #---- class_sources
2546                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2547                         push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2548
2549                         my $class_sources = GetClassSources();
2550                         my $default_source = C4::Context->preference("DefaultClassificationSource");
2551
2552                         foreach my $class_source (sort keys %$class_sources) {
2553                             next unless $class_sources->{$class_source}->{'used'} or
2554                                         ($class_source eq $default_source);
2555                             push @authorised_values, $class_source;
2556                             $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2557                         }
2558
2559                         $defaultvalue = $default_source;
2560
2561                         #---- "true" authorised value
2562                     } else {
2563                         $authorised_values_sth->execute(
2564                             $tagslib->{$tag}->{$subfield}->{authorised_value},
2565                             $branch_limit ? $branch_limit : ()
2566                         );
2567                         push @authorised_values, ""
2568                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2569                         while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2570                             push @authorised_values, $value;
2571                             $authorised_lib{$value} = $lib;
2572                         }
2573                     }
2574                     $subfield_data{marc_value} = {
2575                         type    => 'select',
2576                         values  => \@authorised_values,
2577                         default => "$defaultvalue",
2578                         labels  => \%authorised_lib,
2579                     };
2580                 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2581                 # it is a plugin
2582                     require Koha::FrameworkPlugin;
2583                     my $plugin = Koha::FrameworkPlugin->new({
2584                         name => $tagslib->{$tag}->{$subfield}->{value_builder},
2585                         item_style => 1,
2586                     });
2587                     my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
2588                     $plugin->build( $pars );
2589                     if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
2590                         $defaultvalue = $field->subfield($subfield);
2591                     }
2592                     if( !$plugin->errstr ) {
2593                         #TODO Move html to template; see report 12176/13397
2594                         my $tab= $plugin->noclick? '-1': '';
2595                         my $class= $plugin->noclick? ' disabled': '';
2596                         my $title= $plugin->noclick? 'No popup': 'Tag editor';
2597                         $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
2598                     } else {
2599                         warn $plugin->errstr;
2600                         $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />); # supply default input form
2601                     }
2602                 }
2603                 elsif ( $tag eq '' ) {       # it's an hidden field
2604                     $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
2605                 }
2606                 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
2607                     $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
2608                 }
2609                 elsif ( length($defaultvalue) > 100
2610                             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2611                                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
2612                             or (C4::Context->preference("marcflavour") eq "MARC21"  and
2613                                   500 <= $tag && $tag < 600                     )
2614                           ) {
2615                     # oversize field (textarea)
2616                     $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255">$defaultvalue</textarea>\n");
2617                 } else {
2618                     $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2619                 }
2620                 push( @loop_data, \%subfield_data );
2621             }
2622         }
2623     }
2624     my $itemnumber;
2625     if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2626         $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2627     }
2628     return {
2629         'itemtagfield'    => $itemtagfield,
2630         'itemtagsubfield' => $itemtagsubfield,
2631         'itemnumber'      => $itemnumber,
2632         'iteminformation' => \@loop_data
2633     };
2634 }
2635
2636 sub ToggleNewStatus {
2637     my ( $params ) = @_;
2638     my @rules = @{ $params->{rules} };
2639     my $report_only = $params->{report_only};
2640
2641     my $dbh = C4::Context->dbh;
2642     my @errors;
2643     my @item_columns = map { "items.$_" } Koha::Items->columns;
2644     my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
2645     my $report;
2646     for my $rule ( @rules ) {
2647         my $age = $rule->{age};
2648         my $conditions = $rule->{conditions};
2649         my $substitutions = $rule->{substitutions};
2650         my @params;
2651
2652         my $query = q|
2653             SELECT items.biblionumber, items.itemnumber
2654             FROM items
2655             LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
2656             WHERE 1
2657         |;
2658         for my $condition ( @$conditions ) {
2659             if (
2660                  grep {/^$condition->{field}$/} @item_columns
2661               or grep {/^$condition->{field}$/} @biblioitem_columns
2662             ) {
2663                 if ( $condition->{value} =~ /\|/ ) {
2664                     my @values = split /\|/, $condition->{value};
2665                     $query .= qq| AND $condition->{field} IN (|
2666                         . join( ',', ('?') x scalar @values )
2667                         . q|)|;
2668                     push @params, @values;
2669                 } else {
2670                     $query .= qq| AND $condition->{field} = ?|;
2671                     push @params, $condition->{value};
2672                 }
2673             }
2674         }
2675         if ( defined $age ) {
2676             $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
2677             push @params, $age;
2678         }
2679         my $sth = $dbh->prepare($query);
2680         $sth->execute( @params );
2681         while ( my $values = $sth->fetchrow_hashref ) {
2682             my $biblionumber = $values->{biblionumber};
2683             my $itemnumber = $values->{itemnumber};
2684             my $item = C4::Items::GetItem( $itemnumber );
2685             for my $substitution ( @$substitutions ) {
2686                 next unless $substitution->{field};
2687                 C4::Items::ModItem( {$substitution->{field} => $substitution->{value}}, $biblionumber, $itemnumber )
2688                     unless $report_only;
2689                 push @{ $report->{$itemnumber} }, $substitution;
2690             }
2691         }
2692     }
2693
2694     return $report;
2695 }
2696
2697
2698 1;