Bug 15758: Koha::Libraries - Ultimate duel for C4::Branch
[koha.git] / C4 / Items.pm
index 89b092b..0bca944 100644 (file)
@@ -5,18 +5,18 @@ package C4::Items;
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use strict;
 #use warnings; FIXME - Bug 2505
@@ -25,18 +25,27 @@ use Carp;
 use C4::Context;
 use C4::Koha;
 use C4::Biblio;
-use C4::Dates qw/format_date format_date_in_iso/;
+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::DateUtils qw/dt_from_string/;
+use Koha::Database;
 
-use vars qw($VERSION @ISA @EXPORT);
+use Koha::Biblioitems;
+use Koha::Items;
+use Koha::SearchEngine;
+use Koha::SearchEngine::Search;
+use Koha::Libraries;
+
+use vars qw(@ISA @EXPORT);
 
 BEGIN {
-    $VERSION = 3.07.00.049;
 
        require Exporter;
     @ISA = qw( Exporter );
@@ -72,6 +81,7 @@ BEGIN {
         GetItemnumberFromBarcode
         GetBarcodeFromItemnumber
         GetHiddenItemnumbers
+        ItemSafeToDelete
         DelItemCheck
     MoveItemFromBiblio
     GetLatestAcquisitions
@@ -82,6 +92,7 @@ BEGIN {
        GetAnalyticsCount
         GetItemHolds
 
+        SearchItemsByField
         SearchItems
 
         PrepareItemrecordDisplay
@@ -144,6 +155,7 @@ sub GetItem {
     my ($itemnumber,$barcode, $serial) = @_;
     my $dbh = C4::Context->dbh;
        my $data;
+
     if ($itemnumber) {
         my $sth = $dbh->prepare("
             SELECT * FROM items 
@@ -158,12 +170,17 @@ sub GetItem {
         $sth->execute($barcode);               
         $data = $sth->fetchrow_hashref;
     }
+
+    return unless ( $data );
+
     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();
     }
        #if we don't have an items.itype, use biblioitems.itemtype.
+    # FIXME this should respect the itypes systempreference
+    # if (C4::Context->preference('item-level_itypes')) {
        if( ! $data->{'itype'} ) {
                my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
                $sth->execute($data->{'biblionumber'});
@@ -239,7 +256,7 @@ sub AddItemFromMarc {
        
        my $localitemmarc=MARC::Record->new;
        $localitemmarc->append_fields($source_item_marc->field($itemtag));
-    my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
+    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);
 }
@@ -371,7 +388,7 @@ sub AddItemBatchFromMarc {
         $temp_item_marc->append_fields($item_field);
     
         # add biblionumber and biblioitemnumber
-        my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
+        my $item = TransformMarcToKoha( $temp_item_marc, $frameworkcode, 'items' );
         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
         $item->{'biblionumber'} = $biblionumber;
@@ -420,7 +437,7 @@ other purposes, C<ModItem> should be used.
 
 This function uses the hash %default_values_for_mod_from_marc,
 which contains default values for item fields to
-apply when modifying an item.  This is needed beccause
+apply when modifying an item.  This is needed because
 if an item field's value is cleared, TransformMarcToKoha
 does not include the column in the
 hash that's passed to ModItem, which without
@@ -435,36 +452,58 @@ Returns item record
 
 =cut
 
-my %default_values_for_mod_from_marc = (
-    barcode              => undef, 
-    booksellerid         => undef, 
-    ccode                => undef, 
-    'items.cn_source'    => undef, 
-    coded_location_qualifier => undef,
-    copynumber           => undef, 
-    damaged              => 0,
-#    dateaccessioned      => undef,
-    enumchron            => undef, 
-    holdingbranch        => undef, 
-    homebranch           => undef, 
-    itemcallnumber       => undef, 
-    itemlost             => 0,
-    itemnotes            => undef, 
-    itype                => undef, 
-    location             => undef, 
-    permanent_location   => undef,
-    materials            => undef, 
-    notforloan           => 0,
-    paidfor              => undef, 
-    price                => undef, 
-    replacementprice     => undef, 
-    replacementpricedate => undef, 
-    restricted           => undef, 
-    stack                => undef, 
-    stocknumber          => undef, 
-    uri                  => undef, 
-    wthdrawn             => 0,
-);
+sub _build_default_values_for_mod_marc {
+    my ($frameworkcode) = @_;
+
+    my $cache     = Koha::Caches->get_instance();
+    my $cache_key = "default_value_for_mod_marc-$frameworkcode";
+    my $cached    = $cache->get_from_cache($cache_key);
+    return $cached if $cached;
+
+    my $default_values = {
+        barcode                  => undef,
+        booksellerid             => undef,
+        ccode                    => undef,
+        'items.cn_source'        => undef,
+        coded_location_qualifier => undef,
+        copynumber               => undef,
+        damaged                  => 0,
+        enumchron                => undef,
+        holdingbranch            => undef,
+        homebranch               => undef,
+        itemcallnumber           => undef,
+        itemlost                 => 0,
+        itemnotes                => undef,
+        itemnotes_nonpublic      => undef,
+        itype                    => undef,
+        location                 => undef,
+        permanent_location       => undef,
+        materials                => undef,
+        new_status               => undef,
+        notforloan               => 0,
+        # paidfor => undef, # commented, see bug 12817
+        price                    => undef,
+        replacementprice         => undef,
+        replacementpricedate     => undef,
+        restricted               => undef,
+        stack                    => undef,
+        stocknumber              => undef,
+        uri                      => undef,
+        withdrawn                => 0,
+    };
+    my %default_values_for_mod_from_marc;
+    while ( my ( $field, $default_value ) = each %$default_values ) {
+        my $kohafield = $field;
+        $kohafield =~ s|^([^\.]+)$|items.$1|;
+        $default_values_for_mod_from_marc{$field} =
+          $default_value
+          if C4::Koha::IsKohaFieldLinked(
+            { kohafield => $kohafield, frameworkcode => $frameworkcode } );
+    }
+
+    $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
+    return \%default_values_for_mod_from_marc;
+}
 
 sub ModItemFromMarc {
     my $item_marc = shift;
@@ -477,9 +516,11 @@ sub ModItemFromMarc {
 
     my $localitemmarc = MARC::Record->new;
     $localitemmarc->append_fields( $item_marc->field($itemtag) );
-    my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
-    foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
-        $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
+    my $item = &TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
+    my $default_values = _build_default_values_for_mod_marc($frameworkcode);
+    foreach my $item_field ( keys %$default_values ) {
+        $item->{$item_field} = $default_values->{$item_field}
+          unless exists $item->{$item_field};
     }
     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
 
@@ -533,7 +574,30 @@ sub ModItem {
 
     $item->{'itemnumber'} = $itemnumber or return;
 
-    $item->{onloan} = undef if $item->{itemlost};
+    my @fields = qw( itemlost withdrawn );
+
+    # Only call GetItem if we need to set an "on" date field
+    if ( $item->{itemlost} || $item->{withdrawn} ) {
+        my $pre_mod_item = GetItem( $item->{'itemnumber'} );
+        for my $field (@fields) {
+            if (    defined( $item->{$field} )
+                and not $pre_mod_item->{$field}
+                and $item->{$field} )
+            {
+                $item->{ $field . '_on' } =
+                  DateTime::Format::MySQL->format_datetime( dt_from_string() );
+            }
+        }
+    }
+
+    # If the field is defined but empty, we are removing and,
+    # and thus need to clear out the 'on' field as well
+    for my $field (@fields) {
+        if ( defined( $item->{$field} ) && !$item->{$field} ) {
+            $item->{ $field . '_on' } = undef;
+        }
+    }
+
 
     _set_derived_columns_for_mod($item);
     _do_column_fixes_for_mod($item);
@@ -551,7 +615,7 @@ sub ModItem {
     # item status is possible
     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
 
-    logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
+    logaction("CATALOGUING", "MODIFY", $itemnumber, "item ".Dumper($item)) if C4::Context->preference("CataloguingLog");
 }
 
 =head2 ModItemTransfer
@@ -594,36 +658,41 @@ C<$itemnum> is the item number
 sub ModDateLastSeen {
     my ($itemnumber) = @_;
     
-    my $today = C4::Dates->new();    
-    ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
+    my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
+    ModItem({ itemlost => 0, datelastseen => $today }, undef, $itemnumber);
 }
 
 =head2 DelItem
 
-  DelItem($dbh, $biblionumber, $itemnumber);
+  DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
 
 Exported function (core API) for deleting an item record in Koha.
 
 =cut
 
 sub DelItem {
-    my ( $dbh, $biblionumber, $itemnumber ) = @_;
-    
+    my ( $params ) = @_;
+
+    my $itemnumber   = $params->{itemnumber};
+    my $biblionumber = $params->{biblionumber};
+
+    unless ($biblionumber) {
+        $biblionumber = C4::Biblio::GetBiblionumberFromItemnumber($itemnumber);
+    }
+
+    # If there is no biblionumber for the given itemnumber, there is nothing to delete
+    return 0 unless $biblionumber;
+
     # FIXME check the item has no current issues
-    
-    _koha_delete_item( $dbh, $itemnumber );
+    my $deleted = _koha_delete_item( $itemnumber );
 
     # get the MARC record
     my $record = GetMarcBiblio($biblionumber);
     ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
 
-    # backup the record
-    my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
-    $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
-    # This last update statement makes that the timestamp column in deleteditems is updated too. If you remove these lines, please add a line to update the timestamp separately. See Bugzilla report 7146 and Biblio.pm (DelBiblio).
-
     #search item field code
     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
+    return $deleted;
 }
 
 =head2 CheckItemPreSave
@@ -670,7 +739,6 @@ item that has a given branch code.
 
 sub CheckItemPreSave {
     my $item_ref = shift;
-    require C4::Branch;
 
     my %errors = ();
 
@@ -687,20 +755,16 @@ sub CheckItemPreSave {
 
     # check for valid home branch
     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
-        my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
-        unless (defined $branch_name) {
-            # relies on fact that branches.branchname is a non-NULL column,
-            # so GetBranchName returns undef only if branch does not exist
+        my $home_library = Koha::Libraries->find( $item_ref->{homebranch} );
+        unless (defined $home_library) {
             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
         }
     }
 
     # check for valid holding branch
     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
-        my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
-        unless (defined $branch_name) {
-            # relies on fact that branches.branchname is a non-NULL column,
-            # so GetBranchName returns undef only if branch does not exist
+        my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} );
+        unless (defined $holding_library) {
             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
         }
     }
@@ -732,7 +796,7 @@ C<items.notforloan> field.
 NOTE: does B<not> return an individual item's
 status.
 
-Can be MARC dependant.
+Can be MARC dependent.
 fwkcode is optional.
 But basically could be can be loan or not
 Create a status selector with the following code
@@ -751,12 +815,16 @@ Create a status selector with the following code
 
 =head3 in TEMPLATE
 
- <select name="statusloop">
-     <option value="">Default</option>
- <!-- TMPL_LOOP name="statusloop" -->
-     <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
- <!-- /TMPL_LOOP -->
- </select>
+<select name="statusloop" id="statusloop">
+    <option value="">Default</option>
+    [% FOREACH statusloo IN statusloop %]
+        [% IF ( statusloo.selected ) %]
+            <option value="[% statusloo.value %]" selected="selected">[% statusloo.statusname %]</option>
+        [% ELSE %]
+            <option value="[% statusloo.value %]">[% statusloo.statusname %]</option>
+        [% END %]
+    [% END %]
+</select>
 
 =cut
 
@@ -898,7 +966,7 @@ sub GetItemLocation {
 
 =head2 GetLostItems
 
-  $items = GetLostItems( $where, $orderby );
+  $items = GetLostItems( $where );
 
 This function gets a list of lost items.
 
@@ -912,9 +980,6 @@ and the value to match as value. For example:
 { barcode    => 'abc123',
   homebranch => 'CPL',    }
 
-C<$orderby> is a field of the items table by which the resultset
-should be orderd.
-
 =item return:
 
 C<$items> is a reference to an array full of hashrefs with columns
@@ -923,7 +988,7 @@ from the "items" table as keys.
 =item usage in the perl script:
 
   my $where = { barcode => '0001548' };
-  my $items = GetLostItems( $where, "homebranch" );
+  my $items = GetLostItems( $where );
   $template->param( itemsloop => $items );
 
 =back
@@ -933,12 +998,11 @@ from the "items" table as keys.
 sub GetLostItems {
     # Getting input args.
     my $where   = shift;
-    my $orderby = shift;
     my $dbh     = C4::Context->dbh;
 
     my $query   = "
         SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
-               itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber
+               itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber, itemcallnumber
         FROM   items
             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
@@ -953,11 +1017,6 @@ sub GetLostItems {
         $query .= " AND $key LIKE ?";
         push @query_parameters, "%$where->{$key}%";
     }
-    my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
-    
-    if ( defined $orderby && grep($orderby, @ordervalues)) {
-        $query .= ' ORDER BY '.$orderby;
-    }
 
     my $sth = $dbh->prepare($query);
     $sth->execute( @query_parameters );
@@ -970,9 +1029,20 @@ sub GetLostItems {
 
 =head2 GetItemsForInventory
 
-  $itemlist = GetItemsForInventory($minlocation, $maxlocation, 
-                 $location, $itemtype $datelastseen, $branch, 
-                 $offset, $size, $statushash);
+($itemlist, $iTotalRecords) = GetItemsForInventory( {
+  minlocation  => $minlocation,
+  maxlocation  => $maxlocation,
+  location     => $location,
+  itemtype     => $itemtype,
+  ignoreissued => $ignoreissued,
+  datelastseen => $datelastseen,
+  branchcode   => $branchcode,
+  branch       => $branch,
+  offset       => $offset,
+  size         => $size,
+  statushash   => $statushash,
+  interface    => $interface,
+} );
 
 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
 
@@ -985,19 +1055,37 @@ the datelastseen can be used to specify that you want to see items not seen sinc
 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
 $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.
 
+$iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
+
 =cut
 
 sub GetItemsForInventory {
-    my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
+    my ( $parameters ) = @_;
+    my $minlocation  = $parameters->{'minlocation'}  // '';
+    my $maxlocation  = $parameters->{'maxlocation'}  // '';
+    my $location     = $parameters->{'location'}     // '';
+    my $itemtype     = $parameters->{'itemtype'}     // '';
+    my $ignoreissued = $parameters->{'ignoreissued'} // '';
+    my $datelastseen = $parameters->{'datelastseen'} // '';
+    my $branchcode   = $parameters->{'branchcode'}   // '';
+    my $branch       = $parameters->{'branch'}       // '';
+    my $offset       = $parameters->{'offset'}       // '';
+    my $size         = $parameters->{'size'}         // '';
+    my $statushash   = $parameters->{'statushash'}   // '';
+    my $interface    = $parameters->{'interface'}    // '';
+
     my $dbh = C4::Context->dbh;
     my ( @bind_params, @where_strings );
 
-    my $query = <<'END_SQL';
-SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
-FROM items
-  LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
-  LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
-END_SQL
+    my $select_columns = q{
+        SELECT 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 $query = q{
+        FROM items
+        LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
+        LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
+    };
     if ($statushash){
         for my $authvfield (keys %$statushash){
             if ( scalar @{$statushash->{$authvfield}} > 0 ){
@@ -1018,7 +1106,7 @@ END_SQL
     }
 
     if ($datelastseen) {
-        $datelastseen = format_date_in_iso($datelastseen);  
+        $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
         push @bind_params, $datelastseen;
     }
@@ -1036,7 +1124,7 @@ END_SQL
         }
         push @bind_params, $branchcode;
     }
-    
+
     if ( $itemtype ) {
         push @where_strings, 'biblioitems.itemtype = ?';
         push @bind_params, $itemtype;
@@ -1052,20 +1140,33 @@ END_SQL
         $query .= join ' AND ', @where_strings;
     }
     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
+    my $count_query = $select_count . $query;
+    $query .= " LIMIT $offset, $size" if ($offset and $size);
+    $query = $select_columns . $query;
     my $sth = $dbh->prepare($query);
     $sth->execute( @bind_params );
 
-    my @results;
-    $size--;
-    while ( my $row = $sth->fetchrow_hashref ) {
-        $offset-- if ($offset);
-        $row->{datelastseen}=format_date($row->{datelastseen});
-        if ( ( !$offset ) && $size ) {
-            push @results, $row;
-            $size--;
+    my @results = ();
+    my $tmpresults = $sth->fetchall_arrayref({});
+    $sth = $dbh->prepare( $count_query );
+    $sth->execute( @bind_params );
+    my ($iTotalRecords) = $sth->fetchrow_array();
+
+    my $avmapping = C4::Koha::GetKohaAuthorisedValuesMapping( {
+                      interface => $interface
+                    } );
+    foreach my $row (@$tmpresults) {
+
+        # Auth values
+        foreach (keys %$row) {
+            if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
+                $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
+            }
         }
+        push @results, $row;
     }
-    return \@results;
+
+    return (\@results, $iTotalRecords);
 }
 
 =head2 GetItemsCount
@@ -1097,11 +1198,13 @@ sub GetItemsCount {
 sub GetItemInfosOf {
     my @itemnumbers = @_;
 
-    my $query = '
+    my $itemnumber_values = @itemnumbers ? join( ',', @itemnumbers ) : "''";
+
+    my $query = "
         SELECT *
         FROM items
-        WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
-    ';
+        WHERE itemnumber IN ($itemnumber_values)
+    ";
     return get_infos_of( $query, 'itemnumber' );
 }
 
@@ -1136,7 +1239,7 @@ sub GetItemsByBiblioitemnumber {
             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
         }
         else {
-            # set date_due to blank, so in the template we check itemlost, and wthdrawn 
+            # 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.                  
@@ -1203,6 +1306,8 @@ sub GetItemsInfo {
     my ( $biblionumber ) = @_;
     my $dbh   = C4::Context->dbh;
     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
+    require C4::Languages;
+    my $language = C4::Languages::getlanguage();
     my $query = "
     SELECT items.*,
            biblio.*,
@@ -1218,63 +1323,57 @@ sub GetItemsInfo {
            biblioitems.lccn,
            biblioitems.url,
            items.notforloan as itemnotforloan,
+           issues.borrowernumber,
+           issues.date_due as datedue,
+           issues.onsite_checkout,
+           borrowers.cardnumber,
+           borrowers.surname,
+           borrowers.firstname,
+           borrowers.branchcode as bcode,
+           serial.serialseq,
+           serial.publisheddate,
            itemtypes.description,
+           COALESCE( localization.translation, itemtypes.description ) AS translated_description,
            itemtypes.notforloan as notforloan_per_itemtype,
            holding.branchurl,
+           holding.branchcode,
            holding.branchname,
-           holding.opac_info as branch_opac_info
+           holding.opac_info as holding_branch_opac_info,
+           home.opac_info as home_branch_opac_info
+    ";
+    $query .= "
      FROM items
      LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
      LEFT JOIN branches AS home ON items.homebranch=home.branchcode
      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
+     LEFT JOIN issues USING (itemnumber)
+     LEFT JOIN borrowers USING (borrowernumber)
+     LEFT JOIN serialitems USING (itemnumber)
+     LEFT JOIN serial USING (serialid)
      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
+    $query .= q|
+    LEFT JOIN localization ON itemtypes.itemtype = localization.code
+        AND localization.entity = 'itemtypes'
+        AND localization.lang = ?
+    |;
+
     $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
     my $sth = $dbh->prepare($query);
-    $sth->execute($biblionumber);
+    $sth->execute($language, $biblionumber);
     my $i = 0;
     my @results;
     my $serial;
 
-    my $isth    = $dbh->prepare(
-        "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
-        FROM   issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
-        WHERE  itemnumber = ?"
-       );
-       my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
-       while ( my $data = $sth->fetchrow_hashref ) {
-        my $datedue = '';
-        $isth->execute( $data->{'itemnumber'} );
-        if ( my $idata = $isth->fetchrow_hashref ) {
-            $data->{borrowernumber} = $idata->{borrowernumber};
-            $data->{cardnumber}     = $idata->{cardnumber};
-            $data->{surname}     = $idata->{surname};
-            $data->{firstname}     = $idata->{firstname};
-            $data->{lastreneweddate} = $idata->{lastreneweddate};
-            $datedue                = $idata->{'date_due'};
-        if (C4::Context->preference("IndependantBranches")){
-        my $userenv = C4::Context->userenv;
-        if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) { 
-            $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
-        }
-        }
-        }
-               if ( $data->{'serial'}) {       
-                       $ssth->execute($data->{'itemnumber'}) ;
-                       ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
-                       $serial = 1;
+    my $userenv = C4::Context->userenv;
+    my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
+    while ( my $data = $sth->fetchrow_hashref ) {
+        if ( $data->{borrowernumber} && $want_not_same_branch) {
+            $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
         }
-        #get branch information.....
-        my $bsth = $dbh->prepare(
-            "SELECT * FROM branches WHERE branchcode = ?
-        "
-        );
-        $bsth->execute( $data->{'holdingbranch'} );
-        if ( my $bdata = $bsth->fetchrow_hashref ) {
-            $data->{'branchname'} = $bdata->{'branchname'};
-        }
-        $data->{'datedue'}        = $datedue;
+
+        $serial ||= $data->{'serial'};
 
         # get notforloan complete status if applicable
         if ( my $code = C4::Koha::GetAuthValCode( 'items.notforloan', $data->{frameworkcode} ) ) {
@@ -1284,14 +1383,15 @@ sub GetItemsInfo {
 
         # get restricted status and description if applicable
         if ( my $code = C4::Koha::GetAuthValCode( 'items.restricted', $data->{frameworkcode} ) ) {
-            $data->{restricted}     = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
             $data->{restrictedopac} = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted}, 1 );
+            $data->{restricted}     = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{restricted} );
         }
 
         # my stack procedures
         if ( my $code = C4::Koha::GetAuthValCode( 'items.stack', $data->{frameworkcode} ) ) {
             $data->{stack}          = C4::Koha::GetKohaAuthorisedValueLib( $code, $data->{stack} );
         }
+
         # Find the last 3 people who borrowed this item.
         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
                                     WHERE itemnumber = ?
@@ -1310,11 +1410,10 @@ sub GetItemsInfo {
         $results[$i] = $data;
         $i++;
     }
-       if($serial) {
-               return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
-       } else {
-       return (@results);
-       }
+
+    return $serial
+        ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
+        : @results;
 }
 
 =head2 GetItemsLocationInfo
@@ -1542,36 +1641,42 @@ references on array of itemnumbers.
 
 
 sub get_hostitemnumbers_of {
-       my ($biblionumber) = @_;
-       my $marcrecord = GetMarcBiblio($biblionumber);
-        my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
-       
-       my $marcflavor = C4::Context->preference('marcflavour');
-       if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
-        $tag='773';
-        $biblio_s='0';
-        $item_s='9';
-    } elsif ($marcflavor eq 'UNIMARC') {
-        $tag='461';
-        $biblio_s='0';
-        $item_s='9';
+    my ($biblionumber) = @_;
+    my $marcrecord = GetMarcBiblio($biblionumber);
+
+    return unless $marcrecord;
+
+    my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
+
+    my $marcflavor = C4::Context->preference('marcflavour');
+    if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
+        $tag      = '773';
+        $biblio_s = '0';
+        $item_s   = '9';
+    }
+    elsif ( $marcflavor eq 'UNIMARC' ) {
+        $tag      = '461';
+        $biblio_s = '0';
+        $item_s   = '9';
     }
 
     foreach my $hostfield ( $marcrecord->field($tag) ) {
         my $hostbiblionumber = $hostfield->subfield($biblio_s);
         my $linkeditemnumber = $hostfield->subfield($item_s);
         my @itemnumbers;
-        if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
+        if ( my $itemnumbers =
+            get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber} )
         {
             @itemnumbers = @$itemnumbers;
         }
-        foreach my $itemnumber (@itemnumbers){
-            if ($itemnumber eq $linkeditemnumber){
-                push (@returnhostitemnumbers,$itemnumber);
+        foreach my $itemnumber (@itemnumbers) {
+            if ( $itemnumber eq $linkeditemnumber ) {
+                push( @returnhostitemnumbers, $itemnumber );
                 last;
             }
         }
     }
+
     return @returnhostitemnumbers;
 }
 
@@ -1612,11 +1717,11 @@ sub GetBarcodeFromItemnumber {
 
 =head2 GetHiddenItemnumbers
 
-=over 4
+    my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
 
-$result = GetHiddenItemnumbers(@items);
-
-=back
+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.
 
 =cut
 
@@ -1625,6 +1730,7 @@ sub GetHiddenItemnumbers {
     my @resultitems;
 
     my $yaml = C4::Context->preference('OpacHiddenItems');
+    return () if (! $yaml =~ /\S/ );
     $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
     my $hidingrules;
     eval {
@@ -1665,104 +1771,6 @@ sub GetHiddenItemnumbers {
     return @resultitems;
 }
 
-=head3 get_item_authorised_values
-
-find the types and values for all authorised values assigned to this item.
-
-parameters: itemnumber
-
-returns: a hashref malling the authorised value to the value set for this itemnumber
-
-    $authorised_values = {
-             'CCODE'      => undef,
-             'DAMAGED'    => '0',
-             'LOC'        => '3',
-             'LOST'       => '0'
-             'NOT_LOAN'   => '0',
-             'RESTRICTED' => undef,
-             'STACK'      => undef,
-             'WITHDRAWN'  => '0',
-             'branches'   => 'CPL',
-             'cn_source'  => undef,
-             'itemtypes'  => 'SER',
-           };
-
-Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
-
-=cut
-
-sub get_item_authorised_values {
-    my $itemnumber = shift;
-
-    # assume that these entries in the authorised_value table are item level.
-    my $query = q(SELECT distinct authorised_value, kohafield
-                    FROM marc_subfield_structure
-                    WHERE kohafield like 'item%'
-                      AND authorised_value != '' );
-
-    my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
-    my $iteminfo = GetItem( $itemnumber );
-    # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
-    my $return;
-    foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
-        my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
-        $field =~ s/^items\.//;
-        if ( exists $iteminfo->{ $field } ) {
-            $return->{ $this_authorised_value } = $iteminfo->{ $field };
-        }
-    }
-    # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
-    return $return;
-}
-
-=head3 get_authorised_value_images
-
-find a list of icons that are appropriate for display based on the
-authorised values for a biblio.
-
-parameters: listref of authorised values, such as comes from
-get_item_authorised_values or
-from C4::Biblio::get_biblio_authorised_values
-
-returns: listref of hashrefs for each image. Each hashref looks like this:
-
-      { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
-        label    => '',
-        category => '',
-        value    => '', }
-
-Notes: Currently, I put on the full path to the images on the staff
-side. This should either be configurable or not done at all. Since I
-have to deal with 'intranet' or 'opac' in
-get_biblio_authorised_values, perhaps I should be passing it in.
-
-=cut
-
-sub get_authorised_value_images {
-    my $authorised_values = shift;
-
-    my @imagelist;
-
-    my $authorised_value_list = GetAuthorisedValues();
-    # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
-    foreach my $this_authorised_value ( @$authorised_value_list ) {
-        if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
-             && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
-            # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
-            if ( defined $this_authorised_value->{'imageurl'} ) {
-                push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
-                                   label    => $this_authorised_value->{'lib'},
-                                   category => $this_authorised_value->{'category'},
-                                   value    => $this_authorised_value->{'authorised_value'}, };
-            }
-        }
-    }
-
-    # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
-    return \@imagelist;
-
-}
-
 =head1 LIMITED USE FUNCTIONS
 
 The following functions, while part of the public API,
@@ -1939,7 +1947,7 @@ Given an item hashref containing one or more
 columns to modify, fix up certain values.
 Specifically, set to 0 any passed value
 of C<notforloan>, C<damaged>, C<itemlost>, or
-C<wthdrawn> that is either undefined or
+C<withdrawn> that is either undefined or
 contains the empty string.
 
 =cut
@@ -1959,11 +1967,15 @@ sub _do_column_fixes_for_mod {
         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
         $item->{'itemlost'} = 0;
     }
-    if (exists $item->{'wthdrawn'} and
-        (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
-        $item->{'wthdrawn'} = 0;
+    if (exists $item->{'withdrawn'} and
+        (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
+        $item->{'withdrawn'} = 0;
     }
-    if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
+    if (exists $item->{location}
+        and $item->{location} ne 'CART'
+        and $item->{location} ne 'PROC'
+        and not $item->{permanent_location}
+    ) {
         $item->{'permanent_location'} = $item->{'location'};
     }
     if (exists $item->{'timestamp'}) {
@@ -2035,7 +2047,7 @@ C<items.itemlost>
 
 =item *
 
-C<items.wthdrawn>
+C<items.withdrawn>
 
 =back
 
@@ -2043,8 +2055,8 @@ C<items.wthdrawn>
 
 sub _set_defaults_for_add {
     my $item = shift;
-    $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
-    $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
+    $item->{dateaccessioned} ||= output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
+    $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
 }
 
 =head2 _koha_new_item
@@ -2059,6 +2071,7 @@ sub _koha_new_item {
     my ( $item, $barcode ) = @_;
     my $dbh=C4::Context->dbh;  
     my $error;
+    $item->{permanent_location} //= $item->{location};
     my $query =
            "INSERT INTO items SET
             biblionumber        = ?,
@@ -2076,15 +2089,16 @@ sub _koha_new_item {
             notforloan          = ?,
             damaged             = ?,
             itemlost            = ?,
-            wthdrawn            = ?,
+            withdrawn           = ?,
             itemcallnumber      = ?,
             coded_location_qualifier = ?,
             restricted          = ?,
             itemnotes           = ?,
+            itemnotes_nonpublic = ?,
             holdingbranch       = ?,
             paidfor             = ?,
             location            = ?,
-            permanent_location            = ?,
+            permanent_location  = ?,
             onloan              = ?,
             issues              = ?,
             renewals            = ?,
@@ -2094,14 +2108,15 @@ sub _koha_new_item {
             ccode               = ?,
             itype               = ?,
             materials           = ?,
-            uri = ?,
+            uri                 = ?,
             enumchron           = ?,
             more_subfields_xml  = ?,
             copynumber          = ?,
-            stocknumber         = ?
+            stocknumber         = ?,
+            new_status          = ?
           ";
     my $sth = $dbh->prepare($query);
-    my $today = C4::Dates->today('iso');
+    my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
    $sth->execute(
             $item->{'biblionumber'},
             $item->{'biblioitemnumber'},
@@ -2118,11 +2133,12 @@ sub _koha_new_item {
             $item->{'notforloan'},
             $item->{'damaged'},
             $item->{'itemlost'},
-            $item->{'wthdrawn'},
+            $item->{'withdrawn'},
             $item->{'itemcallnumber'},
             $item->{'coded_location_qualifier'},
             $item->{'restricted'},
             $item->{'itemnotes'},
+            $item->{'itemnotes_nonpublic'},
             $item->{'holdingbranch'},
             $item->{'paidfor'},
             $item->{'location'},
@@ -2141,6 +2157,7 @@ sub _koha_new_item {
             $item->{'more_subfields_xml'},
             $item->{'copynumber'},
             $item->{'stocknumber'},
+            $item->{'new_status'},
     );
 
     my $itemnumber;
@@ -2167,11 +2184,18 @@ Returns undef if the move failed or the biblionumber of the destination record o
 sub MoveItemFromBiblio {
     my ($itemnumber, $frombiblio, $tobiblio) = @_;
     my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
-    $sth->execute( $tobiblio );
-    my ( $tobiblioitem ) = $sth->fetchrow();
-    $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
-    my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
+    my ( $tobiblioitem ) = $dbh->selectrow_array(q|
+        SELECT biblioitemnumber
+        FROM biblioitems
+        WHERE biblionumber = ?
+    |, undef, $tobiblio );
+    my $return = $dbh->do(q|
+        UPDATE items
+        SET biblioitemnumber = ?,
+            biblionumber = ?
+        WHERE itemnumber = ?
+            AND biblionumber = ?
+    |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
     if ($return == 1) {
         ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
         ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
@@ -2183,58 +2207,116 @@ sub MoveItemFromBiblio {
                    $order->{'biblionumber'} = $tobiblio;
                C4::Acquisition::ModOrder($order);
            }
+
+        # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
+        for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
+            $dbh->do( qq|
+                UPDATE $table_name
+                SET biblionumber = ?
+                WHERE itemnumber = ?
+            |, undef, $tobiblio, $itemnumber );
+        }
         return $tobiblio;
        }
     return;
 }
 
-=head2 DelItemCheck
+=head2 ItemSafeToDelete
 
-   DelItemCheck($dbh, $biblionumber, $itemnumber);
+   ItemSafeToDelete( $biblionumber, $itemnumber);
 
-Exported function (core API) for deleting an item record in Koha if there no current issue.
+Exported function (core API) for checking whether an item record is safe to delete.
+
+returns 1 if the item is safe to delete,
+
+"book_on_loan" if the item is checked out,
+
+"not_same_branch" if the item is blocked by independent branches,
+
+"book_reserved" if the there are holds aganst the item, or
+
+"linked_analytics" if the item has linked analytic records.
 
 =cut
 
-sub DelItemCheck {
-    my ( $dbh, $biblionumber, $itemnumber ) = @_;
-    my $error;
+sub ItemSafeToDelete {
+    my ( $biblionumber, $itemnumber ) = @_;
+    my $status;
+    my $dbh = C4::Context->dbh;
 
-        my $countanalytics=GetAnalyticsCount($itemnumber);
+    my $error;
 
+    my $countanalytics = GetAnalyticsCount($itemnumber);
 
     # check that there is no issue on this item before deletion.
-    my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
+    my $sth = $dbh->prepare(
+        q{
+        SELECT COUNT(*) FROM issues
+        WHERE itemnumber = ?
+    }
+    );
     $sth->execute($itemnumber);
+    my ($onloan) = $sth->fetchrow;
 
     my $item = GetItem($itemnumber);
-    my $onloan=$sth->fetchrow;
 
-    if ($onloan){
-        $error = "book_on_loan" 
+    if ($onloan) {
+        $status = "book_on_loan";
     }
-    elsif ( !(C4::Context->userenv->{flags} & 1) and
-            C4::Context->preference("IndependantBranches") and
-           (C4::Context->userenv->{branch} ne
-             $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
+    elsif ( defined C4::Context->userenv
+        and !C4::Context->IsSuperLibrarian()
+        and C4::Context->preference("IndependentBranches")
+        and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
     {
-        $error = "not_same_branch";
+        $status = "not_same_branch";
     }
-       else{
-        # check it doesnt have a waiting reserve
-        $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
+    else {
+        # check it doesn't have a waiting reserve
+        $sth = $dbh->prepare(
+            q{
+            SELECT COUNT(*) FROM reserves
+            WHERE (found = 'W' OR found = 'T')
+            AND itemnumber = ?
+        }
+        );
         $sth->execute($itemnumber);
-        my $reserve=$sth->fetchrow;
-        if ($reserve){
-            $error = "book_reserved";
-        } elsif ($countanalytics > 0){
-               $error = "linked_analytics";
-       } else {
-            DelItem($dbh, $biblionumber, $itemnumber);
-            return 1;
+        my ($reserve) = $sth->fetchrow;
+        if ($reserve) {
+            $status = "book_reserved";
+        }
+        elsif ( $countanalytics > 0 ) {
+            $status = "linked_analytics";
         }
+        else {
+            $status = 1;
+        }
+    }
+    return $status;
+}
+
+=head2 DelItemCheck
+
+   DelItemCheck( $biblionumber, $itemnumber);
+
+Exported function (core API) for deleting an item record in Koha if there no current issue.
+
+DelItemCheck wraps ItemSafeToDelete around DelItem.
+
+=cut
+
+sub DelItemCheck {
+    my ( $biblionumber, $itemnumber ) = @_;
+    my $status = ItemSafeToDelete( $biblionumber, $itemnumber );
+
+    if ( $status == 1 ) {
+        DelItem(
+            {
+                biblionumber => $biblionumber,
+                itemnumber   => $itemnumber
+            }
+        );
     }
-    return $error;
+    return $status;
 }
 
 =head2 _koha_modify_item
@@ -2254,16 +2336,17 @@ sub _koha_modify_item {
     my $query = "UPDATE items SET ";
     my @bind;
     for my $key ( keys %$item ) {
+        next if ( $key eq 'itemnumber' );
         $query.="$key=?,";
         push @bind, $item->{$key};
     }
     $query =~ s/,$//;
     $query .= " WHERE itemnumber=?";
     push @bind, $item->{'itemnumber'};
-    my $sth = C4::Context->dbh->prepare($query);
+    my $sth = $dbh->prepare($query);
     $sth->execute(@bind);
-    if ( C4::Context->dbh->errstr ) {
-        $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
+    if ( $sth->err ) {
+        $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
         warn $error;
     }
     return ($item->{'itemnumber'},$error);
@@ -2271,22 +2354,28 @@ sub _koha_modify_item {
 
 =head2 _koha_delete_item
 
-  _koha_delete_item( $dbh, $itemnum );
+  _koha_delete_item( $itemnum );
 
 Internal function to delete an item record from the koha tables
 
 =cut
 
 sub _koha_delete_item {
-    my ( $dbh, $itemnum ) = @_;
+    my ( $itemnum ) = @_;
 
+    my $dbh = C4::Context->dbh;
     # save the deleted item to deleteditems table
     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
     $sth->execute($itemnum);
     my $data = $sth->fetchrow_hashref();
+
+    # There is no item to delete
+    return 0 unless $data;
+
     my $query = "INSERT INTO deleteditems SET ";
     my @bind  = ();
     foreach my $key ( keys %$data ) {
+        next if ( $key eq 'timestamp' ); # timestamp will be set by db
         $query .= "$key = ?,";
         push( @bind, $data->{$key} );
     }
@@ -2296,8 +2385,8 @@ sub _koha_delete_item {
 
     # delete from items table
     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
-    $sth->execute($itemnum);
-    return;
+    my $deleted = $sth->execute($itemnum);
+    return ( $deleted == 1 ) ? 1 : 0;
 }
 
 =head2 _marc_from_item_hash
@@ -2459,21 +2548,18 @@ counts Usage of itemnumber in Analytical bibliorecords.
 
 sub GetAnalyticsCount {
     my ($itemnumber) = @_;
-    require C4::Search;
 
     ### ZOOM search here
     my $query;
     $query= "hi=".$itemnumber;
-            my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
+    my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
+    my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
     return ($result);
 }
 
 =head2 GetItemHolds
 
-=over 4
-$holds = &GetItemHolds($biblionumber, $itemnumber);
-
-=back
+  $holds = &GetItemHolds($biblionumber, $itemnumber);
 
 This function return the count of holds with $biblionumber and $itemnumber
 
@@ -2492,39 +2578,225 @@ sub GetItemHolds {
     return $holds;
 }
 
-# Return the list of the column names of items table
-sub _get_items_columns {
+=head2 SearchItemsByField
+
+    my $items = SearchItemsByField($field, $value);
+
+SearchItemsByField will search for items on a specific given field.
+For instance you can search all items with a specific stocknumber like this:
+
+    my $items = SearchItemsByField('stocknumber', $stocknumber);
+
+=cut
+
+sub SearchItemsByField {
+    my ($field, $value) = @_;
+
+    my $filters = {
+        field => $field,
+        query => $value,
+    };
+
+    my ($results) = SearchItems($filters);
+    return $results;
+}
+
+sub _SearchItems_build_where_fragment {
+    my ($filter) = @_;
+
     my $dbh = C4::Context->dbh;
-    my $sth = $dbh->column_info(undef, undef, 'items', '%');
-    $sth->execute;
-    my $results = $sth->fetchall_hashref('COLUMN_NAME');
-    return keys %$results;
+
+    my $where_fragment;
+    if (exists($filter->{conjunction})) {
+        my (@where_strs, @where_args);
+        foreach my $f (@{ $filter->{filters} }) {
+            my $fragment = _SearchItems_build_where_fragment($f);
+            if ($fragment) {
+                push @where_strs, $fragment->{str};
+                push @where_args, @{ $fragment->{args} };
+            }
+        }
+        my $where_str = '';
+        if (@where_strs) {
+            $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
+            $where_fragment = {
+                str => $where_str,
+                args => \@where_args,
+            };
+        }
+    } else {
+        my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
+        push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
+        push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
+        my @operators = qw(= != > < >= <= like);
+        my $field = $filter->{field};
+        if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
+            my $op = $filter->{operator};
+            my $query = $filter->{query};
+
+            if (!$op or (0 == grep /^$op$/, @operators)) {
+                $op = '='; # default operator
+            }
+
+            my $column;
+            if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
+                my $marcfield = $1;
+                my $marcsubfield = $2;
+                my ($kohafield) = $dbh->selectrow_array(q|
+                    SELECT kohafield FROM marc_subfield_structure
+                    WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
+                |, undef, $marcfield, $marcsubfield);
+
+                if ($kohafield) {
+                    $column = $kohafield;
+                } else {
+                    # MARC field is not linked to a DB field so we need to use
+                    # ExtractValue on biblioitems.marcxml or
+                    # items.more_subfields_xml, depending on the MARC field.
+                    my $xpath;
+                    my $sqlfield;
+                    my ($itemfield) = GetMarcFromKohaField('items.itemnumber');
+                    if ($marcfield eq $itemfield) {
+                        $sqlfield = 'more_subfields_xml';
+                        $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
+                    } else {
+                        $sqlfield = 'marcxml';
+                        if ($marcfield < 10) {
+                            $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
+                        } else {
+                            $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
+                        }
+                    }
+                    $column = "ExtractValue($sqlfield, '$xpath')";
+                }
+            } else {
+                $column = $field;
+            }
+
+            if (ref $query eq 'ARRAY') {
+                if ($op eq '=') {
+                    $op = 'IN';
+                } elsif ($op eq '!=') {
+                    $op = 'NOT IN';
+                }
+                $where_fragment = {
+                    str => "$column $op (" . join (',', ('?') x @$query) . ")",
+                    args => $query,
+                };
+            } else {
+                $where_fragment = {
+                    str => "$column $op ?",
+                    args => [ $query ],
+                };
+            }
+        }
+    }
+
+    return $where_fragment;
 }
 
 =head2 SearchItems
 
-    my $items = SearchItems($field, $value);
+    my ($items, $total) = SearchItems($filter, $params);
 
-SearchItems will search for items on a specific given field.
-For instance you can search all items with a specific stocknumber like this:
+Perform a search among items
+
+$filter is a reference to a hash which can be a filter, or a combination of filters.
+
+A filter has the following keys:
+
+=over 2
+
+=item * field: the name of a SQL column in table items
+
+=item * query: the value to search in this column
+
+=item * operator: comparison operator. Can be one of = != > < >= <= like
+
+=back
+
+A combination of filters hash the following keys:
+
+=over 2
+
+=item * conjunction: 'AND' or 'OR'
 
-    my $items = SearchItems('stocknumber', $stocknumber);
+=item * filters: array ref of filters
+
+=back
+
+$params is a reference to a hash that can contain the following parameters:
+
+=over 2
+
+=item * rows: Number of items to return. 0 returns everything (default: 0)
+
+=item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
+               (default: 1)
+
+=item * sortby: A SQL column name in items table to sort on
+
+=item * sortorder: 'ASC' or 'DESC'
+
+=back
 
 =cut
 
 sub SearchItems {
-    my ($field, $value) = @_;
+    my ($filter, $params) = @_;
+
+    $filter //= {};
+    $params //= {};
+    return unless ref $filter eq 'HASH';
+    return unless ref $params eq 'HASH';
+
+    # Default parameters
+    $params->{rows} ||= 0;
+    $params->{page} ||= 1;
+    $params->{sortby} ||= 'itemnumber';
+    $params->{sortorder} ||= 'ASC';
+
+    my ($where_str, @where_args);
+    my $where_fragment = _SearchItems_build_where_fragment($filter);
+    if ($where_fragment) {
+        $where_str = $where_fragment->{str};
+        @where_args = @{ $where_fragment->{args} };
+    }
 
     my $dbh = C4::Context->dbh;
-    my @columns = _get_items_columns;
-    my $results = [];
-    if(0 < grep /^$field$/, @columns) {
-        my $query = "SELECT $field FROM items WHERE $field = ?";
-        my $sth = $dbh->prepare( $query );
-        $sth->execute( $value );
-        $results = $sth->fetchall_arrayref({});
+    my $query = q{
+        SELECT SQL_CALC_FOUND_ROWS items.*
+        FROM items
+          LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
+          LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
+    };
+    if (defined $where_str and $where_str ne '') {
+        $query .= qq{ WHERE $where_str };
     }
-    return $results;
+
+    my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
+    push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
+    push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
+    my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
+        ? $params->{sortby} : 'itemnumber';
+    my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
+    $query .= qq{ ORDER BY $sortby $sortorder };
+
+    my $rows = $params->{rows};
+    my @limit_args;
+    if ($rows > 0) {
+        my $offset = $rows * ($params->{page}-1);
+        $query .= qq { LIMIT ?, ? };
+        push @limit_args, $offset, $rows;
+    }
+
+    my $sth = $dbh->prepare($query);
+    my $rv = $sth->execute(@where_args, @limit_args);
+
+    return unless ($rv);
+    my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
+
+    return ($sth->fetchall_arrayref({}), $total_rows);
 }
 
 
@@ -2617,7 +2889,7 @@ sub PrepareItemrecordDisplay {
             # loop through each subfield
             my $cntsubf;
             foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
-                next if ( subfield_is_koha_internal_p($subfield) );
+                next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
                 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
                 my %subfield_data;
                 $subfield_data{tag}           = $tag;
@@ -2631,7 +2903,8 @@ sub PrepareItemrecordDisplay {
                 $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
                 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
                 $subfield_data{hidden}     = "display:none"
-                  if $tagslib->{$tag}->{$subfield}->{hidden};
+                  if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
+                    || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
                 my ( $x, $defaultvalue );
                 if ($itemrecord) {
                     ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
@@ -2689,8 +2962,8 @@ sub PrepareItemrecordDisplay {
                     # builds list, depending on authorised value...
                     #---- branch
                     if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
-                        if (   ( C4::Context->preference("IndependantBranches") )
-                            && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
+                        if (   ( C4::Context->preference("IndependentBranches") )
+                            && !C4::Context->IsSuperLibrarian() ) {
                             my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
                             $sth->execute( C4::Context->userenv->{branch} );
                             push @authorised_values, ""
@@ -2710,20 +2983,19 @@ sub PrepareItemrecordDisplay {
                             }
                         }
 
-                        $defaultvalue = C4::Context->userenv->{branch};
+                        $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
                         if ( $defaultvalues and $defaultvalues->{branchcode} ) {
                             $defaultvalue = $defaultvalues->{branchcode};
                         }
 
                         #----- itemtypes
                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
-                        my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
-                        $sth->execute;
+                        my $itemtypes = GetItemTypes( style => 'array' );
                         push @authorised_values, ""
                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
-                        while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
-                            push @authorised_values, $itemtype;
-                            $authorised_lib{$itemtype} = $description;
+                        for my $itemtype ( @$itemtypes ) {
+                            push @authorised_values, $itemtype->{itemtype};
+                            $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
                         }
                         #---- class_sources
                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
@@ -2754,37 +3026,37 @@ sub PrepareItemrecordDisplay {
                             $authorised_lib{$value} = $lib;
                         }
                     }
-                    $subfield_data{marc_value} = CGI::scrolling_list(
-                        -name     => 'field_value',
-                        -values   => \@authorised_values,
-                        -default  => "$defaultvalue",
-                        -labels   => \%authorised_lib,
-                        -size     => 1,
-                        -tabindex => '',
-                        -multiple => 0,
-                    );
+                    $subfield_data{marc_value} = {
+                        type    => 'select',
+                        values  => \@authorised_values,
+                        default => "$defaultvalue",
+                        labels  => \%authorised_lib,
+                    };
                 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
-                        # opening plugin
-                        my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
-                        if (do $plugin) {
-                            my $extended_param = plugin_parameters( $dbh, undef, $tagslib, $subfield_data{id}, undef );
-                            my ( $function_name, $javascript ) = plugin_javascript( $dbh, undef, $tagslib, $subfield_data{id}, undef );
-                            $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
-                            $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
-                                onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
-                                 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
-                                <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
-                                $javascript];
-                        } else {
-                            warn "Plugin Failed: $plugin";
-                            $subfield_data{marc_value} = qq(<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" />); # supply default input form
-                        }
+                # it is a plugin
+                    require Koha::FrameworkPlugin;
+                    my $plugin = Koha::FrameworkPlugin->new({
+                        name => $tagslib->{$tag}->{$subfield}->{value_builder},
+                        item_style => 1,
+                    });
+                    my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
+                    $plugin->build( $pars );
+                    if( !$plugin->errstr ) {
+                        #TODO Move html to template; see report 12176/13397
+                        my $tab= $plugin->noclick? '-1': '';
+                        my $class= $plugin->noclick? ' disabled': '';
+                        my $title= $plugin->noclick? 'No popup': 'Tag editor';
+                        $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
+                    } else {
+                        warn $plugin->errstr;
+                        $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" />); # supply default input form
+                    }
                 }
                 elsif ( $tag eq '' ) {       # it's an hidden field
-                    $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
+                    $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" />);
                 }
                 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
-                    $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
+                    $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" />);
                 }
                 elsif ( length($defaultvalue) > 100
                             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
@@ -2793,7 +3065,7 @@ sub PrepareItemrecordDisplay {
                                   500 <= $tag && $tag < 600                     )
                           ) {
                     # oversize field (textarea)
-                    $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255">$defaultvalue</textarea>\n");
+                    $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");
                 } else {
                     $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
                 }
@@ -2813,4 +3085,66 @@ sub PrepareItemrecordDisplay {
     };
 }
 
+sub ToggleNewStatus {
+    my ( $params ) = @_;
+    my @rules = @{ $params->{rules} };
+    my $report_only = $params->{report_only};
+
+    my $dbh = C4::Context->dbh;
+    my @errors;
+    my @item_columns = map { "items.$_" } Koha::Items->columns;
+    my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
+    my $report;
+    for my $rule ( @rules ) {
+        my $age = $rule->{age};
+        my $conditions = $rule->{conditions};
+        my $substitutions = $rule->{substitutions};
+        my @params;
+
+        my $query = q|
+            SELECT items.biblionumber, items.itemnumber
+            FROM items
+            LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
+            WHERE 1
+        |;
+        for my $condition ( @$conditions ) {
+            if (
+                 grep {/^$condition->{field}$/} @item_columns
+              or grep {/^$condition->{field}$/} @biblioitem_columns
+            ) {
+                if ( $condition->{value} =~ /\|/ ) {
+                    my @values = split /\|/, $condition->{value};
+                    $query .= qq| AND $condition->{field} IN (|
+                        . join( ',', ('?') x scalar @values )
+                        . q|)|;
+                    push @params, @values;
+                } else {
+                    $query .= qq| AND $condition->{field} = ?|;
+                    push @params, $condition->{value};
+                }
+            }
+        }
+        if ( defined $age ) {
+            $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
+            push @params, $age;
+        }
+        my $sth = $dbh->prepare($query);
+        $sth->execute( @params );
+        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 )
+                    unless $report_only;
+                push @{ $report->{$itemnumber} }, $substitution;
+            }
+        }
+    }
+
+    return $report;
+}
+
+
 1;