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