Bug 25444: Simplify the code using a loop
[koha-ffzg.git] / C4 / Search.pm
index 6d7157c..cd9b892 100644 (file)
@@ -15,8 +15,7 @@ package C4::Search;
 # 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
+use Modern::Perl;
 require Exporter;
 use C4::Context;
 use C4::Biblio;    # GetMarcFromKohaField, GetBiblioData
@@ -34,6 +33,7 @@ use Koha::AuthorisedValues;
 use Koha::ItemTypes;
 use Koha::Libraries;
 use Koha::Patrons;
+use Koha::RecordProcessor;
 use YAML;
 use URI::Escape;
 use Business::ISBN;
@@ -100,22 +100,10 @@ sub FindDuplicate {
         $query = "isbn:$result->{isbn}";
     }
     else {
-        my $QParser;
-        $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
-        my $titleindex;
-        my $authorindex;
-        my $op;
-
-        if ($QParser) {
-            $titleindex = 'title|exact';
-            $authorindex = 'author|exact';
-            $op = '&&';
-            $QParser->custom_data->{'QueryAutoTruncate'} = C4::Context->preference('QueryAutoTruncate');
-        } else {
-            $titleindex = 'ti,ext';
-            $authorindex = 'au,ext';
-            $op = 'and';
-        }
+
+        my $titleindex = 'ti,ext';
+        my $authorindex = 'au,ext';
+        my $op = 'and';
 
         $result->{title} =~ s /\\//g;
         $result->{title} =~ s /\"//g;
@@ -234,25 +222,12 @@ sub SimpleSearch {
     my $results = [];
     my $total_hits = 0;
 
-    my $QParser;
-    $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser') && ! ($query =~ m/\w,\w|\w=\w/));
-    if ($QParser) {
-        $QParser->custom_data->{'QueryAutoTruncate'} = C4::Context->preference('QueryAutoTruncate');
-    }
-
     # Initialize & Search Zebra
     for ( my $i = 0 ; $i < @servers ; $i++ ) {
         eval {
             $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 );
-            if ($QParser) {
-                $query =~ s/=/:/g unless $options{skip_normalize};
-                $QParser->parse( $query );
-                $query = $QParser->target_syntax($servers[$i]);
-                $zoom_queries[$i] = new ZOOM::Query::PQF( $query, $zconns[$i]);
-            } else {
-                $query =~ s/:/=/g unless $options{skip_normalize};
-                $zoom_queries[$i] = new ZOOM::Query::CCL2RPN( $query, $zconns[$i]);
-            }
+            $query =~ s/:/=/g unless $options{skip_normalize};
+            $zoom_queries[$i] = new ZOOM::Query::CCL2RPN( $query, $zconns[$i]);
             $tmpresults[$i] = $zconns[$i]->search( $zoom_queries[$i] );
 
             # error handling
@@ -625,7 +600,7 @@ sub getRecords {
         foreach my $f (@facets_loop) {
             $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
         }
-        @facets_loop = sort {$a->{expand} cmp $b->{expand}} @facets_loop;
+        @facets_loop = sort {defined $a->{expand} && defined $b->{expand} && $a->{expand} cmp $b->{expand}} @facets_loop;
     }
 
     return ( undef, $results_hashref, \@facets_loop );
@@ -713,7 +688,7 @@ sub _get_facets_data_from_record {
 
                 my $data = $field->as_string( $subfield_letters, $facet->{ sep } );
 
-                unless ( grep { /^\Q$data\E$/ } @used_datas ) {
+                unless ( grep { $_ eq $data } @used_datas ) {
                     push @used_datas, $data;
                     $facets_counter->{ $facet->{ idx } }->{ $data }++;
                 }
@@ -1278,134 +1253,6 @@ sub getIndexes{
     return \@indexes;
 }
 
-=head2 _handle_exploding_index
-
-    my $query = _handle_exploding_index($index, $term)
-
-Callback routine to generate the search for "exploding" indexes (i.e.
-those indexes which are turned into multiple or-connected searches based
-on authority data).
-
-=cut
-
-sub _handle_exploding_index {
-    my ($QParser, $filter, $params, $negate, $server) = @_;
-    my $index = $filter;
-    my $term = join(' ', @$params);
-
-    return unless ($index =~ m/(su-br|su-na|su-rl)/ && $term);
-
-    my $marcflavour = C4::Context->preference('marcflavour');
-
-    my $codesubfield = $marcflavour eq 'UNIMARC' ? '5' : 'w';
-    my $wantedcodes = '';
-    my @subqueries = ( "\@attr 1=Subject \@attr 4=1 \"$term\"");
-    my ($error, $results, $total_hits) = SimpleSearch( "he:$term", undef, undef, [ "authorityserver" ] );
-    foreach my $auth (@$results) {
-        my $record = MARC::Record->new_from_usmarc($auth);
-        my @references = $record->field('5..');
-        if (@references) {
-            if ($index eq 'su-br') {
-                $wantedcodes = 'g';
-            } elsif ($index eq 'su-na') {
-                $wantedcodes = 'h';
-            } elsif ($index eq 'su-rl') {
-                $wantedcodes = '';
-            }
-            foreach my $reference (@references) {
-                my $codes = $reference->subfield($codesubfield);
-                push @subqueries, '@attr 1=Subject @attr 4=1 "' . $reference->as_string('abcdefghijlmnopqrstuvxyz') . '"' if (($codes && $codes eq $wantedcodes) || !$wantedcodes);
-            }
-        }
-    }
-    my $query = ' @or ' x (scalar(@subqueries) - 1) . join(' ', @subqueries);
-    return $query;
-}
-
-=head2 parseQuery
-
-    ( $operators, $operands, $indexes, $limits,
-      $sort_by, $scan, $lang ) =
-            parseQuery ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang);
-
-Shim function to ease the transition from buildQuery to a new QueryParser.
-This function is called at the beginning of buildQuery, and modifies
-buildQuery's input. If it can handle the input, it returns a query that
-buildQuery will not try to parse.
-
-=cut
-
-sub parseQuery {
-    my ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang) = @_;
-
-    my @operators = $operators ? @$operators : ();
-    my @indexes   = $indexes   ? @$indexes   : ();
-    my @operands  = $operands  ? @$operands  : ();
-    my @limits    = $limits    ? @$limits    : ();
-    my @sort_by   = $sort_by   ? @$sort_by   : ();
-
-    my $query = $operands[0];
-    my $index;
-    my $term;
-    my $query_desc;
-
-    my $QParser;
-    $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser') || $query =~ s/^qp=//);
-    undef $QParser if ($query =~ m/^(ccl=|pqf=|cql=)/ || grep (/\w,\w|\w=\w/, @operands, @indexes) );
-    undef $QParser if (scalar @limits > 0);
-
-    if ($QParser)
-    {
-        $QParser->custom_data->{'QueryAutoTruncate'} = C4::Context->preference('QueryAutoTruncate');
-        $query = '';
-        for ( my $ii = 0 ; $ii <= @operands ; $ii++ ) {
-            next unless $operands[$ii];
-            $query .= $operators[ $ii - 1 ] eq 'or' ? ' || ' : ' && '
-              if ($query);
-            if ( $operands[$ii] =~ /^[^"]\W*[-|_\w]*:\w.*[^"]$/ ) {
-                $query .= $operands[$ii];
-            }
-            elsif ( $indexes[$ii] =~ m/su-/ ) {
-                $query .= $indexes[$ii] . '(' . $operands[$ii] . ')';
-            }
-            else {
-                $query .=
-                  ( $indexes[$ii] ? "$indexes[$ii]:" : '' ) . $operands[$ii];
-            }
-        }
-        foreach my $limit (@limits) {
-        }
-        if ( scalar(@sort_by) > 0 ) {
-            my $modifier_re =
-              '#(' . join( '|', @{ $QParser->modifiers } ) . ')';
-            $query =~ s/$modifier_re//g;
-            foreach my $modifier (@sort_by) {
-                $query .= " #$modifier";
-            }
-        }
-
-        $query_desc = $query;
-        $query_desc =~ s/\s+/ /g;
-        if ( C4::Context->preference("QueryWeightFields") ) {
-        }
-        $QParser->add_bib1_filter_map( 'su-br' => 'biblioserver' =>
-              { 'target_syntax_callback' => \&_handle_exploding_index } );
-        $QParser->add_bib1_filter_map( 'su-na' => 'biblioserver' =>
-              { 'target_syntax_callback' => \&_handle_exploding_index } );
-        $QParser->add_bib1_filter_map( 'su-rl' => 'biblioserver' =>
-              { 'target_syntax_callback' => \&_handle_exploding_index } );
-        $QParser->parse($query);
-        $operands[0] = "pqf=" . $QParser->target_syntax('biblioserver');
-    }
-    else {
-        require Koha::QueryParser::Driver::PQF;
-        my $modifier_re = '#(' . join( '|', @{Koha::QueryParser::Driver::PQF->modifiers}) . ')';
-        s/$modifier_re//g for @operands;
-    }
-
-    return ( $operators, \@operands, $indexes, $limits, $sort_by, $scan, $lang, $query_desc);
-}
-
 =head2 buildQuery
 
 ( $error, $query,
@@ -1428,7 +1275,6 @@ sub buildQuery {
     warn "---------\nEnter buildQuery\n---------" if $DEBUG;
 
     my $query_desc;
-    ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang, $query_desc) = parseQuery($operators, $operands, $indexes, $limits, $sort_by, $scan, $lang);
 
     # dereference
     my @operators = $operators ? @$operators : ();
@@ -1471,14 +1317,14 @@ sub buildQuery {
         # this happens when selecting a subject on the opac-detail page
         @limits = grep {!/^$/} @limits;
         my $original_q = $q; # without available part
-        unless ( grep { /^available$/ } @limits ) {
-            $q =~ s| and \( \( allrecords,AlwaysMatches:'' not onloan,AlwaysMatches:''\) and \(lost,st-numeric=0\) \)||;
+        unless ( grep { $_ eq 'available' } @limits ) {
+            $q =~ s| and \( \(allrecords,AlwaysMatches=''\) and \(not-onloan-count,st-numeric >= 1\) and \(lost,st-numeric=0\) \)||;
             $original_q = $q;
         }
         if ( @limits ) {
-            if ( grep { /^available$/ } @limits ) {
-                $q .= q| and ( ( allrecords,AlwaysMatches:'' not onloan,AlwaysMatches:'') and (lost,st-numeric=0) )|;
-                delete $limits['available'];
+            if ( grep { $_ eq 'available' } @limits ) {
+                $q .= q| and ( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )|;
+                @limits = grep {!/^available$/} @limits;
             }
             $q .= ' and '.join(' and ', @limits) if @limits;
         }
@@ -1488,12 +1334,8 @@ sub buildQuery {
         return ( undef, $', $', "q=cql=".uri_escape_utf8($'), $', '', '', '', 'cql' );
     }
     if ( $query =~ /^pqf=/ ) {
-        if ($query_desc) {
-            $query_cgi = "q=".uri_escape_utf8($query_desc);
-        } else {
-            $query_desc = $';
-            $query_cgi = "q=pqf=".uri_escape_utf8($');
-        }
+        $query_desc = $';
+        $query_cgi = "q=pqf=".uri_escape_utf8($');
         return ( undef, $', $', $query_cgi, $query_desc, '', '', '', 'pqf' );
     }
 
@@ -1537,7 +1379,7 @@ sub buildQuery {
                     $operands[$i] =~ s/\?/{?}/g; # need to escape question marks
                 }
                 my $operand = $operands[$i];
-                my $index   = $indexes[$i];
+                my $index   = $indexes[$i] || 'kw';
 
                 # Add index-specific attributes
 
@@ -1574,18 +1416,14 @@ sub buildQuery {
                         if ( C4::Context->preference("SearchWithISBNVariations") ) {
                             my @isbns = C4::Koha::GetVariationsOfISBN( $operand );
                             $operands[$i] = $operand =  '(nb=' . join(' OR nb=', @isbns) . ')';
-                            $indexes[$i] = $index = '';
+                            $indexes[$i] = $index = 'kw';
                         }
                     }
                 }
 
-                if(not $index){
-                    $index = 'kw';
-                }
-
                 # Set default structure attribute (word list)
                 my $struct_attr = q{};
-                unless ( $indexes_set || !$index || $index =~ /,(st-|phr|ext|wrdl)/ || $index =~ /^(nb|ns)$/ ) {
+                unless ( $indexes_set || $index =~ /,(st-|phr|ext|wrdl)/ || $index =~ /^(nb|ns)$/ ) {
                     $struct_attr = ",wrdl";
                 }
 
@@ -1691,7 +1529,7 @@ sub buildQuery {
 ## In English:
 ## all records not indexed in the onloan register (zebra) and all records with a value of lost equal to 0
             $availability_limit .=
-"( ( allrecords,AlwaysMatches='' not onloan,AlwaysMatches='') and (lost,st-numeric=0) )"; #or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='')) )";
+"( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )";
             $limit_cgi  .= "&limit=available";
             $limit_desc .= "";
         }
@@ -1751,6 +1589,13 @@ sub buildQuery {
     $query =~ s/(?<=(st-numeric)):/=/g;
     $query =~ s/(?<=(st-year)):/=/g;
     $query =~ s/(?<=(st-date-normalized)):/=/g;
+
+    # Removing warnings for later substitutions
+    $query      //= q{};
+    $query_desc //= q{};
+    $query_cgi  //= q{};
+    $limit      //= q{};
+    $limit_desc //= q{};
     $limit =~ s/:/=/g;
     for ( $query, $query_desc, $limit, $limit_desc ) {
         s/  +/ /g;    # remove extra spaces
@@ -1813,7 +1658,7 @@ sub _build_initial_query {
     $params->{query_cgi} .= "&q=".uri_escape_utf8($params->{original_operand}) if $params->{original_operand};
 
     #e.g. " and kw,wrdl: test"
-    $params->{query_desc} .= $operator . $params->{index_plus} . " " . $params->{original_operand};
+    $params->{query_desc} .= $operator . ( $params->{index_plus} // q{} ) . " " . ( $params->{original_operand} // q{} );
 
     $params->{previous_operand} = 1 unless $params->{previous_operand}; #If there is no previous operand, mark this as one
 
@@ -1833,7 +1678,7 @@ Format results in a form suitable for passing to the template
 # IMO this subroutine is pretty messy still -- it's responsible for
 # building the HTML output for the template
 sub searchResults {
-    my ( $search_context, $searchdesc, $hits, $results_per_page, $offset, $scan, $marcresults ) = @_;
+    my ( $search_context, $searchdesc, $hits, $results_per_page, $offset, $scan, $marcresults, $xslt_variables ) = @_;
     my $dbh = C4::Context->dbh;
     my @newresults;
 
@@ -1846,6 +1691,10 @@ sub searchResults {
         $is_opac       = 1;
     }
 
+    my $record_processor = Koha::RecordProcessor->new({
+        filters => 'ViewPolicy'
+    });
+
     #Build branchnames hash
     my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' });
 
@@ -1938,12 +1787,8 @@ sub searchResults {
 
         SetUTF8Flag($marcrecord);
         my $oldbiblio = TransformMarcToKoha( $marcrecord, $fw );
-        $oldbiblio->{subtitle} = GetRecordValue('subtitle', $marcrecord);
         $oldbiblio->{result_number} = $i + 1;
 
-        # add imageurl to itemtype if there is one
-        $oldbiblio->{imageurl} = getitemtypeimagelocation( $search_context, $itemtypes{ $oldbiblio->{itemtype} }->{imageurl} );
-
                $oldbiblio->{normalized_upc}  = GetNormalizedUPC(       $marcrecord,$marcflavour);
                $oldbiblio->{normalized_ean}  = GetNormalizedEAN(       $marcrecord,$marcflavour);
                $oldbiblio->{normalized_oclc} = GetNormalizedOCLCNumber($marcrecord,$marcflavour);
@@ -1952,10 +1797,15 @@ sub searchResults {
 
                # edition information, if any
         $oldbiblio->{edition} = $oldbiblio->{editionstatement};
-        $oldbiblio->{description} = $itemtypes{ $oldbiblio->{itemtype} }->{translated_description};
- # Build summary if there is one (the summary is defined in the itemtypes table)
- # FIXME: is this used anywhere, I think it can be commented out? -- JF
-        if ( $itemtypes{ $oldbiblio->{itemtype} }->{summary} ) {
+
+        my $itemtype = $oldbiblio->{itemtype} ? $itemtypes{$oldbiblio->{itemtype}} : undef;
+        # add imageurl to itemtype if there is one
+        $oldbiblio->{imageurl} = $itemtype ? getitemtypeimagelocation( $search_context->{'interface'}, $itemtype->{imageurl} ) : q{};
+        # Build summary if there is one (the summary is defined in the itemtypes table)
+        $oldbiblio->{description} = $itemtype ? $itemtype->{translated_description} : q{};
+
+        # FIXME: this is only used in the deprecated non-XLST opac results
+        if ( !$xslfile && $is_opac && $itemtype && $itemtype->{summary} ) {
             my $summary = $itemtypes{ $oldbiblio->{itemtype} }->{summary};
             my @fields  = $marcrecord->fields();
 
@@ -2014,18 +1864,11 @@ sub searchResults {
                 my $hostbiblionumber = $hostfield->subfield("0");
                 my $linkeditemnumber = $hostfield->subfield("9");
                 if( $hostbiblionumber ) {
-                    my $hostbiblio = GetMarcBiblio({
-                        biblionumber => $hostbiblionumber,
-                        embed_items  => 1 });
-                    my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
-                    if( $hostbiblio ) {
-                        my @hostitems = $hostbiblio->field($itemfield);
-                        foreach my $hostitem (@hostitems){
-                            if ($hostitem->subfield("9") eq $linkeditemnumber){
-                                my $linkeditem =$hostitem;
-                                # append linked items if they exist
-                                push @fields, $linkeditem if $linkeditem;
-                            }
+                    my $linkeditemmarc = C4::Items::GetMarcItem( $hostbiblionumber, $linkeditemnumber );
+                    if ($linkeditemmarc) {
+                        my $linkeditemfield = $linkeditemmarc->field($itemtag);
+                        if ($linkeditemfield) {
+                            push( @fields, $linkeditemfield );
                         }
                     }
                 }
@@ -2068,7 +1911,7 @@ sub searchResults {
             foreach my $code ( keys %subfieldstosearch ) {
                 $item->{$code} = $field->subfield( $subfieldstosearch{$code} );
             }
-            $item->{description} = $itemtypes{ $item->{itype} }{translated_description};
+            $item->{description} = $itemtypes{ $item->{itype} }{translated_description} if $item->{itype};
 
                # OPAC hidden items
             if ($is_opac) {
@@ -2097,7 +1940,11 @@ sub searchResults {
                 $item->{'branchname'} = $branches{$item->{$otherbranch}};
             }
 
-                       my $prefix = $item->{$hbranch} . '--' . $item->{location} . $item->{itype} . $item->{itemcallnumber};
+            my $prefix =
+                ( $item->{$hbranch} ? $item->{$hbranch} . '--' : q{} )
+              . ( $item->{location} ? $item->{location} : q{} )
+              . ( $item->{itype}    ? $item->{itype}    : q{} )
+              . ( $item->{itemcallnumber} ? $item->{itemcallnumber} : q{} );
 # For each grouping of items (onloan, available, unavailable), we build a key to store relevant info about that item
             if ( $item->{onloan}
                 and $logged_in_user
@@ -2127,7 +1974,9 @@ sub searchResults {
          # items not on loan, but still unavailable ( lost, withdrawn, damaged )
             else {
 
-                $item->{notforloan}=1 if !$item->{notforloan}  && $itemtypes{ C4::Context->preference("item-level_itypes")? $item->{itype}: $oldbiblio->{itemtype} }->{notforloan};
+                my $itemtype = C4::Context->preference("item-level_itypes")? $item->{itype}: $oldbiblio->{itemtype};
+                $item->{notforloan} = 1 if !$item->{notforloan} &&
+                    $itemtype && $itemtypes{ $itemtype }->{notforloan};
 
                 # item is on order
                 if ( $item->{notforloan} < 0 ) {
@@ -2172,14 +2021,14 @@ sub searchResults {
                     || $item->{damaged}
                     || $item->{notforloan}
                     || $reservestatus eq 'Waiting'
-                    || ($transfertwhen ne ''))
+                    || ($transfertwhen && $transfertwhen ne ''))
                 {
                     $withdrawn_count++        if $item->{withdrawn};
                     $itemlost_count++        if $item->{itemlost};
                     $itemdamaged_count++     if $item->{damaged};
-                    $item_in_transit_count++ if $transfertwhen ne '';
+                    $item_in_transit_count++ if $transfertwhen && $transfertwhen ne '';
                     $item_onhold_count++     if $reservestatus eq 'Waiting';
-                    $item->{status} = $item->{withdrawn} . "-" . $item->{itemlost} . "-" . $item->{damaged} . "-" . $item->{notforloan};
+                    $item->{status} = ($item->{withdrawn}//q{}) . "-" . ($item->{itemlost}//q{}) . "-" . ($item->{damaged}//q{}) . "-" . ($item->{notforloan}//q{});
 
                     # can place a hold on a item if
                     # not lost nor withdrawn
@@ -2203,9 +2052,9 @@ sub searchResults {
                     $other_items->{$key}->{onhold} = ($reservestatus) ? 1 : 0;
                     $other_items->{$key}->{notforloan} = GetAuthorisedValueDesc('','',$item->{notforloan},'','',$notforloan_authorised_value) if $notforloan_authorised_value and $item->{notforloan};
                     $other_items->{$key}->{count}++ if $item->{$hbranch};
-                    $other_items->{$key}->{location} = $shelflocations->{ $item->{location} };
+                    $other_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
                     $other_items->{$key}->{description} = $item->{description};
-                    $other_items->{$key}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype} }->{imageurl} );
+                    $other_items->{$key}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} );
                 }
                 # item is available
                 else {
@@ -2215,8 +2064,8 @@ sub searchResults {
                     foreach (qw(branchname itemcallnumber description)) {
                         $available_items->{$prefix}->{$_} = $item->{$_};
                     }
-                    $available_items->{$prefix}->{location} = $shelflocations->{ $item->{location} };
-                    $available_items->{$prefix}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype} }->{imageurl} );
+                    $available_items->{$prefix}->{location} = $shelflocations->{ $item->{location} } if $item->{location};
+                    $available_items->{$prefix}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} );
                 }
             }
         }    # notforloan, item level and biblioitem level
@@ -2243,12 +2092,18 @@ sub searchResults {
         # XSLT processing of some stuff
         # we fetched the sysprefs already before the loop through all retrieved record!
         if (!$scan && $xslfile) {
-            $oldbiblio->{XSLTResultsRecord} = XSLTParse4Display($oldbiblio->{biblionumber}, $marcrecord, $xslsyspref, 1, \@hiddenitems, $sysxml, $xslfile, $lang);
+            $record_processor->options({
+                frameworkcode => $fw,
+                interface     => $search_context->{'interface'}
+            });
+
+            $record_processor->process($marcrecord);
+            $oldbiblio->{XSLTResultsRecord} = XSLTParse4Display($oldbiblio->{biblionumber}, $marcrecord, $xslsyspref, 1, \@hiddenitems, $sysxml, $xslfile, $lang, $xslt_variables);
         }
 
         # if biblio level itypes are used and itemtype is notforloan, it can't be reserved either
         if (!C4::Context->preference("item-level_itypes")) {
-            if ($itemtypes{ $oldbiblio->{itemtype} }->{notforloan}) {
+            if ($itemtype && $itemtype->{notforloan}) {
                 $can_place_holds = 0;
             }
         }
@@ -2299,6 +2154,8 @@ sub searchResults {
             $oldbiblio->{'alternateholdings_count'} = $alternateholdingscount;
         }
 
+        $oldbiblio->{biblio_object} = Koha::Biblios->find( $oldbiblio->{biblionumber} );
+
         push( @newresults, $oldbiblio );
     }