(bug #3042) Changing XSLT sysprefs to take filename
[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 if ( ! $record ) {
66     print $query->redirect("/cgi-bin/koha/errors/404.pl");
67     exit;
68 }
69 $template->param( biblionumber => $biblionumber );
70 # XSLT processing of some stuff
71 if (C4::Context->preference("XSLTDetailsDisplay") ) {
72     $template->param(
73         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, C4::Context->preference("XSLTDetailsDisplay")) );
74 }
75
76 # change back when ive fixed request.pl
77 my @all_items = &GetItemsInfo( $biblionumber, 'opac' );
78 my @items;
79 @items = @all_items unless C4::Context->preference('hidelostitems');
80
81 if (C4::Context->preference('hidelostitems')) {
82     # Hide host items
83     for my $itm (@all_items) {
84         push @items, $itm unless $itm->{itemlost};
85     }
86 }
87 my $dat = &GetBiblioData($biblionumber);
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 $normalized_isbn  = GetNormalizedISBN($dat->{isbn},$record,$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                      normalized_oclc         => GetNormalizedOCLCNumber($record,$marcflavour),
189                      normalized_upc          => GetNormalizedUPC       ($record,$marcflavour),
190                      normalized_isbn         => $normalized_isbn,
191                      MARCNOTES               => $marcnotesarray,
192                      MARCSUBJCTS             => $marcsubjctsarray,
193                      MARCAUTHORS             => $marcauthorsarray,
194                      MARCSERIES              => $marcseriesarray,
195                      MARCURLS                => $marcurlsarray,
196                      norequests              => $norequests,
197                      RequestOnOpac           => C4::Context->preference("RequestOnOpac"),
198                      itemdata_ccode          => $itemfields{ccode},
199                      itemdata_enumchron      => $itemfields{enumchron},
200                      itemdata_uri            => $itemfields{uri},
201                      itemdata_copynumber     => $itemfields{copynumber},
202                      itemdata_itemnotes          => $itemfields{itemnotes},
203                      authorised_value_images => $biblio_authorised_value_images,
204                      subtitle                => $subtitle,
205     );
206
207 foreach ( keys %{$dat} ) {
208     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
209 }
210
211 # COinS format FIXME: for books Only
212 $template->param(
213     ocoins => GetCOinSBiblio($biblionumber),
214 );
215
216 my $reviews = getreviews( $biblionumber, 1 );
217 my $loggedincommenter;
218 foreach ( @$reviews ) {
219     my $borrowerData   = GetMember($_->{borrowernumber},'borrowernumber');
220     # setting some borrower info into this hash
221     $_->{title}     = $borrowerData->{'title'};
222     $_->{surname}   = $borrowerData->{'surname'};
223     $_->{firstname} = $borrowerData->{'firstname'};
224     $_->{userid}    = $borrowerData->{'userid'};
225     $_->{cardnumber}    = $borrowerData->{'cardnumber'};
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
249 # XISBN Stuff
250
251 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
252     eval {
253         $template->param(
254             XISBNS => get_xisbns($normalized_isbn)
255         );
256     };
257     if ($@) { warn "XISBN Failed $@"; }
258 }
259 # Amazon.com Stuff
260 if ( C4::Context->preference("OPACAmazonEnabled") ) {
261     $template->param( AmazonTld => get_amazon_tld() );
262 }
263 if ( C4::Context->preference("OPACAmazonEnabled") && C4::Context->preference("OPACAmazonSimilarItems") ) {
264     my $similar_products_exist;
265     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
266     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
267     my @services;
268     my $amazon_details = &get_amazon_details( $normalized_isbn, $record, $marcflavour, \@services );
269
270     if ( $amazon_reviews ) {
271         
272         my $item = $amazon_details->{Items}->{Item}->[0];
273         my $customer_reviews = \@{ $item->{CustomerReviews}->{Review} };
274         for my $one_review ( @$customer_reviews ) {
275             $one_review->{Date} = format_date($one_review->{Date});
276         }
277         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
278         my $average_rating = $item->{CustomerReviews}->{AverageRating} || 0;
279         $template->param( amazon_average_rating    => $average_rating * 20);
280         $template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews );
281         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews );
282     }
283     if ( $amazon_similars ) {
284         my $item = $amazon_details->{Items}->{Item}->[0];
285         my @similar_products;
286         for my $similar_product (@{ $item->{SimilarProducts}->{SimilarProduct} }) {
287             # do we have any of these isbns in our collection?
288             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
289             # verify that there is at least one similar item
290             if (scalar(@$similar_biblionumbers)){
291                 $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
292                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
293             }
294         }
295         $template->param( OPACAmazonSimilarItems => $similar_products_exist );
296         $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
297     }    
298     
299 }
300
301 # Babelthèque
302 if ( C4::Context->preference("Babeltheque") ) {
303     $template->param( 
304         Babeltheque => 1,
305     );
306 }
307
308 # Shelf Browser Stuff
309 if (C4::Context->preference("OPACShelfBrowser")) {
310     # pick the first itemnumber unless one was selected by the user
311     my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
312     $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
313     # find the right cn_sort value for this item
314     my ($starting_cn_sort, $starting_homebranch, $starting_location);
315     my $sth_get_cn_sort = $dbh->prepare("SELECT cn_sort,homebranch,location from items where itemnumber=?");
316     $sth_get_cn_sort->execute($starting_itemnumber);
317     while (my $result = $sth_get_cn_sort->fetchrow_hashref()) {
318         $starting_cn_sort = $result->{'cn_sort'};
319         $starting_homebranch->{code} = $result->{'homebranch'};
320         $starting_homebranch->{description} = $branches->{$result->{'homebranch'}}{branchname};
321         $starting_location->{code} = $result->{'location'};
322         $starting_location->{description} = GetAuthorisedValueDesc('','',   $result->{'location'} ,'','','LOC');
323     
324     }
325     
326     ## List of Previous Items
327     # order by cn_sort, which should include everything we need for ordering purposes (though not
328     # for limits, those need to be handled separately
329     my $sth_shelfbrowse_previous;
330     if (defined $starting_location->{code}) {
331       $sth_shelfbrowse_previous = $dbh->prepare("
332         SELECT *
333         FROM items
334         WHERE
335             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
336             homebranch = ? AND location = ?
337         ORDER BY cn_sort DESC, itemnumber LIMIT 3
338         ");
339       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
340     } else {
341       $sth_shelfbrowse_previous = $dbh->prepare("
342         SELECT *
343         FROM items
344         WHERE
345             ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) AND
346             homebranch = ?
347         ORDER BY cn_sort DESC, itemnumber LIMIT 3
348         ");
349       $sth_shelfbrowse_previous->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
350     }
351     my @previous_items;
352     while (my $this_item = $sth_shelfbrowse_previous->fetchrow_hashref()) {
353         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=?");
354         $sth_get_biblio->execute($this_item->{biblionumber});
355         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
356             $this_item->{'title'} = $this_biblio->{'title'};
357         }
358         unshift @previous_items, $this_item;
359     }
360     
361     ## List of Next Items; this also intentionally catches the current item
362     my $sth_shelfbrowse_next;
363     if (defined $starting_location->{code}) {
364       $sth_shelfbrowse_next = $dbh->prepare("
365         SELECT *
366         FROM items
367         WHERE
368             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
369             homebranch = ? AND location = ?
370         ORDER BY cn_sort, itemnumber LIMIT 3
371         ");
372       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code}, $starting_location->{code});
373     } 
374     else {
375       $sth_shelfbrowse_next = $dbh->prepare("
376         SELECT *
377         FROM items
378         WHERE
379             ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) AND
380             homebranch = ?
381         ORDER BY cn_sort, itemnumber LIMIT 3
382         ");
383       $sth_shelfbrowse_next->execute($starting_cn_sort, $starting_itemnumber, $starting_cn_sort, $starting_homebranch->{code});
384     }
385     my @next_items;
386     while (my $this_item = $sth_shelfbrowse_next->fetchrow_hashref()) {
387         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=?");
388         $sth_get_biblio->execute($this_item->{biblionumber});
389         while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
390             $this_item->{'title'} = $this_biblio->{'title'};
391         }
392         push @next_items, $this_item;
393     }
394
395
396     # alas, these won't auto-vivify, see http://www.perlmonks.org/?node_id=508481
397     my $shelfbrowser_next_itemnumber = $next_items[-1]->{itemnumber} if @next_items;
398     my $shelfbrowser_next_biblionumber = $next_items[-1]->{biblionumber} if @next_items;
399     
400     $template->param(
401         starting_homebranch => $starting_homebranch->{description},
402         starting_location => $starting_location->{description},
403         starting_itemnumber => $starting_itemnumber,
404         shelfbrowser_prev_itemnumber => (@previous_items ? $previous_items[0]->{itemnumber} : 0),
405         shelfbrowser_next_itemnumber => $shelfbrowser_next_itemnumber,
406         shelfbrowser_prev_biblionumber => (@previous_items ? $previous_items[0]->{biblionumber} : 0),
407         shelfbrowser_next_biblionumber => $shelfbrowser_next_biblionumber,
408         PREVIOUS_SHELF_BROWSE => \@previous_items,
409         NEXT_SHELF_BROWSE => \@next_items,
410     );
411 }
412
413 if (C4::Context->preference("BakerTaylorEnabled")) {
414         $template->param(
415                 BakerTaylorEnabled  => 1,
416                 BakerTaylorImageURL => &image_url(),
417                 BakerTaylorLinkURL  => &link_url(),
418                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
419         );
420         my ($bt_user, $bt_pass);
421         if ($normalized_isbn and
422                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
423                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
424         {
425                 $template->param(
426                 BakerTaylorContentURL   =>
427                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
428                                 $bt_user,$bt_pass,$normalized_isbn)
429                 );
430         }
431 }
432
433 my $tag_quantity;
434 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
435         $template->param(
436                 TagsEnabled => 1,
437                 TagsShowOnDetail => $tag_quantity,
438                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
439         );
440         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
441                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
442 }
443
444 output_html_with_http_headers $query, $cookie, $template->output;