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