Merge branch 'new/enh/bug_5579' into kcmaster
[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 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
45     {
46         template_name   => "catalogue/detail.tmpl",
47         query           => $query,
48         type            => "intranet",
49         authnotrequired => 0,
50         flagsrequired   => { catalogue => 1 },
51     }
52 );
53
54 my $biblionumber = $query->param('biblionumber');
55 my $record       = GetMarcBiblio($biblionumber);
56
57 if ( not defined $record ) {
58     # biblionumber invalid -> report and exit
59     $template->param( unknownbiblionumber => 1,
60                       biblionumber => $biblionumber );
61     output_html_with_http_headers $query, $cookie, $template->output;
62     exit;
63 }
64
65 if($query->cookie("holdfor")){ 
66     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
67     $template->param(
68         holdfor => $query->cookie("holdfor"),
69         holdfor_surname => $holdfor_patron->{'surname'},
70         holdfor_firstname => $holdfor_patron->{'firstname'},
71         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
72     );
73 }
74
75 my $fw           = GetFrameworkCode($biblionumber);
76 my $showallitems = $query->param('showallitems');
77 my $marcflavour  = C4::Context->preference("marcflavour");
78
79 # XSLT processing of some stuff
80 if (C4::Context->preference("XSLTDetailsDisplay") ) {
81     $template->param('XSLTDetailsDisplay' =>'1',
82         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, 'Detail','intranet') );
83 }
84
85 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
86
87 # some useful variables for enhanced content;
88 # in each case, we're grabbing the first value we find in
89 # the record and normalizing it
90 my $upc = GetNormalizedUPC($record,$marcflavour);
91 my $ean = GetNormalizedEAN($record,$marcflavour);
92 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
93 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
94
95 $template->param(
96     normalized_upc => $upc,
97     normalized_ean => $ean,
98     normalized_oclc => $oclc,
99     normalized_isbn => $isbn,
100 );
101
102 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
103 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
104 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
105 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
106 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
107 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
108 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
109
110 # Get Branches, Itemtypes and Locations
111 my $branches = GetBranches();
112 my $itemtypes = GetItemTypes();
113 my $dbh = C4::Context->dbh;
114
115 # 'intra' param included, even though it's not respected in GetItemsInfo currently
116 my @all_items= GetItemsInfo($biblionumber, 'intra');
117 my @items;
118 for my $itm (@all_items) {
119     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
120 }
121 my $dat = &GetBiblioData($biblionumber);
122
123 # get count of holds
124 my ( $holdcount, $holds ) = GetReservesFromBiblionumber($biblionumber,1);
125
126 #coping with subscriptions
127 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
128 my @subscriptions       = GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
129 my @subs;
130
131 foreach my $subscription (@subscriptions) {
132     my %cell;
133         my $serials_to_display;
134     $cell{subscriptionid}    = $subscription->{subscriptionid};
135     $cell{subscriptionnotes} = $subscription->{notes};
136     $cell{branchcode}        = $subscription->{branchcode};
137     $cell{branchname}        = GetBranchName($subscription->{branchcode});
138     $cell{hasalert}          = $subscription->{hasalert};
139     #get the three latest serials.
140         $serials_to_display = $subscription->{staffdisplaycount};
141         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
142         $cell{staffdisplaycount} = $serials_to_display;
143     $cell{latestserials} =
144       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
145     push @subs, \%cell;
146 }
147
148 if ( defined $dat->{'itemtype'} ) {
149     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
150 }
151
152 $dat->{'count'} = scalar @all_items;
153 $dat->{'showncount'} = scalar @items;
154 $dat->{'hiddencount'} = scalar @all_items - scalar @items;
155
156 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
157 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
158 my (@itemloop, %itemfields);
159 my $norequests = 1;
160 my $authvalcode_items_itemlost = GetAuthValCode('items.itemlost',$fw);
161 my $authvalcode_items_damaged  = GetAuthValCode('items.damaged', $fw);
162 foreach my $item (@items) {
163
164     $item->{homebranch}        = GetBranchName($item->{homebranch});
165
166     # can place holds defaults to yes
167     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
168
169     # format some item fields for display
170     if ( defined $item->{'publictype'} ) {
171         $item->{ $item->{'publictype'} } = 1;
172     }
173     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
174                                                : '';
175
176         foreach (qw(datedue datelastseen onloan)) {
177                 $item->{$_} = format_date($item->{$_});
178         }
179     # item damaged, lost, withdrawn loops
180     $item->{itemlostloop} = GetAuthorisedValues($authvalcode_items_itemlost, $item->{itemlost}) if $authvalcode_items_itemlost;
181     if ($item->{damaged}) {
182         $item->{itemdamagedloop} = GetAuthorisedValues($authvalcode_items_damaged, $item->{damaged}) if $authvalcode_items_damaged;
183     }
184     #get shelf location and collection code description if they are authorised value.
185     my $shelfcode = $item->{'location'};
186     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
187     my $ccode = $item->{'ccode'};
188     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
189     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
190         $itemfields{$_} = 1 if ( $item->{$_} );
191     }
192
193     # checking for holds
194     my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($item->{itemnumber});
195     my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
196     
197     if (C4::Context->preference('HidePatronName')){
198         $item->{'hidepatronname'} = 1;
199     }
200
201     if ( defined $reservedate ) {
202         $item->{backgroundcolor} = 'reserved';
203         $item->{reservedate}     = format_date($reservedate);
204         $item->{ReservedForBorrowernumber}     = $reservedfor;
205         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
206         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
207         $item->{ExpectedAtLibrary}      = $branches->{$expectedAt}{branchname};
208         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
209     }
210
211         # Check the transit status
212     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
213     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
214         $item->{transfertwhen} = format_date($transfertwhen);
215         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
216         $item->{transfertto}   = $branches->{$transfertto}{branchname};
217         $item->{nocancel} = 1;
218     }
219
220     # FIXME: move this to a pm, check waiting status for holds
221     my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
222     $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
223     while (my $wait_hashref = $sth2->fetchrow_hashref) {
224         $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
225     }
226
227     push @itemloop, $item;
228 }
229
230 $template->param( norequests => $norequests );
231 $template->param(
232         MARCNOTES   => $marcnotesarray,
233         MARCSUBJCTS => $marcsubjctsarray,
234         MARCAUTHORS => $marcauthorsarray,
235         MARCSERIES  => $marcseriesarray,
236         MARCURLS => $marcurlsarray,
237     MARCISBNS => $marcisbnsarray,
238         subtitle    => $subtitle,
239         itemdata_ccode      => $itemfields{ccode},
240         itemdata_enumchron  => $itemfields{enumchron},
241         itemdata_uri        => $itemfields{uri},
242         itemdata_copynumber => $itemfields{copynumber},
243         volinfo                         => $itemfields{enumchron},
244     itemdata_itemnotes  => $itemfields{itemnotes},
245         z3950_search_params     => C4::Search::z3950_search_args($dat),
246     holdcount           => $holdcount,
247         C4::Search::enabled_staff_search_views,
248 );
249
250 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
251     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
252     my $subfields = substr $fieldspec, 3;
253     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
254     my @alternateholdingsinfo = ();
255     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
256
257     for my $field (@holdingsfields) {
258         my %holding = ( holding => '' );
259         my $havesubfield = 0;
260         for my $subfield ($field->subfields()) {
261             if ((index $subfields, $$subfield[0]) >= 0) {
262                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
263                 $holding{'holding'} .= $$subfield[1];
264                 $havesubfield++;
265             }
266         }
267         if ($havesubfield) {
268             push(@alternateholdingsinfo, \%holding);
269         }
270     }
271
272     $template->param(
273         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
274         );
275 }
276
277 my @results = ( $dat, );
278 foreach ( keys %{$dat} ) {
279     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
280 }
281
282 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
283 # method query not found?!?!
284
285 $template->param(
286     itemloop        => \@itemloop,
287     biblionumber        => $biblionumber,
288     detailview => 1,
289     subscriptions       => \@subs,
290     subscriptionsnumber => $subscriptionsnumber,
291     subscriptiontitle   => $dat->{title},
292 );
293
294 # $debug and $template->param(debug_display => 1);
295
296 # Lists
297
298 if (C4::Context->preference("virtualshelves") ) {
299    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
300 }
301
302 # XISBN Stuff
303 if (C4::Context->preference("FRBRizeEditions")==1) {
304     eval {
305         $template->param(
306             XISBNS => get_xisbns($isbn)
307         );
308     };
309     if ($@) { warn "XISBN Failed $@"; }
310 }
311 if ( C4::Context->preference("AmazonEnabled") == 1 ) {
312     $template->param( AmazonTld => get_amazon_tld() );
313     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
314     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
315     my @services;
316     if ( $amazon_reviews ) {
317         $template->param( AmazonReviews => 1 );
318         push( @services, 'EditorialReview' );
319     }
320     if ( $amazon_similars ) {
321         $template->param( AmazonSimilarItems => 1 );
322         push( @services, 'Similarities' );
323     }
324     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
325     if ( $amazon_similars ) {
326         my $similar_products_exist;
327         my @similar_products;
328         for my $similar_product (@{$amazon_details->{Items}->{Item}->[0]->{SimilarProducts}->{SimilarProduct}}) {
329             # do we have any of these isbns in our collection?
330             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
331             # verify that there is at least one similar item
332                     if (scalar(@$similar_biblionumbers)){            
333                             $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
334                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
335             }
336         }
337         $template->param( AmazonSimilarItems       => $similar_products_exist );
338         $template->param( AMAZON_SIMILAR_PRODUCTS  => \@similar_products      );
339     }
340     if ( $amazon_reviews ) {
341         my $item = $amazon_details->{Items}->{Item}->[0];
342         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
343         #my $customer_reviews  = \@{$amazon_details->{Items}->{Item}->[0]->{CustomerReviews}->{Review}};
344         #my $average_rating = $amazon_details->{Items}->{Item}->[0]->{CustomerReviews}->{AverageRating} || 0;
345         #$template->param( amazon_average_rating    => $average_rating * 20    );
346         #$template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews       );
347         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews      );
348     }
349 }
350
351 # Get OPAC URL
352 if (C4::Context->preference('OPACBaseURL')){
353      $template->param( OpacUrl => C4::Context->preference('OPACBaseURL') );
354 }
355
356 output_html_with_http_headers $query, $cookie, $template->output;