Bug 1633 localcoverimages, updatedatabase & kohaversion for pushing
[koha.git] / catalogue / detail.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18
19 use strict;
20 use warnings;
21
22 use CGI;
23 use C4::Auth;
24 use C4::Dates qw/format_date/;
25 use C4::Koha;
26 use C4::Serials;    #uses getsubscriptionfrom biblionumber
27 use C4::Output;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Circulation;
31 use C4::Branch;
32 use C4::Reserves;
33 use C4::Members; # to use GetMember
34 use C4::Serials;
35 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
36 use C4::External::Amazon;
37 use C4::Search;         # enabled_staff_search_views
38 use C4::VirtualShelves;
39 use C4::XSLT;
40 use C4::Images;
41
42 # use Smart::Comments;
43
44 my $query = CGI->new();
45
46 my $analyze = $query->param('analyze');
47
48 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
49     {
50     template_name   =>  'catalogue/detail.tmpl',
51         query           => $query,
52         type            => "intranet",
53         authnotrequired => 0,
54         flagsrequired   => { catalogue => 1 },
55     }
56 );
57
58 my $biblionumber = $query->param('biblionumber');
59 my $record       = GetMarcBiblio($biblionumber);
60
61 if ( not defined $record ) {
62     # biblionumber invalid -> report and exit
63     $template->param( unknownbiblionumber => 1,
64                       biblionumber => $biblionumber );
65     output_html_with_http_headers $query, $cookie, $template->output;
66     exit;
67 }
68
69 if($query->cookie("holdfor")){ 
70     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
71     $template->param(
72         holdfor => $query->cookie("holdfor"),
73         holdfor_surname => $holdfor_patron->{'surname'},
74         holdfor_firstname => $holdfor_patron->{'firstname'},
75         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
76     );
77 }
78
79 my $fw           = GetFrameworkCode($biblionumber);
80 my $showallitems = $query->param('showallitems');
81 my $marcflavour  = C4::Context->preference("marcflavour");
82
83 # XSLT processing of some stuff
84 if (C4::Context->preference("XSLTDetailsDisplay") ) {
85     $template->param('XSLTDetailsDisplay' =>'1',
86         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, 'Detail','intranet') );
87 }
88
89 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
90 $template->param( ocoins => GetCOinSBiblio($record) );
91
92 # some useful variables for enhanced content;
93 # in each case, we're grabbing the first value we find in
94 # the record and normalizing it
95 my $upc = GetNormalizedUPC($record,$marcflavour);
96 my $ean = GetNormalizedEAN($record,$marcflavour);
97 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
98 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
99
100 $template->param(
101     normalized_upc => $upc,
102     normalized_ean => $ean,
103     normalized_oclc => $oclc,
104     normalized_isbn => $isbn,
105 );
106
107 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
108 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
109 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
110 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
111 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
112 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
113 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
114 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
115
116 # Get Branches, Itemtypes and Locations
117 my $branches = GetBranches();
118 my $itemtypes = GetItemTypes();
119 my $dbh = C4::Context->dbh;
120
121 my @all_items = GetItemsInfo( $biblionumber );
122 my @items;
123 for my $itm (@all_items) {
124     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
125 }
126
127 # flag indicating existence of at least one item linked via a host record
128 my $hostrecords;
129 # adding items linked via host biblios
130 my @hostitems = GetHostItemsInfo($record);
131 if (@hostitems){
132         $hostrecords =1;
133         push (@items,@hostitems);
134 }
135
136 my $dat = &GetBiblioData($biblionumber);
137
138 # get count of holds
139 my ( $holdcount, $holds ) = GetReservesFromBiblionumber($biblionumber,1);
140
141 #coping with subscriptions
142 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
143 my @subscriptions       = GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
144 my @subs;
145
146 foreach my $subscription (@subscriptions) {
147     my %cell;
148         my $serials_to_display;
149     $cell{subscriptionid}    = $subscription->{subscriptionid};
150     $cell{subscriptionnotes} = $subscription->{notes};
151     $cell{branchcode}        = $subscription->{branchcode};
152     $cell{branchname}        = GetBranchName($subscription->{branchcode});
153     $cell{hasalert}          = $subscription->{hasalert};
154     #get the three latest serials.
155         $serials_to_display = $subscription->{staffdisplaycount};
156         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
157         $cell{staffdisplaycount} = $serials_to_display;
158     $cell{latestserials} =
159       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
160     push @subs, \%cell;
161 }
162
163 if ( defined $dat->{'itemtype'} ) {
164     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
165 }
166
167 $dat->{'count'} = scalar @all_items + @hostitems;
168 $dat->{'showncount'} = scalar @items + @hostitems;
169 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
170
171 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
172 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
173 my (@itemloop, %itemfields);
174 my $norequests = 1;
175 my $authvalcode_items_itemlost = GetAuthValCode('items.itemlost',$fw);
176 my $authvalcode_items_damaged  = GetAuthValCode('items.damaged', $fw);
177
178 my $analytics_flag;
179 my $materials_flag; # set this if the items have anything in the materials field
180 foreach my $item (@items) {
181
182     $item->{homebranch}        = GetBranchName($item->{homebranch});
183
184     # can place holds defaults to yes
185     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
186
187     # format some item fields for display
188     if ( defined $item->{'publictype'} ) {
189         $item->{ $item->{'publictype'} } = 1;
190     }
191     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
192                                                : '';
193
194         foreach (qw(datedue datelastseen onloan)) {
195                 $item->{$_} = format_date($item->{$_});
196         }
197     # item damaged, lost, withdrawn loops
198     $item->{itemlostloop} = GetAuthorisedValues($authvalcode_items_itemlost, $item->{itemlost}) if $authvalcode_items_itemlost;
199     if ($item->{damaged}) {
200         $item->{itemdamagedloop} = GetAuthorisedValues($authvalcode_items_damaged, $item->{damaged}) if $authvalcode_items_damaged;
201     }
202     #get shelf location and collection code description if they are authorised value.
203     my $shelfcode = $item->{'location'};
204     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
205     my $ccode = $item->{'ccode'};
206     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
207     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
208         $itemfields{$_} = 1 if ( $item->{$_} );
209     }
210
211     # checking for holds
212     my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($item->{itemnumber});
213     my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
214     
215     if (C4::Context->preference('HidePatronName')){
216         $item->{'hidepatronname'} = 1;
217     }
218
219     if ( defined $reservedate ) {
220         $item->{backgroundcolor} = 'reserved';
221         $item->{reservedate}     = format_date($reservedate);
222         $item->{ReservedForBorrowernumber}     = $reservedfor;
223         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
224         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
225         $item->{ExpectedAtLibrary}      = $branches->{$expectedAt}{branchname};
226         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
227     }
228
229         # Check the transit status
230     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
231     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
232         $item->{transfertwhen} = format_date($transfertwhen);
233         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
234         $item->{transfertto}   = $branches->{$transfertto}{branchname};
235         $item->{nocancel} = 1;
236     }
237
238     # FIXME: move this to a pm, check waiting status for holds
239     my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
240     $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
241     while (my $wait_hashref = $sth2->fetchrow_hashref) {
242         $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
243     }
244
245     # item has a host number if its biblio number does not match the current bib
246     if ($item->{biblionumber} ne $biblionumber){
247         $item->{hostbiblionumber} = $item->{biblionumber};
248         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
249     }
250         
251         #count if item is used in analytical bibliorecords
252         my $countanalytics= GetAnalyticsCount($item->{itemnumber});
253         if ($countanalytics > 0){
254                 $analytics_flag=1;
255                 $item->{countanalytics} = $countanalytics;
256         }
257     if ($item->{'materials'} ne ''){
258         $materials_flag = 1;
259     }
260     push @itemloop, $item;
261 }
262
263 $template->param( norequests => $norequests );
264 $template->param(
265         MARCNOTES   => $marcnotesarray,
266         MARCSUBJCTS => $marcsubjctsarray,
267         MARCAUTHORS => $marcauthorsarray,
268         MARCSERIES  => $marcseriesarray,
269         MARCURLS => $marcurlsarray,
270     MARCISBNS => $marcisbnsarray,
271         MARCHOSTS => $marchostsarray,
272         subtitle    => $subtitle,
273         itemdata_ccode      => $itemfields{ccode},
274         itemdata_enumchron  => $itemfields{enumchron},
275         itemdata_uri        => $itemfields{uri},
276         itemdata_copynumber => $itemfields{copynumber},
277         volinfo                         => $itemfields{enumchron},
278     itemdata_itemnotes  => $itemfields{itemnotes},
279         z3950_search_params     => C4::Search::z3950_search_args($dat),
280     holdcount           => $holdcount,
281         hostrecords         => $hostrecords,
282         analytics_flag  => $analytics_flag,
283         C4::Search::enabled_staff_search_views,
284         materials       => $materials_flag,
285 );
286
287 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
288     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
289     my $subfields = substr $fieldspec, 3;
290     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
291     my @alternateholdingsinfo = ();
292     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
293
294     for my $field (@holdingsfields) {
295         my %holding = ( holding => '' );
296         my $havesubfield = 0;
297         for my $subfield ($field->subfields()) {
298             if ((index $subfields, $$subfield[0]) >= 0) {
299                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
300                 $holding{'holding'} .= $$subfield[1];
301                 $havesubfield++;
302             }
303         }
304         if ($havesubfield) {
305             push(@alternateholdingsinfo, \%holding);
306         }
307     }
308
309     $template->param(
310         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
311         );
312 }
313
314 my @results = ( $dat, );
315 foreach ( keys %{$dat} ) {
316     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
317 }
318
319 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
320 # method query not found?!?!
321
322 $template->param(
323     itemloop        => \@itemloop,
324     biblionumber        => $biblionumber,
325     ($analyze? 'analyze':'detailview') =>1,
326     subscriptions       => \@subs,
327     subscriptionsnumber => $subscriptionsnumber,
328     subscriptiontitle   => $dat->{title},
329 );
330
331 # $debug and $template->param(debug_display => 1);
332
333 # Lists
334
335 if (C4::Context->preference("virtualshelves") ) {
336    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
337 }
338
339 # XISBN Stuff
340 if (C4::Context->preference("FRBRizeEditions")==1) {
341     eval {
342         $template->param(
343             XISBNS => get_xisbns($isbn)
344         );
345     };
346     if ($@) { warn "XISBN Failed $@"; }
347 }
348 if ( C4::Context->preference("AmazonEnabled") == 1 ) {
349     $template->param( AmazonTld => get_amazon_tld() );
350     my $amazon_reviews  = C4::Context->preference("AmazonReviews");
351     my $amazon_similars = C4::Context->preference("AmazonSimilarItems");
352     my @services;
353     if ( $amazon_reviews ) {
354         $template->param( AmazonReviews => 1 );
355         push( @services, 'EditorialReview' );
356     }
357     if ( $amazon_similars ) {
358         $template->param( AmazonSimilarItems => 1 );
359         push( @services, 'Similarities' );
360     }
361     my $amazon_details = &get_amazon_details( $isbn, $record, $marcflavour, \@services );
362     if ( $amazon_similars ) {
363         my $similar_products_exist;
364         my @similar_products;
365         for my $similar_product (@{$amazon_details->{Items}->{Item}->[0]->{SimilarProducts}->{SimilarProduct}}) {
366             # do we have any of these isbns in our collection?
367             my $similar_biblionumbers = get_biblionumber_from_isbn($similar_product->{ASIN});
368             # verify that there is at least one similar item
369                     if (scalar(@$similar_biblionumbers)){            
370                             $similar_products_exist++ if ($similar_biblionumbers && $similar_biblionumbers->[0]);
371                 push @similar_products, +{ similar_biblionumbers => $similar_biblionumbers, title => $similar_product->{Title}, ASIN => $similar_product->{ASIN}  };
372             }
373         }
374         $template->param( AmazonSimilarItems       => $similar_products_exist );
375         $template->param( AMAZON_SIMILAR_PRODUCTS  => \@similar_products      );
376     }
377     if ( $amazon_reviews ) {
378         my $item = $amazon_details->{Items}->{Item}->[0];
379         my $editorial_reviews = \@{ $item->{EditorialReviews}->{EditorialReview} };
380         #my $customer_reviews  = \@{$amazon_details->{Items}->{Item}->[0]->{CustomerReviews}->{Review}};
381         #my $average_rating = $amazon_details->{Items}->{Item}->[0]->{CustomerReviews}->{AverageRating} || 0;
382         #$template->param( amazon_average_rating    => $average_rating * 20    );
383         #$template->param( AMAZON_CUSTOMER_REVIEWS  => $customer_reviews       );
384         $template->param( AMAZON_EDITORIAL_REVIEWS => $editorial_reviews      );
385     }
386 }
387
388 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
389     my @images = ListImagesForBiblio($biblionumber);
390     $template->{VARS}->{localimages} = \@images;
391 }
392
393 # Get OPAC URL
394 if (C4::Context->preference('OPACBaseURL')){
395      $template->param( OpacUrl => C4::Context->preference('OPACBaseURL') );
396 }
397
398 output_html_with_http_headers $query, $cookie, $template->output;