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