Bug 2047: adding images to arbitrary authorized values
[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/koha-tmpl/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       =
97   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 %itemfields;
125 for my $itm (@items) {
126      $norequests = 0 && $norequests
127        if ( (not $itm->{'wthdrawn'} )
128          || (not $itm->{'itemlost'} )
129          || (not $itm->{'itemnotforloan'} )
130          || ($itm->{'itemnumber'} ) );
131         $itm->{ $itm->{'publictype'} } = 1;
132     $itm->{datedue} = format_date($itm->{datedue});
133     $itm->{datelastseen} = format_date($itm->{datelastseen});
134
135     #get collection code description, too
136         my $ccode= $itm->{'ccode'};
137         $itm->{'ccode'} = $collections->{$ccode} if(defined($collections) && exists($collections->{$ccode}));
138     $itm->{'location_description'} = $shelflocations->{$itm->{'location'} };
139     $itm->{'imageurl'}    = $imgdir."/".$itemtypes->{ $itm->{itype} }->{'imageurl'};     
140     $itm->{'description'} = $itemtypes->{$itemtype}->{'description'};
141         $itemfields{ccode} = 1 if($itm->{ccode});
142         $itemfields{enumchron} = 1 if($itm->{enumchron});
143         $itemfields{copynumber} = 1 if($itm->{copynumber});
144
145      # walk through the item-level authorised values and populate some images
146      my $item_authorised_value_images = C4::Items::get_authorised_value_images( C4::Items::get_item_authorised_values( $itm->{'itemnumber'} ) );
147      # warn( Data::Dumper->Dump( [ $item_authorised_value_images ], [ 'item_authorised_value_images' ] ) );
148
149      if ( $itm->{'itemlost'} ) {
150          my $lostimageinfo = List::Util::first { $_->{'category'} eq 'LOST' } @$item_authorised_value_images;
151          $itm->{'lostimageurl'}   = $lostimageinfo->{ 'imageurl' };
152          $itm->{'lostimagelabel'} = $lostimageinfo->{ 'label' };
153      }
154
155 }
156
157 ## get notes and subjects from MARC record
158 my $dbh              = C4::Context->dbh;
159 my $marcflavour      = C4::Context->preference("marcflavour");
160 my $record           = GetMarcBiblio($biblionumber);
161 my $marcnotesarray   = GetMarcNotes   ($record,$marcflavour);
162 my $marcauthorsarray = GetMarcAuthors ($record,$marcflavour);
163 my $marcsubjctsarray = GetMarcSubjects($record,$marcflavour);
164 my $marcseriesarray  = GetMarcSeries  ($record,$marcflavour);
165 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
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     );
180
181 foreach ( keys %{$dat} ) {
182     $template->param( "$_" => $dat->{$_} . "" );
183 }
184
185 # COinS format FIXME: for books Only
186 my $coins_format;
187 my $fmt = substr $record->leader(), 6,2;
188 my $fmts;
189 $fmts->{'am'} = 'book';
190 $coins_format = $fmts->{$fmt};
191 $template->param(
192         ocoins_format => $coins_format,
193 );
194
195 my $reviews = getreviews( $biblionumber, 1 );
196 my $loggedincommenter;
197 foreach ( @$reviews ) {
198     my $borrowerData   = GetMember($_->{borrowernumber},'borrowernumber');
199     # setting some borrower info into this hash
200     $_->{title}     = $borrowerData->{'title'};
201     $_->{surname}   = $borrowerData->{'surname'};
202     $_->{firstname} = $borrowerData->{'firstname'};
203     $_->{userid}    = $borrowerData->{'userid'};
204     $_->{datereviewed} = format_date($_->{datereviewed});
205     if ($borrowerData->{'borrowernumber'} eq $borrowernumber) {
206                 $_->{your_comment} = 1;
207                 $loggedincommenter = 1;
208         }
209 }
210
211
212 if(C4::Context->preference("ISBD")) {
213         $template->param(ISBD => 1);
214 }
215
216 $template->param(
217     ITEM_RESULTS        => \@items,
218     subscriptionsnumber => $subscriptionsnumber,
219     biblionumber        => $biblionumber,
220     subscriptions       => \@subs,
221     subscriptionsnumber => $subscriptionsnumber,
222     reviews             => $reviews,
223     loggedincommenter   => $loggedincommenter
224 );
225
226 # XISBN Stuff
227 my $xisbn=$dat->{'isbn'};
228 $xisbn =~ /(\d*[X]*)/;
229 $template->param(amazonisbn => $1);             # FIXME: so it is OK if the ISBN = 'XXXXX' ?
230 my ($clean, $amazonisbn);
231 $amazonisbn = $1;
232 # these might be overkill, but they are better than the regexp above.
233 if (
234         $amazonisbn =~ /\b(\d{13})\b/ or
235         $amazonisbn =~ /\b(\d{10})\b/ or 
236         $amazonisbn =~ /\b(\d{9}X)\b/i
237 ) {
238         $clean = $1;
239         $template->param(clean_isbn => $1);
240 }
241
242 if (C4::Context->preference("OPACFRBRizeEditions")==1) {
243     eval {
244         $template->param(
245             xisbn => $xisbn,
246             XISBNS => get_xisbns($xisbn)
247         );
248     };
249     if ($@) { warn "XISBN Failed $@"; }
250 }
251 # Amazon.com Stuff
252 if ( C4::Context->preference("OPACAmazonContent") == 1 ) {
253     my $similar_products_exist;
254     my $amazon_details = &get_amazon_details( $xisbn );
255     my $item_attributes = \%{$amazon_details->{Items}->{Item}->{ItemAttributes}};
256     my $customer_reviews = \@{$amazon_details->{Items}->{Item}->{CustomerReviews}->{Review}};
257     for my $one_review (@$customer_reviews) {
258         $one_review->{Date} = format_date($one_review->{Date});
259     }
260     my @similar_products;
261     for my $similar_product (@{$amazon_details->{Items}->{Item}->{SimilarProducts}->{SimilarProduct}}) {
262         # do we have any of these isbns in our collection?
263         my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
264         # verify that there is at least one similar item
265         $similar_products_exist++ if ${@$similar_biblionumbers}[0];
266         push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
267     }
268     my $editorial_reviews = \@{$amazon_details->{Items}->{Item}->{EditorialReviews}->{EditorialReview}};
269     my $average_rating = $amazon_details->{Items}->{Item}->{CustomerReviews}->{AverageRating};
270     $template->param( OPACAmazonSimilarItems => $similar_products_exist );
271     $template->param( amazon_average_rating => $average_rating * 20);
272     $template->param( AMAZON_CUSTOMER_REVIEWS    => $customer_reviews );
273     $template->param( AMAZON_SIMILAR_PRODUCTS => \@similar_products );
274     $template->param( AMAZON_EDITORIAL_REVIEWS    => $editorial_reviews );
275 }
276 # Shelf Browser Stuff
277 if (C4::Context->preference("OPACShelfBrowser")) {
278 # pick the first itemnumber unless one was selected by the user
279 my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); # || $items[0]->{itemnumber};
280 $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber;
281 # find the right cn_sort value for this item
282 my ($starting_cn_sort, $starting_homebranch, $starting_location);
283 my $sth_get_cn_sort = $dbh->prepare("SELECT cn_sort,homebranch,location from items where itemnumber=?");
284 $sth_get_cn_sort->execute($starting_itemnumber);
285 my $branches = GetBranches();
286 while (my $result = $sth_get_cn_sort->fetchrow_hashref()) {
287     $starting_cn_sort = $result->{'cn_sort'};
288     $starting_homebranch->{code} = $result->{'homebranch'};
289     $starting_homebranch->{description} = $branches->{$result->{'homebranch'}}{branchname};
290     $starting_location->{code} = $result->{'location'};
291     $starting_location->{description} = GetAuthorisedValueDesc('','',   $result->{'location'} ,'','','LOC');
292
293 }
294
295 ## List of Previous Items
296 # order by cn_sort, which should include everything we need for ordering purposes (though not
297 # for limits, those need to be handled separately
298 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");
299 $sth_shelfbrowse_previous->execute($starting_cn_sort.$starting_itemnumber, $starting_homebranch->{code}, $starting_location->{code});
300 my @previous_items;
301 while (my $this_item = $sth_shelfbrowse_previous->fetchrow_hashref()) {
302     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=?");
303     $sth_get_biblio->execute($this_item->{biblionumber});
304     while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
305         $this_item->{'title'} = $this_biblio->{'title'};
306         $this_item->{'isbn'} = $this_biblio->{'isbn'};
307     }
308     unshift @previous_items, $this_item;
309 }
310 my $throwaway = pop @previous_items;
311 ## List of Next Items
312 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");
313 $sth_shelfbrowse_next->execute($starting_cn_sort.$starting_itemnumber, $starting_homebranch->{code}, $starting_location->{code});
314 my @next_items;
315 while (my $this_item = $sth_shelfbrowse_next->fetchrow_hashref()) {
316     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=?");
317     $sth_get_biblio->execute($this_item->{biblionumber});
318     while (my $this_biblio = $sth_get_biblio->fetchrow_hashref()) {
319         $this_item->{'title'} = $this_biblio->{'title'};
320         $this_item->{'isbn'} = $this_biblio->{'isbn'};
321     }
322     push @next_items, $this_item;
323 }
324
325 # alas, these won't auto-vivify, see http://www.perlmonks.org/?node_id=508481
326 my $shelfbrowser_next_itemnumber = $next_items[-1]->{itemnumber} if @next_items;
327 my $shelfbrowser_next_biblionumber = $next_items[-1]->{biblionumber} if @next_items;
328
329 $template->param(
330     starting_homebranch => $starting_homebranch->{description},
331     starting_location => $starting_location->{description},
332     shelfbrowser_prev_itemnumber => $previous_items[0]->{itemnumber},
333     shelfbrowser_next_itemnumber => $shelfbrowser_next_itemnumber,
334     shelfbrowser_prev_biblionumber => $previous_items[0]->{biblionumber},
335     shelfbrowser_next_biblionumber => $shelfbrowser_next_biblionumber,
336     PREVIOUS_SHELF_BROWSE => \@previous_items,
337     NEXT_SHELF_BROWSE => \@next_items,
338 );
339 }
340
341 if (C4::Context->preference("BakerTaylorEnabled")) {
342         $template->param(
343                 BakerTaylorEnabled  => 1,
344                 BakerTaylorImageURL => &image_url(),
345                 BakerTaylorLinkURL  => &link_url(),
346                 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
347         );
348         my ($bt_user, $bt_pass);
349         if ($clean and
350                 $bt_user = C4::Context->preference('BakerTaylorUsername') and
351                 $bt_pass = C4::Context->preference('BakerTaylorPassword')    )
352         {
353                 $template->param(
354                 BakerTaylorContentURL   =>
355                 sprintf("http://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y",
356                                 $bt_user,$bt_pass,$clean)
357                 );
358         }
359 }
360
361 my $tag_quantity;
362 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
363         $template->param(
364                 TagsEnabled => 1,
365                 TagsShowOnDetail => $tag_quantity,
366                 TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail')
367         );
368         $template->param(TagLoop => get_tags({biblionumber=>$biblionumber,
369                                                                 'sort'=>'-weight', limit=>$tag_quantity}));
370 }
371
372 output_html_with_http_headers $query, $cookie, $template->output;