(bug #4075) add use of getrecordvalue in opac-detail
[koha.git] / opac / opac-detail.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 use warnings;
23
24 use CGI;
25 use C4::Auth;
26 use C4::Branch;
27 use C4::Koha;
28 use C4::Serials;    #uses getsubscriptionfrom biblionumber
29 use C4::Output;
30 use C4::Biblio;
31 use C4::Items;
32 use C4::Circulation;
33 use C4::Tags qw(get_tags);
34 use C4::Dates qw/format_date/;
35 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn get_biblio_from_xisbn);
36 use C4::External::Amazon;
37 use C4::Review;
38 use C4::Members;
39 use C4::XSLT;
40
41 BEGIN {
42         if (C4::Context->preference('BakerTaylorEnabled')) {
43                 require C4::External::BakerTaylor;
44                 import C4::External::BakerTaylor qw(&image_url &link_url);
45         }
46 }
47
48 my $query = new CGI;
49 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
50     {
51         template_name   => "opac-detail.tmpl",
52         query           => $query,
53         type            => "opac",
54         authnotrequired => 1,
55         flagsrequired   => { borrow => 1 },
56     }
57 );
58
59 my $biblionumber = $query->param('biblionumber') || $query->param('bib');
60
61 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
62 $template->param( 'ItemsIssued' => CountItemsIssued( $biblionumber ) );
63 $template->param(C4::Search::enabled_opac_search_views);
64
65 my $record       = GetMarcBiblio($biblionumber);
66 if ( ! $record ) {
67     print $query->redirect("/cgi-bin/koha/errors/404.pl");
68     exit;
69 }
70 $template->param( biblionumber => $biblionumber );
71 # XSLT processing of some stuff
72 if (C4::Context->preference("XSLTDetailsDisplay") ) {
73     $template->param(
74         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, C4::Context->preference("XSLTDetailsDisplay")) );
75 }
76
77 # change back when ive fixed request.pl
78 my @all_items = &GetItemsInfo( $biblionumber, 'opac' );
79 my @items;
80 @items = @all_items unless C4::Context->preference('hidelostitems');
81
82 if (C4::Context->preference('hidelostitems')) {
83     # Hide host items
84     for my $itm (@all_items) {
85         push @items, $itm unless $itm->{itemlost};
86     }
87 }
88 my $dat = &GetBiblioData($biblionumber);
89
90 my $itemtypes = GetItemTypes();
91 # imageurl:
92 my $itemtype = $dat->{'itemtype'};
93 if ( $itemtype ) {
94     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
95     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
96 }
97 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'});
98 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'} );
99
100 #coping with subscriptions
101 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
102 my @subscriptions       = GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
103 my @subs;
104 $dat->{'serials'}=1 if $subscriptionsnumber;
105 foreach my $subscription (@subscriptions) {
106     my %cell;
107     $cell{subscriptionid}    = $subscription->{subscriptionid};
108     $cell{subscriptionnotes} = $subscription->{notes};
109     $cell{branchcode}        = $subscription->{branchcode};
110     $cell{hasalert}          = $subscription->{hasalert};
111     #get the three latest serials.
112     $cell{latestserials} =
113       GetLatestSerials( $subscription->{subscriptionid}, 3 );
114     push @subs, \%cell;
115 }
116
117 $dat->{'count'} = scalar(@items);
118
119 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
120
121 my $norequests = 1;
122 my $branches = GetBranches();
123 my %itemfields;
124 for my $itm (@items) {
125     $norequests = 0
126        if ( (not $itm->{'wthdrawn'} )
127          && (not $itm->{'itemlost'} )
128          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
129                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
130          && ($itm->{'itemnumber'} ) );
131
132     if ( defined $itm->{'publictype'} ) {
133         # I can't actually find any case in which this is defined. --amoore 2008-12-09
134         $itm->{ $itm->{'publictype'} } = 1;
135     }
136     $itm->{datedue}      = format_date($itm->{datedue});
137     $itm->{datelastseen} = format_date($itm->{datelastseen});
138
139     # get collection code description, too
140     if ( my $ccode = $itm->{'ccode'} ) {
141         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
142     }
143     if ( defined $itm->{'location'} ) {
144         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
145     }
146     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
147         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
148         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
149     }
150     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
151         $itemfields{$_} = 1 if ($itm->{$_});
152     }
153
154      # walk through the item-level authorised values and populate some images
155      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
156      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
157
158      if ( $itm->{'itemlost'} ) {
159          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
160          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
161          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
162      }
163
164      if( $itm->{'count_reserves'}){
165           if( $itm->{'count_reserves'} eq "Waiting"){ $itm->{'waiting'} = 1; }
166           if( $itm->{'count_reserves'} eq "Reserved"){ $itm->{'onhold'} = 1; }
167      }
168     
169      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
170      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
171         $itm->{transfertwhen} = format_date($transfertwhen);
172         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
173         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
174      }
175 }
176
177 ## get notes and subjects from MARC record
178 my $dbh              = C4::Context->dbh;
179 my $marcflavour      = C4::Context->preference("marcflavour");
180 my $normalized_isbn  = GetNormalizedISBN($dat->{isbn},$record,$marcflavour);
181 my $marcnotesarray   = GetMarcNotes     ($record,$marcflavour);
182 my $marcauthorsarray = GetMarcAuthors   ($record,$marcflavour);
183 my $marcsubjctsarray = GetMarcSubjects  ($record,$marcflavour);
184 my $marcseriesarray  = GetMarcSeries    ($record,$marcflavour);
185 my $marcurlsarray    = GetMarcUrls      ($record,$marcflavour);
186 my $subtitle         = GetRecordValue('subtitle', $record, GetFrameworkCode($biblionumber));
187
188     $template->param(
189                      normalized_oclc         => GetNormalizedOCLCNumber($record,$marcflavour),
190                      normalized_upc          => GetNormalizedUPC       ($record,$marcflavour),
191                      normalized_isbn         => $normalized_isbn,
192                      MARCNOTES               => $marcnotesarray,
193                      MARCSUBJCTS             => $marcsubjctsarray,
194                      MARCAUTHORS             => $marcauthorsarray,
195                      MARCSERIES              => $marcseriesarray,
196                      MARCURLS                => $marcurlsarray,
197                      norequests              => $norequests,
198                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
199                      itemdata_ccode          => $itemfields{ccode},
200                      itemdata_enumchron      => $itemfields{enumchron},
201                      itemdata_uri            => $itemfields{uri},
202                      itemdata_copynumber     => $itemfields{copynumber},
203                      itemdata_itemnotes          => $itemfields{itemnotes},
204                      authorised_value_images => $biblio_authorised_value_images,
205                      subtitle                => $subtitle,
206     );
207
208 foreach ( keys %{$dat} ) {
209     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
210 }
211
212 # COinS format FIXME: for books Only
213 $template->param(
214     ocoins => GetCOinSBiblio($biblionumber),
215 );
216
217 my $reviews = getreviews( $biblionumber, 1 );
218 my $loggedincommenter;
219 foreach ( @$reviews ) {
220     my $borrowerData   = GetMember($_->{borrowernumber},'borrowernumber');
221     # setting some borrower info into this hash
222     $_->{title}     = $borrowerData->{'title'};
223     $_->{surname}   = $borrowerData->{'surname'};
224     $_->{firstname} = $borrowerData->{'firstname'};
225     $_->{userid}    = $borrowerData->{'userid'};
226     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
227     $_->{datereviewed} = format_date($_->{datereviewed});
228     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
229                 $_->{your_comment} = 1;
230                 $loggedincommenter = 1;
231         }
232 }
233
234
235 if(C4::Context->preference("ISBD")) {
236         $template->param(ISBD => 1);
237 }
238
239 $template->param(
240     ITEM_RESULTS        => \@items,
241     subscriptionsnumber => $subscriptionsnumber,
242     biblionumber        => $biblionumber,
243     subscriptions       => \@subs,
244     subscriptionsnumber => $subscriptionsnumber,
245     reviews             => $reviews,
246     loggedincommenter   => $loggedincommenter
247 );
248
249
250 # XISBN Stuff
251
252 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
253     eval {
254         $template->param(
255             XISBNS => get_xisbns($normalized_isbn)
256         );
257     };
258     if ($@) { warn "XISBN Failed $@"; }
259 }
260 # Amazon.com Stuff
261 if ( C4::Context->preference("OPACAmazonEnabled") ) {
262     $template->param( AmazonTld => get_amazon_tld() );
263 }
264 if ( C4::Context->preference("OPACAmazonEnabled") && C4::Context->preference("OPACAmazonSimilarItems") ) {
265     my $similar_products_exist;
266     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
267     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
268     my @services;
269     my $amazon_details = &get_amazon_details( $normalized_isbn, $record, $marcflavour, \@services );
270
271     if ( $amazon_reviews ) {
272         
273         my $item = $amazon_details->{Items}->{Item}->[0];
274         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
275         for my $one_review ( @$customer_reviews ) {
276             $one_review->{Date} = format_date($one_review->{Date});
277         }
278         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
279         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
280         $template->param( amazon_average_rating    => $average_rating * 20);
281         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
282         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
283     }
284     if ( $amazon_similars ) {
285         my $item = $amazon_details->{Items}->{Item}->[0];
286         my @similar_products;
287         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
288             # do we have any of these isbns in our collection?
289             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
290             # verify that there is at least one similar item
291             if (scalar(@$similar_biblionumbers)){
292                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
293                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
294             }
295         }
296         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
297         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
298     }    
299     
300 }
301
302 # Babelthèque
303 if ( C4::Context->preference("Babeltheque") ) {
304     $template->param( 
305         Babeltheque => 1,
306     );
307 }
308
309 # Shelf Browser Stuff
310 if (C4::Context->preference("OPACShelfBrowser")) {
311     # pick the first itemnumber unless one was selected by the user
312     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
313     $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
314     # find the right cn_sort value for this item
315     my ($starting_cn_sort, $starting_homebranch, $starting_location);
316     my $sth_get_cn_sort = $dbh->prepare("SELECT cn_sort,homebranch,location from items where itemnumber=?");
317     $sth_get_cn_sort->execute($starting_itemnumber);
318     while (my $result = $sth_get_cn_sort->fetchrow_hashref()) {
319         $starting_cn_sort = $result->{'cn_sort'};
320         $starting_homebranch->{code} = $result->{'homebranch'};
321         $starting_homebranch->{description} = $branches->{$result->{'homebranch'}}{branchname};
322         $starting_location->{code} = $result->{'location'};
323         $starting_location->{description} = GetAuthorisedValueDesc('','',   $result->{'location'} ,'','','LOC');
324     
325     }
326     
327     ## List of Previous Items
328     # order by cn_sort, which should include everything we need for ordering purposes (though not
329     # for limits, those need to be handled separately
330     my $sth_shelfbrowse_previous;
331     if (defined $starting_location->{code}) {
332       $sth_shelfbrowse_previous = $dbh->prepare("
333         SELECT *
334         FROM items
335         WHERE
336             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
337             homebranch = ? AND location = ?
338         ORDER BY cn_sort DESC, itemnumber LIMIT 3
339         ");
340       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
341     } else {
342       $sth_shelfbrowse_previous = $dbh->prepare("
343         SELECT *
344         FROM items
345         WHERE
346             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
347             homebranch = ?
348         ORDER BY cn_sort DESC, itemnumber LIMIT 3
349         ");
350       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
351     }
352     my @previous_items;
353     while (my $this_item = $sth_shelfbrowse_previous->fetchrow_hashref()) {
354         my $sth_get_biblio = $dbh->prepare("SELECT biblio.*,biblioitems.isbn AS isbn FROM biblio LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber WHERE biblio.biblionumber=?");
355         $sth_get_biblio->execute($this_item->{biblionumber});
356         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
357             $this_item->{'title'} = $this_biblio->{'title'};
358         }
359         unshift @previous_items, $this_item;
360     }
361     
362     ## List of Next Items; this also intentionally catches the current item
363     my $sth_shelfbrowse_next;
364     if (defined $starting_location->{code}) {
365       $sth_shelfbrowse_next = $dbh->prepare("
366         SELECT *
367         FROM items
368         WHERE
369             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
370             homebranch = ? AND location = ?
371         ORDER BY cn_sort, itemnumber LIMIT 3
372         ");
373       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
374     } 
375     else {
376       $sth_shelfbrowse_next = $dbh->prepare("
377         SELECT *
378         FROM items
379         WHERE
380             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
381             homebranch = ?
382         ORDER BY cn_sort, itemnumber LIMIT 3
383         ");
384       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
385     }
386     my @next_items;
387     while (my $this_item = $sth_shelfbrowse_next->fetchrow_hashref()) {
388         my $sth_get_biblio = $dbh->prepare("SELECT biblio.*,biblioitems.isbn AS isbn FROM biblio LEFT JOIN biblioitems ON biblio.biblionumber=biblioitems.biblionumber WHERE biblio.biblionumber=?");
389         $sth_get_biblio->execute($this_item->{biblionumber});
390         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
391             $this_item->{'title'} = $this_biblio->{'title'};
392         }
393         push @next_items, $this_item;
394     }
395
396
397     # alas, these won't auto-vivify, see http://www.perlmonks.org/?node_id=508481
398     my $shelfbrowser_next_itemnumber = $next_items[-1]->{itemnumber} if @next_items;
399     my $shelfbrowser_next_biblionumber = $next_items[-1]->{biblionumber} if @next_items;
400     
401     $template->param(
402         starting_homebranch => $starting_homebranch->{description},
403         starting_location => $starting_location->{description},
404         starting_itemnumber => $starting_itemnumber,
405         shelfbrowser_prev_itemnumber => (@previous_items ? $previous_items[0]->{itemnumber} : 0),
406         shelfbrowser_next_itemnumber => $shelfbrowser_next_itemnumber,
407         shelfbrowser_prev_biblionumber => (@previous_items ? $previous_items[0]->{biblionumber} : 0),
408         shelfbrowser_next_biblionumber => $shelfbrowser_next_biblionumber,
409         PREVIOUS_SHELF_BROWSE => \@previous_items,
410         NEXT_SHELF_BROWSE => \@next_items,
411     );
412 }
413
414 if (C4::Context->preference("BakerTaylorEnabled")) {
415         $template->param(
416                 BakerTaylorEnabled  => 1,
417                 BakerTaylorImageURL => &image_url(),
418                 BakerTaylorLinkURL  => &link_url(),
419                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
420         );
421         my ($bt_user, $bt_pass);
422         if ($normalized_isbn and
423                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
424                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
425         {
426                 $template->param(
427                 BakerTaylorContentURL   =>
428                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
429                                 $bt_user,$bt_pass,$normalized_isbn)
430                 );
431         }
432 }
433
434 my $tag_quantity;
435 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
436         $template->param(
437                 TagsEnabled => 1,
438                 TagsShowOnDetail => $tag_quantity,
439                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
440         );
441         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
442                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
443 }
444
445 output_html_with_http_headers $query, $cookie, $template->output;