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