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