bugfix: pagination bar has an empty page at the end
[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
64 my $record       = GetMarcBiblio($biblionumber);
65 $template->param( biblionumber => $biblionumber );
66 # XSLT processing of some stuff
67 if (C4::Context->preference("XSLTDetailsDisplay") ) {
68     $template->param(
69         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, 'Detail') );
70 }
71
72 # change back when ive fixed request.pl
73 my @all_items = &GetItemsInfo( $biblionumber, 'opac' );
74 my @items;
75 @items = @all_items unless C4::Context->preference('hidelostitems');
76
77 if (C4::Context->preference('hidelostitems')) {
78     # Hide host items
79     for my $itm (@all_items) {
80         push @items, $itm unless $itm->{itemlost};
81     }
82 }
83 my $dat = &GetBiblioData($biblionumber);
84
85 if (!$dat) {
86     print $query->redirect("/cgi-bin/koha/errors/404.pl");
87     exit;
88 }
89 my $itemtypes = GetItemTypes();
90 # imageurl:
91 my $itemtype = $dat->{'itemtype'};
92 if ( $itemtype ) {
93     $dat->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
94     $dat->{'description'} = $itemtypes->{$itemtype}->{'description'};
95 }
96 my $shelflocations =GetKohaAuthorisedValues('items.location',$dat->{'frameworkcode'});
97 my $collections =  GetKohaAuthorisedValues('items.ccode',$dat->{'frameworkcode'} );
98
99 #coping with subscriptions
100 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
101 my @subscriptions       = GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
102 my @subs;
103 $dat->{'serials'}=1 if $subscriptionsnumber;
104 foreach my $subscription (@subscriptions) {
105     my %cell;
106     $cell{subscriptionid}    = $subscription->{subscriptionid};
107     $cell{subscriptionnotes} = $subscription->{notes};
108     $cell{branchcode}        = $subscription->{branchcode};
109     $cell{hasalert}          = $subscription->{hasalert};
110     #get the three latest serials.
111     $cell{latestserials} =
112       GetLatestSerials( $subscription->{subscriptionid}, 3 );
113     push @subs, \%cell;
114 }
115
116 $dat->{'count'} = scalar(@items);
117
118 my $biblio_authorised_value_images = C4::Items::get_authorised_value_images( C4::Biblio::get_biblio_authorised_values( $biblionumber, $record ) );
119
120 my $norequests = 1;
121 my $branches = GetBranches();
122 my %itemfields;
123 for my $itm (@items) {
124     $norequests = 0
125        if ( (not $itm->{'wthdrawn'} )
126          && (not $itm->{'itemlost'} )
127          && ($itm->{'itemnotforloan'}<0 || not $itm->{'itemnotforloan'} )
128                  && (not $itemtypes->{$itm->{'itype'}}->{notforloan} )
129          && ($itm->{'itemnumber'} ) );
130
131     if ( defined $itm->{'publictype'} ) {
132         # I can't actually find any case in which this is defined. --amoore 2008-12-09
133         $itm->{ $itm->{'publictype'} } = 1;
134     }
135     $itm->{datedue}      = format_date($itm->{datedue});
136     $itm->{datelastseen} = format_date($itm->{datelastseen});
137
138     # get collection code description, too
139     if ( my $ccode = $itm->{'ccode'} ) {
140         $itm->{'ccode'} = $collections->{$ccode} if ( defined($collections) && exists( $collections->{$ccode} ) );
141     }
142     if ( defined $itm->{'location'} ) {
143         $itm->{'location_description'} = $shelflocations->{ $itm->{'location'} };
144     }
145     if (exists $itm->{itype} && defined($itm->{itype}) && exists $itemtypes->{ $itm->{itype} }) {
146         $itm->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{ $itm->{itype} }->{'imageurl'} );
147         $itm->{'description'} = $itemtypes->{ $itm->{itype} }->{'description'};
148     }
149     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
150         $itemfields{$_} = 1 if ($itm->{$_});
151     }
152
153      # walk through the item-level authorised values and populate some images
154      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
155      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
156
157      if ( $itm->{'itemlost'} ) {
158          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
159          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
160          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
161      }
162
163      if( $itm->{'count_reserves'}){
164           if( $itm->{'count_reserves'} eq "Waiting"){ $itm->{'waiting'} = 1; }
165           if( $itm->{'count_reserves'} eq "Reserved"){ $itm->{'onhold'} = 1; }
166      }
167     
168      my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($itm->{itemnumber});
169      if ( defined( $transfertwhen ) && $transfertwhen ne '' ) {
170         $itm->{transfertwhen} = format_date($transfertwhen);
171         $itm->{transfertfrom} = $branches->{$transfertfrom}{branchname};
172         $itm->{transfertto}   = $branches->{$transfertto}{branchname};
173      }
174 }
175
176 ## get notes and subjects from MARC record
177 my $dbh              = C4::Context->dbh;
178 my $marcflavour      = C4::Context->preference("marcflavour");
179 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
180 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
181 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
182 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
183 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
184 my $subtitle         = C4::Biblio::get_koha_field_from_marc('bibliosubtitle', 'subtitle', $record, '');
185
186     $template->param(
187                      MARCNOTES               => $marcnotesarray,
188                      MARCSUBJCTS             => $marcsubjctsarray,
189                      MARCAUTHORS             => $marcauthorsarray,
190                      MARCSERIES              => $marcseriesarray,
191                      MARCURLS                => $marcurlsarray,
192                      norequests              => $norequests,
193                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
194                      itemdata_ccode          => $itemfields{ccode},
195                      itemdata_enumchron      => $itemfields{enumchron},
196                      itemdata_uri            => $itemfields{uri},
197                      itemdata_copynumber     => $itemfields{copynumber},
198                      itemdata_itemnotes          => $itemfields{itemnotes},
199                      authorised_value_images => $biblio_authorised_value_images,
200                      subtitle                => $subtitle,
201     );
202
203 foreach ( keys %{$dat} ) {
204     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
205 }
206
207 # COinS format FIXME: for books Only
208 $template->param(
209     ocoins => GetCOinSBiblio($biblionumber),
210 );
211
212 my $reviews = getreviews( $biblionumber, 1 );
213 my $loggedincommenter;
214 foreach ( @$reviews ) {
215     my $borrowerData   = GetMember($_->{borrowernumber},'borrowernumber');
216     # setting some borrower info into this hash
217     $_->{title}     = $borrowerData->{'title'};
218     $_->{surname}   = $borrowerData->{'surname'};
219     $_->{firstname} = $borrowerData->{'firstname'};
220     $_->{userid}    = $borrowerData->{'userid'};
221     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
222     $_->{datereviewed} = format_date($_->{datereviewed});
223     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
224                 $_->{your_comment} = 1;
225                 $loggedincommenter = 1;
226         }
227 }
228
229
230 if(C4::Context->preference("ISBD")) {
231         $template->param(ISBD => 1);
232 }
233
234 $template->param(
235     ITEM_RESULTS        => \@items,
236     subscriptionsnumber => $subscriptionsnumber,
237     biblionumber        => $biblionumber,
238     subscriptions       => \@subs,
239     subscriptionsnumber => $subscriptionsnumber,
240     reviews             => $reviews,
241     loggedincommenter   => $loggedincommenter
242 );
243
244 sub isbn_cleanup ($) {
245         my $isbn=shift;
246     ($isbn) = $isbn =~ /([\d-]*[X]*)/;
247     $isbn =~ s/-//g;
248         if (
249                 $isbn =~ /\b(\d{13})\b/ or
250                 $isbn =~ /\b(\d{10})\b/ or 
251                 $isbn =~ /\b(\d{9}X)\b/i
252         ) {
253                 return $1;
254         }
255         return undef;
256 }
257
258 # XISBN Stuff
259 my $xisbn=$dat->{'isbn'};
260 (my $aisbn) = $xisbn =~ /([\d-]*[X]*)/;
261 $aisbn =~ s/-//g;
262 $template->param(amazonisbn => $aisbn);         # FIXME: so it is OK if the ISBN = 'XXXXX' ?
263 my ($clean,$clean2);
264 # these might be overkill, but they are better than the regexp above.
265 if ($clean = isbn_cleanup($xisbn)){
266         $template->param(clean_isbn => $clean);
267 }
268
269 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
270     eval {
271         $template->param(
272             xisbn => $xisbn,
273             XISBNS => get_xisbns($xisbn)
274         );
275     };
276     if ($@) { warn "XISBN Failed $@"; }
277 }
278 # Amazon.com Stuff
279 if ( C4::Context->preference("OPACAmazonEnabled") ) {
280     $template->param( AmazonTld => get_amazon_tld() );
281 }
282 if ( C4::Context->preference("OPACAmazonEnabled") && C4::Context->preference("OPACAmazonSimilarItems") ) {
283     my $similar_products_exist;
284     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
285     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
286     my @services;
287     my $amazon_details = &get_amazon_details( $dat->{isbn}, $record, $marcflavour, \@services );
288
289     if ( $amazon_reviews ) {
290         
291         my $item = $amazon_details->{Items}->{Item}->[0];
292         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
293         for my $one_review ( @$customer_reviews ) {
294             $one_review->{Date} = format_date($one_review->{Date});
295         }
296         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
297         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
298         $template->param( amazon_average_rating    => $average_rating * 20);
299         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
300         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
301     }
302     if ( $amazon_similars ) {
303         my $item = $amazon_details->{Items}->{Item}->[0];
304         my @similar_products;
305         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
306             # do we have any of these isbns in our collection?
307             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
308             # verify that there is at least one similar item
309             if (scalar(@$similar_biblionumbers)){
310                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
311                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
312             }
313         }
314         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
315         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
316     }    
317     
318 }
319
320 # Babelthèque
321 if ( C4::Context->preference("Babeltheque") ) {
322     $template->param( 
323         Babeltheque => 1,
324     );
325 }
326
327 # Shelf Browser Stuff
328 if (C4::Context->preference("OPACShelfBrowser")) {
329     # pick the first itemnumber unless one was selected by the user
330     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
331     $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
332     # find the right cn_sort value for this item
333     my ($starting_cn_sort, $starting_homebranch, $starting_location);
334     my $sth_get_cn_sort = $dbh->prepare("SELECT cn_sort,homebranch,location from items where itemnumber=?");
335     $sth_get_cn_sort->execute($starting_itemnumber);
336     while (my $result = $sth_get_cn_sort->fetchrow_hashref()) {
337         $starting_cn_sort = $result->{'cn_sort'};
338         $starting_homebranch->{code} = $result->{'homebranch'};
339         $starting_homebranch->{description} = $branches->{$result->{'homebranch'}}{branchname};
340         $starting_location->{code} = $result->{'location'};
341         $starting_location->{description} = GetAuthorisedValueDesc('','',   $result->{'location'} ,'','','LOC');
342     
343     }
344     
345     ## List of Previous Items
346     # order by cn_sort, which should include everything we need for ordering purposes (though not
347     # for limits, those need to be handled separately
348     my $sth_shelfbrowse_previous;
349     if (defined $starting_location->{code}) {
350       $sth_shelfbrowse_previous = $dbh->prepare("
351         SELECT *
352         FROM items
353         WHERE
354             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
355             homebranch = ? AND location = ?
356         ORDER BY cn_sort DESC, itemnumber LIMIT 3
357         ");
358       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
359     } else {
360       $sth_shelfbrowse_previous = $dbh->prepare("
361         SELECT *
362         FROM items
363         WHERE
364             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
365             homebranch = ?
366         ORDER BY cn_sort DESC, itemnumber LIMIT 3
367         ");
368       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
369     }
370     my @previous_items;
371     while (my $this_item = $sth_shelfbrowse_previous->fetchrow_hashref()) {
372         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=?");
373         $sth_get_biblio->execute($this_item->{biblionumber});
374         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
375             $this_item->{'title'} = $this_biblio->{'title'};
376             if ($clean2 = isbn_cleanup($this_biblio->{'isbn'})) {
377                 $this_item->{'isbn'} = $clean2;
378             } else { 
379                 $this_item->{'isbn'} = $this_biblio->{'isbn'};
380             }
381         }
382         unshift @previous_items, $this_item;
383     }
384     
385     ## List of Next Items; this also intentionally catches the current item
386     my $sth_shelfbrowse_next;
387     if (defined $starting_location->{code}) {
388       $sth_shelfbrowse_next = $dbh->prepare("
389         SELECT *
390         FROM items
391         WHERE
392             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
393             homebranch = ? AND location = ?
394         ORDER BY cn_sort, itemnumber LIMIT 3
395         ");
396       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
397     } 
398     else {
399       $sth_shelfbrowse_next = $dbh->prepare("
400         SELECT *
401         FROM items
402         WHERE
403             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
404             homebranch = ?
405         ORDER BY cn_sort, itemnumber LIMIT 3
406         ");
407       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
408     }
409     my @next_items;
410     while (my $this_item = $sth_shelfbrowse_next->fetchrow_hashref()) {
411         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=?");
412         $sth_get_biblio->execute($this_item->{biblionumber});
413         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
414             $this_item->{'title'} = $this_biblio->{'title'};
415             if ($clean2 = isbn_cleanup($this_biblio->{'isbn'})) {
416                 $this_item->{'isbn'} = $clean2;
417             } else { 
418                 $this_item->{'isbn'} = $this_biblio->{'isbn'};
419             }
420         }
421         push @next_items, $this_item;
422     }
423
424
425     # alas, these won't auto-vivify, see http://www.perlmonks.org/?node_id=508481
426     my $shelfbrowser_next_itemnumber = $next_items[-1]->{itemnumber} if @next_items;
427     my $shelfbrowser_next_biblionumber = $next_items[-1]->{biblionumber} if @next_items;
428     
429     $template->param(
430         starting_homebranch => $starting_homebranch->{description},
431         starting_location => $starting_location->{description},
432         starting_itemnumber => $starting_itemnumber,
433         shelfbrowser_prev_itemnumber => (@previous_items ? $previous_items[0]->{itemnumber} : 0),
434         shelfbrowser_next_itemnumber => $shelfbrowser_next_itemnumber,
435         shelfbrowser_prev_biblionumber => (@previous_items ? $previous_items[0]->{biblionumber} : 0),
436         shelfbrowser_next_biblionumber => $shelfbrowser_next_biblionumber,
437         PREVIOUS_SHELF_BROWSE => \@previous_items,
438         NEXT_SHELF_BROWSE => \@next_items,
439     );
440 }
441
442 if (C4::Context->preference("BakerTaylorEnabled")) {
443         $template->param(
444                 BakerTaylorEnabled  => 1,
445                 BakerTaylorImageURL => &image_url(),
446                 BakerTaylorLinkURL  => &link_url(),
447                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
448         );
449         my ($bt_user, $bt_pass);
450         if ($clean and
451                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
452                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
453         {
454                 $template->param(
455                 BakerTaylorContentURL   =>
456                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
457                                 $bt_user,$bt_pass,$clean)
458                 );
459         }
460 }
461
462 my $tag_quantity;
463 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
464         $template->param(
465                 TagsEnabled => 1,
466                 TagsShowOnDetail => $tag_quantity,
467                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
468         );
469         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
470                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
471 }
472
473 output_html_with_http_headers $query, $cookie, $template->output;