Bug 22330: Transfer limits should be respected for placing holds in staff interface...
[koha.git] / C4 / Items.pm
index f4e6d65..611c63e 100644 (file)
@@ -21,80 +21,65 @@ package C4::Items;
 use strict;
 #use warnings; FIXME - Bug 2505
 
 use strict;
 #use warnings; FIXME - Bug 2505
 
-use Carp;
-use C4::Context;
-use C4::Koha;
-use C4::Biblio;
-use Koha::DateUtils;
-use MARC::Record;
-use C4::ClassSource;
-use C4::Log;
-use List::MoreUtils qw/any/;
-use YAML qw/Load/;
-use DateTime::Format::MySQL;
-use Data::Dumper; # used as part of logging item record changes, not just for
-                  # debugging; so please don't remove this
-
-use Koha::AuthorisedValues;
-use Koha::DateUtils qw/dt_from_string/;
-use Koha::Database;
-
-use Koha::Biblioitems;
-use Koha::Items;
-use Koha::ItemTypes;
-use Koha::SearchEngine;
-use Koha::SearchEngine::Search;
-use Koha::Libraries;
-
 use vars qw(@ISA @EXPORT);
 use vars qw(@ISA @EXPORT);
-
 BEGIN {
 BEGIN {
+    require Exporter;
+    @ISA = qw(Exporter);
 
 
-       require Exporter;
-    @ISA = qw( Exporter );
-
-    # function exports
     @EXPORT = qw(
     @EXPORT = qw(
-        GetItem
         AddItemFromMarc
         AddItem
         AddItemBatchFromMarc
         ModItemFromMarc
         AddItemFromMarc
         AddItem
         AddItemBatchFromMarc
         ModItemFromMarc
-    Item2Marc
+        Item2Marc
         ModItem
         ModDateLastSeen
         ModItemTransfer
         DelItem
         ModItem
         ModDateLastSeen
         ModItemTransfer
         DelItem
-    
         CheckItemPreSave
         CheckItemPreSave
-    
         GetItemsForInventory
         GetItemsForInventory
-        GetItemsByBiblioitemnumber
         GetItemsInfo
         GetItemsInfo
-       GetItemsLocationInfo
-       GetHostItemsInfo
-        GetItemnumbersForBiblio
-       get_hostitemnumbers_of
-        GetBarcodeFromItemnumber
+        GetItemsLocationInfo
+        GetHostItemsInfo
+        get_hostitemnumbers_of
         GetHiddenItemnumbers
         ItemSafeToDelete
         DelItemCheck
         GetHiddenItemnumbers
         ItemSafeToDelete
         DelItemCheck
-    MoveItemFromBiblio
-    GetLatestAcquisitions
-
+        MoveItemFromBiblio
         CartToShelf
         ShelfToCart
         CartToShelf
         ShelfToCart
-
-       GetAnalyticsCount
-
+        GetAnalyticsCount
         SearchItemsByField
         SearchItems
         SearchItemsByField
         SearchItems
-
         PrepareItemrecordDisplay
         PrepareItemrecordDisplay
-
     );
 }
 
     );
 }
 
+use Carp;
+use C4::Context;
+use C4::Koha;
+use C4::Biblio;
+use Koha::DateUtils;
+use MARC::Record;
+use C4::ClassSource;
+use C4::Log;
+use List::MoreUtils qw(any);
+use YAML qw(Load);
+use DateTime::Format::MySQL;
+use Data::Dumper; # used as part of logging item record changes, not just for
+                  # debugging; so please don't remove this
+
+use Koha::AuthorisedValues;
+use Koha::DateUtils qw(dt_from_string);
+use Koha::Database;
+
+use Koha::Biblioitems;
+use Koha::Items;
+use Koha::ItemTypes;
+use Koha::SearchEngine;
+use Koha::SearchEngine::Search;
+use Koha::Libraries;
+
 =head1 NAME
 
 C4::Items - item management functions
 =head1 NAME
 
 C4::Items - item management functions
@@ -114,12 +99,6 @@ indexed (e.g., by Zebra), but means that each item
 modification transaction must keep the items table
 and the MARC XML in sync at all times.
 
 modification transaction must keep the items table
 and the MARC XML in sync at all times.
 
