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