Bug 6840 warning in logs
[koha.git] / catalogue / detail.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18
19 use strict;
20 use warnings;
21
22 use CGI;
23 use C4::Auth;
24 use C4::Dates qw/format_date/;
25 use C4::Koha;
26 use C4::Serials;    #uses getsubscriptionfrom biblionumber
27 use C4::Output;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Circulation;
31 use C4::Branch;
32 use C4::Reserves;
33 use C4::Members; # to use GetMember
34 use C4::Serials;
35 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
36 use C4::External::Amazon;
37 use C4::Search;         # enabled_staff_search_views
38 use C4::VirtualShelves;
39 use C4::XSLT;
40
41 # use Smart::Comments;
42
43 my $query = CGI->new();
44
45 my $analyze = $query->param('analyze');
46
47 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
48     {
49     template_name   =>  'catalogue/detail.tmpl',
50         query           => $query,
51         type            => "intranet",
52         authnotrequired => 0,
53         flagsrequired   => { catalogue => 1 },
54     }
55 );
56
57 my $biblionumber = $query->param('biblionumber');
58 my $record       = GetMarcBiblio($biblionumber);
59
60 if ( not defined $record ) {
61     # biblionumber invalid -> report and exit
62     $template->param( unknownbiblionumber => 1,
63                       biblionumber => $biblionumber );
64     output_html_with_http_headers $query, $cookie, $template->output;
65     exit;
66 }
67
68 if($query->cookie("holdfor")){ 
69     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
70     $template->param(
71         holdfor => $query->cookie("holdfor"),
72         holdfor_surname => $holdfor_patron->{'surname'},
73         holdfor_firstname => $holdfor_patron->{'firstname'},
74         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
75     );
76 }
77
78 my $fw           = GetFrameworkCode($biblionumber);
79 my $showallitems = $query->param('showallitems');
80 my $marcflavour  = C4::Context->preference("marcflavour");
81
82 # XSLT processing of some stuff
83 if (C4::Context->preference("XSLTDetailsDisplay") ) {
84     $template->param('XSLTDetailsDisplay' =>'1',
85         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, 'Detail','intranet') );
86 }
87
88 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
89
90 # some useful variables for enhanced content;
91 # in each case, we're grabbing the first value we find in
92 # the record and normalizing it
93 my $upc = GetNormalizedUPC($record,$marcflavour);
94 my $ean = GetNormalizedEAN($record,$marcflavour);
95 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
96 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
97
98 $template->param(
99     normalized_upc => $upc,
100     normalized_ean => $ean,
101     normalized_oclc => $oclc,
102     normalized_isbn => $isbn,
103 );
104
105 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
106 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
107 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
108 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
109 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
110 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
111 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
112 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
113
114 # Get Branches, Itemtypes and Locations
115 my $branches = GetBranches();
116 my $itemtypes = GetItemTypes();
117 my $dbh = C4::Context->dbh;
118
119 my @all_items = GetItemsInfo( $biblionumber );
120 my @items;
121 for my $itm (@all_items) {
122     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
123 }
124
125 # flag indicating existence of at least one item linked via a host record
126 my $hostrecords;
127 # adding items linked via host biblios
128 my @hostitems = GetHostItemsInfo($record);
129 if (@hostitems){
130         $hostrecords =1;
131         push (@items,@hostitems);
132 }
133
134 my $dat = &GetBiblioData($biblionumber);
135
136 # get count of holds
137 my ( $holdcount, $holds ) = GetReservesFromBiblionumber($biblionumber,1);
138
139 #coping with subscriptions
140 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
141 my @subscriptions       = GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
142 my @subs;
143
144 foreach my $subscription (@subscriptions) {
145     my %cell;
146         my $serials_to_display;
147     $cell{subscriptionid}    = $subscription->{subscriptionid};
148     $cell{subscriptionnotes} = $subscription->{notes};
149     $cell{branchcode}        = $subscription->{branchcode};
150     $cell{branchname}        = GetBranchName($subscription->{branchcode});
151     $cell{hasalert}          = $subscription->{hasalert};
152     #get the three latest serials.
153         $serials_to_display = $subscription->{staffdisplaycount};
154         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
155         $cell{staffdisplaycount} = $serials_to_display;
156     $cell{latestserials} =
157       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
158     push @subs, \%cell;
159 }
160
161 if ( defined $dat->{'itemtype'} ) {
162     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
163 }
164
165 $dat->{'count'} = scalar @all_items + @hostitems;
166 $dat->{'showncount'} = scalar @items + @hostitems;
167 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
168
169 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
170 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
171 my (@itemloop, %itemfields);
172 my $norequests = 1;
173 my $authvalcode_items_itemlost = GetAuthValCode('items.itemlost',$fw);
174 my $authvalcode_items_damaged  = GetAuthValCode('items.damaged', $fw);
175
176 my $analytics_flag;
177 foreach my $item (@items) {
178
179     $item->{homebranch}        = GetBranchName($item->{homebranch});
180
181     # can place holds defaults to yes
182     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
183
184     # format some item fields for display
185     if ( defined $item->{'publictype'} ) {
186         $item->{ $item->{'publictype'} } = 1;
187     }
188     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
189                                                : '';
190
191         foreach (qw(datedue datelastseen onloan)) {
192                 $item->{$_} = format_date($item->{$_});
193         }
194     # item damaged, lost, withdrawn loops
195     $item->{itemlostloop} = GetAuthorisedValues($authvalcode_items_itemlost, $item->{itemlost}) if $authvalcode_items_itemlost;
196     if ($item->{damaged}) {
197         $item->{itemdamagedloop} = GetAuthorisedValues($authvalcode_items_damaged, $item->{damaged}) if $authvalcode_items_damaged;
198     }
199     #get shelf location and collection code description if they are authorised value.
200     my $shelfcode = $item->{'location'};
201     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
202     my $ccode = $item->{'ccode'};
203     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
204     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
205         $itemfields{$_} = 1 if ( $item->{$_} );
206     }
207
208     # checking for holds
209     my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($item->{itemnumber});
210     my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
211     
212     if (C4::Context->preference('HidePatronName')){
213         $item->{'hidepatronname'} = 1;
214     }
215
216     if ( defined $reservedate ) {
217         $item->{backgroundcolor} = 'reserved';
218         $item->{reservedate}     = format_date($reservedate);
219         $item->{ReservedForBorrowernumber}     = $reservedfor;
220         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
221         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
222         $item->{ExpectedAtLibrary}      = $branches->{$expectedAt}{branchname};
223         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
224     }
225
226         # Check the transit status
227     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
228     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
229         $item->{transfertwhen} = format_date($transfertwhen);
230         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
231         $item->{transfertto}   = $branches->{$transfertto}{branchname};
232         $item->{nocancel} = 1;
233     }
234
235     # FIXME: move this to a pm, check waiting status for holds
236     my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
237     $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
238     while (my $wait_hashref = $sth2->fetchrow_hashref) {
239         $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
240     }
241
242     # item has a host number if its biblio number does not match the current bib
243     if ($item->{biblionumber} ne $biblionumber){
244         $item->{hostbiblionumber} = $item->{biblionumber};
245         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
246     }
247         
248         #count if item is used in analytical bibliorecords
249         my $countanalytics= GetAnalyticsCount($item->{itemnumber});
250         if ($countanalytics > 0){
251                 $analytics_flag=1;
252                 $item->{countanalytics} = $countanalytics;
253         }
254
255     push @itemloop, $item;
256 }
257
258 $template->param( norequests => $norequests );
259 $template->param(
260         MARCNOTES   => $marcnotesarray,
261         MARCSUBJCTS => $marcsubjctsarray,
262         MARCAUTHORS => $marcauthorsarray,
263         MARCSERIES  => $marcseriesarray,
264         MARCURLS => $marcurlsarray,
265     MARCISBNS => $marcisbnsarray,
266         MARCHOSTS => $marchostsarray,
267         subtitle    => $subtitle,
268         itemdata_ccode      => $itemfields{ccode},
269         itemdata_enumchron  => $itemfields{enumchron},
270         itemdata_uri        => $itemfields{uri},
271         itemdata_copynumber => $itemfields{copynumber},
272         volinfo                         => $itemfields{enumchron},
273     itemdata_itemnotes  => $itemfields{itemnotes},
274         z3950_search_params     => C4::Search::z3950_search_args($dat),
275     holdcount           => $holdcount,
276         hostrecords         => $hostrecords,
277         analytics_flag  => $analytics_flag,
278         C4::Search::enabled_staff_search_views,
279 );
280
281 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
282     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
283     my $subfields = substr $fieldspec, 3;
284     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
285     my @alternateholdingsinfo = ();
286     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
287
288     for my $field (@holdingsfields) {
289         my %holding = ( holding => '' );
290         my $havesubfield = 0;
291         for my $subfield ($field->subfields()) {
292             if ((index $subfields, $$subfield[0]) >= 0) {
293                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
294                 $holding{'holding'} .= $$subfield[1];
295                 $havesubfield++;
296             }
297         }
298         if ($havesubfield) {
299             push(@alternateholdingsinfo, \%holding);
300         }
301     }
302
303     $template->param(
304         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
305         );
306 }
307
308 my @results = ( $dat, );
309 foreach ( keys %{$dat} ) {
310     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
311 }
312
313 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
314 # method query not found?!?!
315
316 $template->param(
317     itemloop        => \@itemloop,
318     biblionumber        => $biblionumber,
319     ($analyze? 'analyze':'detailview') =>1,
320     subscriptions       => \@subs,
321     subscriptionsnumber => $subscriptionsnumber,
322     subscriptiontitle   => $dat->{title},
323 );
324
325 # $debug and $template->param(debug_display => 1);
326
327 # Lists
328
329 if (C4::Context->preference("virtualshelves") ) {
330    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
331 }
332
333 # XISBN Stuff
334 if (C4::Context->preference("FRBRizeEditions")==1) {
335     eval {
336         $template->param(
337             XISBNS => get_xisbns($isbn)
338         );
339     };
340     if ($@) { warn "XISBN Failed $@"; }
341 }
342 if ( C4::Context->preference("AmazonEnabled") == 1 ) {
343     $template->param( AmazonTld => get_amazon_tld() );
344     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
345     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
346     my @services;
347     if ( $amazon_reviews ) {
348         $template->param( AmazonReviews => 1 );
349         push( @services, 'EditorialReview' );
350     }
351     if ( $amazon_similars ) {
352         $template->param( AmazonSimilarItems => 1 );
353         push( @services, 'Similarities' );
354     }
355     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
356     if ( $amazon_similars ) {
357         my $similar_products_exist;
358         my @similar_products;
359         for my $similar_product (@{$amazon_details->{Items}->{Item}->[0]->{SimilarProducts}->{SimilarProduct}}) {
360             # do we have any of these isbns in our collection?
361             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
362             # verify that there is at least one similar item
363                     if (scalar(@$similar_biblionumbers)){            
364                             $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
365                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
366             }
367         }
368         $template->param( AmazonSimilarItems       => $similar_products_exist );
369         $template->param( AMAZON_SIMILAR_PRODUCTS  => \@similar_products      );
370     }
371     if ( $amazon_reviews ) {
372         my $item = $amazon_details->{Items}->{Item}->[0];
373         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
374         #my $customer_reviews  = \@{$amazon_details->{Items}->{Item}->[0]->{CustomerReviews}->{Review}};
375         #my $average_rating = $amazon_details->{Items}->{Item}->[0]->{CustomerReviews}->{AverageRating} || 0;
376         #$template->param( amazon_average_rating    => $average_rating * 20    );
377         #$template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews       );
378         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews      );
379     }
380 }
381
382 # Get OPAC URL
383 if (C4::Context->preference('OPACBaseURL')){
384      $template->param( OpacUrl => C4::Context->preference('OPACBaseURL') );
385 }
386
387 output_html_with_http_headers $query, $cookie, $template->output;