-Consequently, all code that creates, modifies, or deletes
-item records B<must> use an appropriate function from 
-C<C4::Items>.  If no existing function is suitable, it is
-better to add one to C<C4::Items> than to use add
-one-off SQL statements to add or modify items.
-
 The items table will be considered authoritative.  In other
 words, if there is ever a discrepancy between the items
 table and the MARC XML, the items table should be considered
 The items table will be considered authoritative.  In other
 words, if there is ever a discrepancy between the items
 table and the MARC XML, the items table should be considered
@@ -137,41 +116,6 @@ of C<C4::Items>
 
 =cut
 
 
 =cut
 
-=head2 GetItem
-
-  $item = GetItem($itemnumber,$barcode,$serial);
-
-Return item information, for a given itemnumber or barcode.
-The return value is a hashref mapping item column
-names to values.  If C<$serial> is true, include serial publication data.
-
-=cut
-
-sub GetItem {
-    my ($itemnumber,$barcode, $serial) = @_;
-    my $dbh = C4::Context->dbh;
-
-    my $item;
-    if ($itemnumber) {
-        $item = Koha::Items->find( $itemnumber );
-    } else {
-        $item = Koha::Items->find( { barcode => $barcode } );
-    }
-
-    return unless ( $item );
-
-    my $data = $item->unblessed();
-    $data->{itype} = $item->effective_itemtype(); # set the correct itype
-
-    if ($serial) {
-        my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
-        $ssth->execute( $data->{'itemnumber'} );
-        ( $data->{'serialseq'}, $data->{'publisheddate'} ) = $ssth->fetchrow_array();
-    }
-
-    return $data;
-}    # sub GetItem
-
 =head2 CartToShelf
 
   CartToShelf($itemnumber);
 =head2 CartToShelf
 
   CartToShelf($itemnumber);
@@ -191,10 +135,9 @@ sub CartToShelf {
         croak "FAILED CartToShelf() - no itemnumber supplied";
     }
 
         croak "FAILED CartToShelf() - no itemnumber supplied";
     }
 
-    my $item = GetItem($itemnumber);
-    if ( $item->{location} eq 'CART' ) {
-        $item->{location} = $item->{permanent_location};
-        ModItem($item, undef, $itemnumber);
+    my $item = Koha::Items->find($itemnumber);
+    if ( $item->location eq 'CART' ) {
+        ModItem({ location => $item->permanent_location}, undef, $itemnumber);
     }
 }
 
     }
 }
 
@@ -214,9 +157,7 @@ sub ShelfToCart {
         croak "FAILED ShelfToCart() - no itemnumber supplied";
     }
 
         croak "FAILED ShelfToCart() - no itemnumber supplied";
     }
 
-    my $item = GetItem($itemnumber);
-    $item->{'location'} = 'CART';
-    ModItem($item, undef, $itemnumber);
+    ModItem({ location => 'CART'}, undef, $itemnumber);
 }
 
 =head2 AddItemFromMarc
 }
 
 =head2 AddItemFromMarc
@@ -234,14 +175,14 @@ sub AddItemFromMarc {
     my $dbh = C4::Context->dbh;
 
     # parse item hash from MARC
     my $dbh = C4::Context->dbh;
 
     # parse item hash from MARC
-    my $frameworkcode = C4::Biblio::GetFrameworkCode( $biblionumber );
-    my ($itemtag,$itemsubfield)=C4::Biblio::GetMarcFromKohaField("items.itemnumber",$frameworkcode);
-       
-       my $localitemmarc=MARC::Record->new;
-       $localitemmarc->append_fields($source_item_marc->field($itemtag));
-    my $item = &TransformMarcToKoha( $localitemmarc, $frameworkcode ,'items');
-    my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
-    return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
+    my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
+    my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
+
+    my $localitemmarc = MARC::Record->new;
+    $localitemmarc->append_fields( $source_item_marc->field($itemtag) );
+    my $item = C4::Biblio::TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
+    my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
+    return AddItem( $item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields );
 }
 
 =head2 AddItem
 }
 
 =head2 AddItem
