7ce4cf7f832d107f006e2ca45fbca76231ba040d
[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::Serials;
39 use C4::Members;
40 use C4::XSLT;
41
42 BEGIN {
43         if (C4::Context->preference('BakerTaylorEnabled')) {
44                 require C4::External::BakerTaylor;
45                 import C4::External::BakerTaylor qw(&image_url &link_url);
46         }
47 }
48
49 my $query = new CGI;
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
51     {
52         template_name   => "opac-detail.tmpl",
53         query           => $query,
54         type            => "opac",
55         authnotrequired => 1,
56         flagsrequired   => { borrow => 1 },
57     }
58 );
59
60 my $biblionumber = $query->param('biblionumber') || $query->param('bib');
61
62 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
63 $template->param( 'ItemsIssued' => CountItemsIssued( $biblionumber ) );
64
65 my $record       = GetMarcBiblio($biblionumber);
66 $template->param( biblionumber => $biblionumber );
67 # XSLT processing of some stuff
68 if (C4::Context->preference("XSLTDetailsDisplay") ) {
69     $template->param(
70         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, 'Detail') );
71 }
72
73 # change back when ive fixed request.pl
74 my @all_items = &GetItemsInfo( $biblionumber, 'opac' );
75 my @items;
76 @items = @all_items unless C4::Context->preference('hidelostitems');
77
78 if (C4::Context->preference('hidelostitems')) {
79     # Hide host items
80     for my $itm (@all_items) {
81         push @items, $itm unless $itm->{itemlost};
82     }
83 }
84 my $dat = &GetBiblioData($biblionumber);
85
86 if (!$dat) {
87     print $query->redirect("/cgi-bin/koha/errors/404.pl");
88     exit;
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->{'serial'}=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 $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
181 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
182 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
183 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
184 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
185 my $subtitle         = C4::Biblio::get_koha_field_from_marc('bibliosubtitle', 'subtitle', $record, '');
186
187     $template->param(
188                      MARCNOTES               => $marcnotesarray,
189                      MARCSUBJCTS             => $marcsubjctsarray,
190                      MARCAUTHORS             => $marcauthorsarray,
191                      MARCSERIES              => $marcseriesarray,
192                      MARCURLS                => $marcurlsarray,
193                      norequests              => $norequests,
194                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
195                      itemdata_ccode          => $itemfields{ccode},
196                      itemdata_enumchron      => $itemfields{enumchron},
197                      itemdata_uri            => $itemfields{uri},
198                      itemdata_copynumber     => $itemfields{copynumber},
199                      itemdata_itemnotes          => $itemfields{itemnotes},
200                      authorised_value_images => $biblio_authorised_value_images,
201                      subtitle                => $subtitle,
202     );
203
204 foreach ( keys %{$dat} ) {
205     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
206 }
207
208 # COinS format FIXME: for books Only
209 $template->param(
210     ocoins => GetCOinSBiblio($biblionumber),
211 );
212
213 my $reviews = getreviews( $biblionumber, 1 );
214 my $loggedincommenter;
215 foreach ( @$reviews ) {
216     my $borrowerData   = GetMember($_->{borrowernumber},'borrowernumber');
217     # setting some borrower info into this hash
218     $_->{title}     = $borrowerData->{'title'};
219     $_->{surname}   = $borrowerData->{'surname'};
220     $_->{firstname} = $borrowerData->{'firstname'};
221     $_->{userid}    = $borrowerData->{'userid'};
222     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
223     $_->{datereviewed} = format_date($_->{datereviewed});
224     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
225                 $_->{your_comment} = 1;
226                 $loggedincommenter = 1;
227         }
228 }
229
230
231 if(C4::Context->preference("ISBD")) {
232         $template->param(ISBD => 1);
233 }
234
235 $template->param(
236     ITEM_RESULTS        => \@items,
237     subscriptionsnumber => $subscriptionsnumber,
238     biblionumber        => $biblionumber,
239     subscriptions       => \@subs,
240     subscriptionsnumber => $subscriptionsnumber,
241     reviews             => $reviews,
242     loggedincommenter   => $loggedincommenter
243 );
244
245 sub isbn_cleanup ($) {
246         my $isbn=shift;
247     ($isbn) = $isbn =~ /([\d-]*[X]*)/;
248     $isbn =~ s/-//g;
249         if (
250                 $isbn =~ /\b(\d{13})\b/ or
251                 $isbn =~ /\b(\d{10})\b/ or 
252                 $isbn =~ /\b(\d{9}X)\b/i
253         ) {
254                 return $1;
255         }
256         return undef;
257 }
258
259 # XISBN Stuff
260 my $xisbn=$dat->{'isbn'};
261 (my $aisbn) = $xisbn =~ /([\d-]*[X]*)/;
262 $aisbn =~ s/-//g;
263 $template->param(amazonisbn => $aisbn);         # FIXME: so it is OK if the ISBN = 'XXXXX' ?
264 my ($clean,$clean2);
265 # these might be overkill, but they are better than the regexp above.
266 if ($clean = isbn_cleanup($xisbn)){
267         $template->param(clean_isbn => $clean);
268 }
269
270 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
271     eval {
272         $template->param(
273             xisbn => $xisbn,
274             XISBNS => get_xisbns($xisbn)
275         );
276     };
277     if ($@) { warn "XISBN Failed $@"; }
278 }
279 # Amazon.com Stuff
280 if ( C4::Context->preference("OPACAmazonEnabled") ) {
281     $template->param( AmazonTld => get_amazon_tld() );
282 }
283 if ( C4::Context->preference("OPACAmazonEnabled") && C4::Context->preference("OPACAmazonSimilarItems") ) {
284     my $similar_products_exist;
285     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
286     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
287     my @services;
288     my $amazon_details = &get_amazon_details( $dat->{isbn}, $record, $marcflavour, \@services );
289
290     if ( $amazon_reviews ) {
291         
292         my $item = $amazon_details->{Items}->{Item}->[0];
293         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
294         for my $one_review ( @$customer_reviews ) {
295             $one_review->{Date} = format_date($one_review->{Date});
296         }
297         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
298         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
299         $template->param( amazon_average_rating    => $average_rating * 20);
300         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
301         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
302     }
303     if ( $amazon_similars ) {
304         my $item = $amazon_details->{Items}->{Item}->[0];
305         my @similar_products;
306         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
307             # do we have any of these isbns in our collection?
308             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
309             # verify that there is at least one similar item
310             if (scalar(@$similar_biblionumbers)){
311                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
312                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
313             }
314         }
315         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
316         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
317     }    
318     
319 }
320
321 # Babelthèque
322 if ( C4::Context->preference("Babeltheque") ) {
323     $template->param( 
324         Babeltheque => 1,
325     );
326 }
327
328 # Shelf Browser Stuff
329 if (C4::Context->preference("OPACShelfBrowser")) {
330     # pick the first itemnumber unless one was selected by the user
331     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
332     $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
333     # find the right cn_sort value for this item
334     my ($starting_cn_sort, $starting_homebranch, $starting_location);
335     my $sth_get_cn_sort = $dbh->prepare("SELECT cn_sort,homebranch,location from items where itemnumber=?");
336     $sth_get_cn_sort->execute($starting_itemnumber);
337     while (my $result = $sth_get_cn_sort->fetchrow_hashref()) {
338         $starting_cn_sort = $result->{'cn_sort'};
339         $starting_homebranch->{code} = $result->{'homebranch'};
340         $starting_homebranch->{description} = $branches->{$result->{'homebranch'}}{branchname};
341         $starting_location->{code} = $result->{'location'};
342         $starting_location->{description} = GetAuthorisedValueDesc('','',   $result->{'location'} ,'','','LOC');
343     
344     }
345     
346     ## List of Previous Items
347     # order by cn_sort, which should include everything we need for ordering purposes (though not
348     # for limits, those need to be handled separately
349     my $sth_shelfbrowse_previous;
350     if (defined $starting_location->{code}) {
351       $sth_shelfbrowse_previous = $dbh->prepare("
352         SELECT *
353         FROM items
354         WHERE
355             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
356             homebranch = ? AND location = ?
357         ORDER BY cn_sort DESC, itemnumber LIMIT 3
358         ");
359       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
360     } else {
361       $sth_shelfbrowse_previous = $dbh->prepare("
362         SELECT *
363         FROM items
364         WHERE
365             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
366             homebranch = ?
367         ORDER BY cn_sort DESC, itemnumber LIMIT 3
368         ");
369       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
370     }
371     my @previous_items;
372     while (my $this_item = $sth_shelfbrowse_previous->fetchrow_hashref()) {
373         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=?");
374         $sth_get_biblio->execute($this_item->{biblionumber});
375         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
376             $this_item->{'title'} = $this_biblio->{'title'};
377             if ($clean2 = isbn_cleanup($this_biblio->{'isbn'})) {
378                 $this_item->{'isbn'} = $clean2;
379             } else { 
380                 $this_item->{'isbn'} = $this_biblio->{'isbn'};
381             }
382         }
383         unshift @previous_items, $this_item;
384     }
385     
386     ## List of Next Items; this also intentionally catches the current item
387     my $sth_shelfbrowse_next;
388     if (defined $starting_location->{code}) {
389       $sth_shelfbrowse_next = $dbh->prepare("
390         SELECT *
391         FROM items
392         WHERE
393             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
394             homebranch = ? AND location = ?
395         ORDER BY cn_sort, itemnumber LIMIT 3
396         ");
397       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
398     } 
399     else {
400       $sth_shelfbrowse_next = $dbh->prepare("
401         SELECT *
402         FROM items
403         WHERE
404             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
405             homebranch = ?
406         ORDER BY cn_sort, itemnumber LIMIT 3
407         ");
408       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
409     }
410     my @next_items;
411     while (my $this_item = $sth_shelfbrowse_next->fetchrow_hashref()) {
412         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=?");
413         $sth_get_biblio->execute($this_item->{biblionumber});
414         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
415             $this_item->{'title'} = $this_biblio->{'title'};
416             if ($clean2 = isbn_cleanup($this_biblio->{'isbn'})) {
417                 $this_item->{'isbn'} = $clean2;
418             } else { 
419                 $this_item->{'isbn'} = $this_biblio->{'isbn'};
420             }
421         }
422         push @next_items, $this_item;
423     }
424
425
426     # alas, these won't auto-vivify, see http://www.perlmonks.org/?node_id=508481
427     my $shelfbrowser_next_itemnumber = $next_items[-1]->{itemnumber} if @next_items;
428     my $shelfbrowser_next_biblionumber = $next_items[-1]->{biblionumber} if @next_items;
429     
430     $template->param(
431         starting_homebranch => $starting_homebranch->{description},
432         starting_location => $starting_location->{description},
433         starting_itemnumber => $starting_itemnumber,
434         shelfbrowser_prev_itemnumber => (@previous_items ? $previous_items[0]->{itemnumber} : 0),
435         shelfbrowser_next_itemnumber => $shelfbrowser_next_itemnumber,
436         shelfbrowser_prev_biblionumber => (@previous_items ? $previous_items[0]->{biblionumber} : 0),
437         shelfbrowser_next_biblionumber => $shelfbrowser_next_biblionumber,
438         PREVIOUS_SHELF_BROWSE => \@previous_items,
439         NEXT_SHELF_BROWSE => \@next_items,
440     );
441 }
442
443 if (C4::Context->preference("BakerTaylorEnabled")) {
444         $template->param(
445                 BakerTaylorEnabled  => 1,
446                 BakerTaylorImageURL => &image_url(),
447                 BakerTaylorLinkURL  => &link_url(),
448                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
449         );
450         my ($bt_user, $bt_pass);
451         if ($clean and
452                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
453                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
454         {
455                 $template->param(
456                 BakerTaylorContentURL   =>
457                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
458                                 $bt_user,$bt_pass,$clean)
459                 );
460         }
461 }
462
463 my $tag_quantity;
464 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
465         $template->param(
466                 TagsEnabled => 1,
467                 TagsShowOnDetail => $tag_quantity,
468                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
469         );
470         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
471                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
472 }
473
474 output_html_with_http_headers $query, $cookie, $template->output;