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