@@ -298,7 +239,7 @@ sub AddItem {
 
     $item->{'itemnumber'} = $itemnumber;
 
 
     $item->{'itemnumber'} = $itemnumber;
 
-    ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
+    C4::Biblio::ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
 
     logaction( "CATALOGUING", "ADD", $itemnumber, "item" )
       if C4::Context->preference("CataloguingLog");
 
     logaction( "CATALOGUING", "ADD", $itemnumber, "item" )
       if C4::Context->preference("CataloguingLog");
@@ -501,7 +442,7 @@ sub ModItemFromMarc {
 
     my $localitemmarc = MARC::Record->new;
     $localitemmarc->append_fields( $item_marc->field($itemtag) );
 
     my $localitemmarc = MARC::Record->new;
     $localitemmarc->append_fields( $item_marc->field($itemtag) );
-    my $item = &TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
+    my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
     my $default_values = _build_default_values_for_mod_marc();
     foreach my $item_field ( keys %$default_values ) {
         $item->{$item_field} = $default_values->{$item_field}
     my $default_values = _build_default_values_for_mod_marc();
     foreach my $item_field ( keys %$default_values ) {
         $item->{$item_field} = $default_values->{$item_field}
@@ -525,8 +466,7 @@ ModItem(
     }
 );
 
     }
 );
 
-Change one or more columns in an item record and update
-the MARC representation of the item.
+Change one or more columns in an item record.
 
 The first argument is a hashref mapping from item column
 names to the new values.  The second and third arguments
 
 The first argument is a hashref mapping from item column
 names to the new values.  The second and third arguments
@@ -556,6 +496,9 @@ sub ModItem {
     my $log_action = $additional_params->{log_action} // 1;
     my $unlinked_item_subfields = $additional_params->{unlinked_item_subfields};
 
     my $log_action = $additional_params->{log_action} // 1;
     my $unlinked_item_subfields = $additional_params->{unlinked_item_subfields};
 
+    return unless %$item;
+    $item->{'itemnumber'} = $itemnumber or return;
+
     # if $biblionumber is undefined, get it from the current item
     unless (defined $biblionumber) {
         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
     # if $biblionumber is undefined, get it from the current item
     unless (defined $biblionumber) {
         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
@@ -565,16 +508,14 @@ sub ModItem {
         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
     };
 
         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
     };
 
-    $item->{'itemnumber'} = $itemnumber or return;
-
     my @fields = qw( itemlost withdrawn damaged );
 
     my @fields = qw( itemlost withdrawn damaged );
 
-    # Only call GetItem if we need to set an "on" date field
+    # Only retrieve the item if we need to set an "on" date field
     if ( $item->{itemlost} || $item->{withdrawn} || $item->{damaged} ) {
     if ( $item->{itemlost} || $item->{withdrawn} || $item->{damaged} ) {
-        my $pre_mod_item = GetItem( $item->{'itemnumber'} );
+        my $pre_mod_item = Koha::Items->find( $item->{'itemnumber'} );
         for my $field (@fields) {
             if (    defined( $item->{$field} )
         for my $field (@fields) {
             if (    defined( $item->{$field} )
-                and not $pre_mod_item->{$field}
+                and not $pre_mod_item->$field
                 and $item->{$field} )
             {
                 $item->{ $field . '_on' } =
                 and $item->{$field} )
             {
                 $item->{ $field . '_on' } =
@@ -637,7 +578,7 @@ sub ModItemTransfer {
         VALUES (?, ?, NOW(), ?)");
     $sth->execute($itemnumber, $frombranch, $tobranch);
 
         VALUES (?, ?, NOW(), ?)");
     $sth->execute($itemnumber, $frombranch, $tobranch);
 
-    ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
+    ModItem({ holdingbranch => $tobranch }, undef, $itemnumber, { log_action => 0 });
     ModDateLastSeen($itemnumber);
     return;
 }
     ModDateLastSeen($itemnumber);
     return;
 }
@@ -780,11 +721,6 @@ The following functions provide various ways of
 getting an item record, a set of item records, or
 lists of authorized values for certain item fields.
 
 getting an item record, a set of item records, or
 lists of authorized values for certain item fields.
 
-Some of the functions in this group are candidates
-for refactoring -- for example, some of the code
-in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
-has copy-and-paste work.
-
 =cut
 
 =head2 GetItemsForInventory
 =cut
 
 =head2 GetItemsForInventory
@@ -822,6 +758,7 @@ sub GetItemsForInventory {
     my ( $parameters ) = @_;
     my $minlocation  = $parameters->{'minlocation'}  // '';
     my $maxlocation  = $parameters->{'maxlocation'}  // '';
     my ( $parameters ) = @_;
     my $minlocation  = $parameters->{'minlocation'}  // '';
     my $maxlocation  = $parameters->{'maxlocation'}  // '';
+    my $class_source = $parameters->{'class_source'}  // C4::Context->preference('DefaultClassificationSource');
     my $location     = $parameters->{'location'}     // '';
     my $itemtype     = $parameters->{'itemtype'}     // '';
     my $ignoreissued = $parameters->{'ignoreissued'} // '';
     my $location     = $parameters->{'location'}     // '';
     my $itemtype     = $parameters->{'itemtype'}     // '';
     my $ignoreissued = $parameters->{'ignoreissued'} // '';
@@ -831,14 +768,18 @@ sub GetItemsForInventory {
     my $offset       = $parameters->{'offset'}       // '';
     my $size         = $parameters->{'size'}         // '';
     my $statushash   = $parameters->{'statushash'}   // '';
     my $offset       = $parameters->{'offset'}       // '';
     my $size         = $parameters->{'size'}         // '';
     my $statushash   = $parameters->{'statushash'}   // '';
+    my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // '';
 
     my $dbh = C4::Context->dbh;
     my ( @bind_params, @where_strings );
 
 
     my $dbh = C4::Context->dbh;
     my ( @bind_params, @where_strings );
 
+    my $min_cnsort = GetClassSort($class_source,undef,$minlocation);
+    my $max_cnsort = GetClassSort($class_source,undef,$maxlocation);
+
     my $select_columns = q{
     my $select_columns = q{
-        SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
+        SELECT DISTINCT(items.itemnumber), barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
     };
     };
-    my $select_count = q{SELECT COUNT(*)};
+    my $select_count = q{SELECT COUNT(DISTINCT(items.itemnumber))};
     my $query = q{
         FROM items
         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
     my $query = q{
         FROM items
         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
@@ -854,13 +795,13 @@ sub GetItemsForInventory {
     }
 
     if ($minlocation) {
     }
 
     if ($minlocation) {
-        push @where_strings, 'itemcallnumber >= ?';
-        push @bind_params, $minlocation;
+        push @where_strings, 'items.cn_sort >= ?';
+        push @bind_params, $min_cnsort;
     }
 
     if ($maxlocation) {
     }
 
     if ($maxlocation) {
-        push @where_strings, 'itemcallnumber <= ?';
-        push @bind_params, $maxlocation;
+        push @where_strings, 'items.cn_sort <= ?';
+        push @bind_params, $max_cnsort;
     }
 
     if ($datelastseen) {
     }
 
     if ($datelastseen) {
@@ -893,6 +834,11 @@ sub GetItemsForInventory {
         push @where_strings, 'issues.date_due IS NULL';
     }
 
         push @where_strings, 'issues.date_due IS NULL';
     }
 
+    if ( $ignore_waiting_holds ) {
+        $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber ";
+        push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} );
+    }
+
     if ( @where_strings ) {
         $query .= 'WHERE ';
         $query .= join ' AND ', @where_strings;
     if ( @where_strings ) {
         $query .= 'WHERE ';
         $query .= join ' AND ', @where_strings;
@@ -937,58 +883,6 @@ sub GetItemsForInventory {
     return (\@results, $iTotalRecords);
 }
 
     return (\@results, $iTotalRecords);
 }
 
-=head2 GetItemsByBiblioitemnumber
-
-  GetItemsByBiblioitemnumber($biblioitemnumber);
-
-Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
-Called by C<C4::XISBN>
-
-=cut
-
-sub GetItemsByBiblioitemnumber {
-    my ( $bibitem ) = @_;
-    my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
-    # Get all items attached to a biblioitem
-    my $i = 0;
-    my @results; 
-    $sth->execute($bibitem) || die $sth->errstr;
-    while ( my $data = $sth->fetchrow_hashref ) {  
-        # Foreach item, get circulation information
-        my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
-                                   WHERE itemnumber = ?
-                                   AND issues.borrowernumber = borrowers.borrowernumber"
-        );
-        $sth2->execute( $data->{'itemnumber'} );
-        if ( my $data2 = $sth2->fetchrow_hashref ) {
-            # if item is out, set the due date and who it is out too
-            $data->{'date_due'}   = $data2->{'date_due'};
-            $data->{'cardnumber'} = $data2->{'cardnumber'};
-            $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
-        }
-        else {
-            # set date_due to blank, so in the template we check itemlost, and withdrawn
-            $data->{'date_due'} = '';                                                                                                         
-        }    # else         
-        # Find the last 3 people who borrowed this item.                  
-        my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
-                      AND old_issues.borrowernumber = borrowers.borrowernumber
-                      ORDER BY returndate desc,timestamp desc LIMIT 3";
-        $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
-        $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
-        my $i2 = 0;
-        while ( my $data2 = $sth2->fetchrow_hashref ) {
-            $data->{"timestamp$i2"} = $data2->{'timestamp'};
-            $data->{"card$i2"}      = $data2->{'cardnumber'};
-            $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
-            $i2++;
-        }
-        push(@results,$data);
-    } 
-    return (\@results); 
-}
-
 =head2 GetItemsInfo
 
   @results = GetItemsInfo($biblionumber);
 =head2 GetItemsInfo
 
   @results = GetItemsInfo($biblionumber);
@@ -1111,8 +1005,8 @@ sub GetItemsInfo {
 
         # get restricted status and description if applicable
         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
 
         # get restricted status and description if applicable
         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
-        $data->{restricted}     = $descriptions->{lib} // '';
-        $data->{restrictedopac} = $descriptions->{opac_description} // '';
+        $data->{restrictedvalue}     = $descriptions->{lib} // '';
+        $data->{restrictedvalueopac} = $descriptions->{opac_description} // '';
 
         # my stack procedures
         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
 
         # my stack procedures
         $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
@@ -1246,77 +1140,6 @@ sub GetHostItemsInfo {
     return @returnitemsInfo;
 }
 
     return @returnitemsInfo;
 }
 
-=head2 GetLastAcquisitions
-
-  my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
-                                    'itemtypes' => ('BK','BD')}, 10);
-
-=cut
-
-sub  GetLastAcquisitions {
-       my ($data,$max) = @_;
-
-       my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
-       
-       my $number_of_branches = @{$data->{branches}};
-       my $number_of_itemtypes   = @{$data->{itemtypes}};
-       
-       
-       my @where = ('WHERE 1 '); 
-       $number_of_branches and push @where
-          , 'AND holdingbranch IN (' 
-          , join(',', ('?') x $number_of_branches )
-          , ')'
-        ;
-       
-       $number_of_itemtypes and push @where
-          , "AND $itemtype IN (" 
-          , join(',', ('?') x $number_of_itemtypes )
-          , ')'
-        ;
-
-       my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
-                                FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber) 
-                                   RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
-                                   @where
-                                   GROUP BY biblio.biblionumber 
-                                   ORDER BY dateaccessioned DESC LIMIT $max";
-
-       my $dbh = C4::Context->dbh;
-       my $sth = $dbh->prepare($query);
-    
-    $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
-       
-       my @results;
-       while( my $row = $sth->fetchrow_hashref){
-               push @results, {date => $row->{dateaccessioned} 
-                                               , biblionumber => $row->{biblionumber}
-                                               , title => $row->{title}};
-       }
-       
-       return @results;
-}
-
-=head2 GetItemnumbersForBiblio
-
-  my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
-
-Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
-
-=cut
-
-sub GetItemnumbersForBiblio {
-    my $biblionumber = shift;
-    my @items;
-    my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
-    $sth->execute($biblionumber);
-    while (my $result = $sth->fetchrow_hashref) {
-        push @items, $result->{'itemnumber'};
-    }
-    return \@items;
-}
-
 =head2 get_hostitemnumbers_of
 
   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
 =head2 get_hostitemnumbers_of
 
   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
@@ -1331,8 +1154,12 @@ references on array of itemnumbers.
 
 sub get_hostitemnumbers_of {
     my ($biblionumber) = @_;
 
 sub get_hostitemnumbers_of {
     my ($biblionumber) = @_;
-    my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
 
 
+    if( !C4::Context->preference('EasyAnalyticalRecords') ) {
+        return ();
+    }
+
+    my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
     return unless $marcrecord;
 
     my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
     return unless $marcrecord;
 
     my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
@@ -1365,36 +1192,27 @@ sub get_hostitemnumbers_of {
     return @returnhostitemnumbers;
 }
 
     return @returnhostitemnumbers;
 }
 
-
-=head2 GetBarcodeFromItemnumber
-
-  $result = GetBarcodeFromItemnumber($itemnumber);
-
-=cut
-
-sub GetBarcodeFromItemnumber {
-    my ($itemnumber) = @_;
-    my $dbh = C4::Context->dbh;
-
-    my $rq =
-      $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
-    $rq->execute($itemnumber);
-    my ($result) = $rq->fetchrow;
-    return ($result);
-}
-
 =head2 GetHiddenItemnumbers
 
 =head2 GetHiddenItemnumbers
 
-    my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
+    my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
 
 Given a list of items it checks which should be hidden from the OPAC given
 the current configuration. Returns a list of itemnumbers corresponding to
 
 Given a list of items it checks which should be hidden from the OPAC given
 the current configuration. Returns a list of itemnumbers corresponding to
-those that should be hidden.
+those that should be hidden. Optionally takes a borcat parameter for certain borrower types
+to be excluded
 
 =cut
 
 sub GetHiddenItemnumbers {
 
 =cut
 
 sub GetHiddenItemnumbers {
-    my (@items) = @_;
+    my $params = shift;
+    my $items = $params->{items};
+    if (my $exceptions = C4::Context->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
+        foreach my $except (split(/\|/, $exceptions)){
+            if ($params->{'borcat'} eq $except){
+                return; # we don't hide anything for this borrower category
+            }
+        }
+    }
     my @resultitems;
 
     my $yaml = C4::Context->preference('OpacHiddenItems');
     my @resultitems;
 
     my $yaml = C4::Context->preference('OpacHiddenItems');
@@ -1411,7 +1229,7 @@ sub GetHiddenItemnumbers {
     my $dbh = C4::Context->dbh;
 
     # For each item
     my $dbh = C4::Context->dbh;
 
     # For each item
-    foreach my $item (@items) {
+    foreach my $item (@$items) {
 
         # We check each rule
         foreach my $field (keys %$hidingrules) {
 
         # We check each rule
         foreach my $field (keys %$hidingrules) {
@@ -1475,13 +1293,12 @@ sub GetMarcItem {
     # while the other treats the MARC representation as authoritative
     # under certain circumstances.
 
     # while the other treats the MARC representation as authoritative
     # under certain circumstances.
 
-    my $itemrecord = GetItem($itemnumber);
+    my $item = Koha::Items->find($itemnumber) or return;
 
     # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
     # Also, don't emit a subfield if the underlying field is blank.
 
 
     # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
     # Also, don't emit a subfield if the underlying field is blank.
 
-    
-    return Item2Marc($itemrecord,$biblionumber);
+    return Item2Marc($item->unblessed, $biblionumber);
 
 }
 sub Item2Marc {
 
 }
 sub Item2Marc {
@@ -1492,9 +1309,7 @@ sub Item2Marc {
         } keys %{ $itemrecord } 
     };
     my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
         } keys %{ $itemrecord } 
     };
     my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
-    my $itemmarc = C4::Biblio::TransformKohaToMarc(
-        $mungeditem, { no_split => 1},
-    );
+    my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem ); # Bug 21774: no_split parameter removed to allow cloned subfields
     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
         "items.itemnumber", $framework,
     );
     my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
         "items.itemnumber", $framework,
     );
@@ -1922,31 +1737,21 @@ sub ItemSafeToDelete {
 
     my $countanalytics = GetAnalyticsCount($itemnumber);
 
 
     my $countanalytics = GetAnalyticsCount($itemnumber);
 
-    # check that there is no issue on this item before deletion.
-    my $sth = $dbh->prepare(
-        q{
-        SELECT COUNT(*) FROM issues
-        WHERE itemnumber = ?
-    }
-    );
-    $sth->execute($itemnumber);
-    my ($onloan) = $sth->fetchrow;
-
-    my $item = GetItem($itemnumber);
+    my $item = Koha::Items->find($itemnumber) or return;
 
 
-    if ($onloan) {
+    if ($item->checkout) {
         $status = "book_on_loan";
     }
     elsif ( defined C4::Context->userenv
         and !C4::Context->IsSuperLibrarian()
         and C4::Context->preference("IndependentBranches")
         $status = "book_on_loan";
     }
     elsif ( defined C4::Context->userenv
         and !C4::Context->IsSuperLibrarian()
         and C4::Context->preference("IndependentBranches")
-        and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
+        and ( C4::Context->userenv->{branch} ne $item->homebranch ) )
     {
         $status = "not_same_branch";
     }
     else {
         # check it doesn't have a waiting reserve
     {
         $status = "not_same_branch";
     }
     else {
         # check it doesn't have a waiting reserve
-        $sth = $dbh->prepare(
+        my $sth = $dbh->prepare(
             q{
             SELECT COUNT(*) FROM reserves
             WHERE (found = 'W' OR found = 'T')
             q{
             SELECT COUNT(*) FROM reserves
             WHERE (found = 'W' OR found = 'T')
@@ -2178,7 +1983,7 @@ sub _get_unlinked_item_subfields {
     my $original_item_marc = shift;
     my $frameworkcode = shift;
 
     my $original_item_marc = shift;
     my $frameworkcode = shift;
 
-    my $marcstructure = GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
+    my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
 
     # assume that this record has only one field, and that that
     # field contains only the item information
 
     # assume that this record has only one field, and that that
     # field contains only the item information
@@ -2458,7 +2263,7 @@ sub SearchItems {
         $query .= qq{ AND $where_str };
     }
 
         $query .= qq{ AND $where_str };
     }
 
-    $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.marcflavour = ? };
+    $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.schema = ? };
     push @where_args, C4::Context->preference('marcflavour');
 
     my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
     push @where_args, C4::Context->preference('marcflavour');
 
     my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
@@ -2550,7 +2355,7 @@ sub PrepareItemrecordDisplay {
     # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
     # a shared data structure. No plugin (including custom ones) should change
     # its contents. See also GetMarcStructure.
     # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
     # a shared data structure. No plugin (including custom ones) should change
     # its contents. See also GetMarcStructure.
-    my $tagslib = &GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
+    my $tagslib = GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
 
     # return nothing if we don't have found an existing framework.
     return q{} unless $tagslib;
 
     # return nothing if we don't have found an existing framework.
     return q{} unless $tagslib;
@@ -2831,7 +2636,6 @@ sub ToggleNewStatus {
         while ( my $values = $sth->fetchrow_hashref ) {
             my $biblionumber = $values->{biblionumber};
             my $itemnumber = $values->{itemnumber};
         while ( my $values = $sth->fetchrow_hashref ) {
             my $biblionumber = $values->{biblionumber};
             my $itemnumber = $values->{itemnumber};
-            my $item = C4::Items::GetItem( $itemnumber );
             for my $substitution ( @$substitutions ) {
                 next unless $substitution->{field};
                 C4::Items::ModItem( {$substitution->{field} => $substitution->{value}}, $biblionumber, $itemnumber )
             for my $substitution ( @$substitutions ) {
                 next unless $substitution->{field};
                 C4::Items::ModItem( {$substitution->{field} => $substitution->{value}}, $biblionumber, $itemnumber )