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