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