bug 8215: (followup) rename GetItemReservesInfo
[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::Tags qw(get_tags);
39 use C4::VirtualShelves;
40 use C4::XSLT;
41 use C4::Images;
42 use Koha::DateUtils;
43 use C4::HTML5Media;
44 use C4::CourseReserves qw(GetItemCourseReservesInfo);
45
46 # use Smart::Comments;
47
48 my $query = CGI->new();
49
50 my $analyze = $query->param('analyze');
51
52 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
53     {
54     template_name   =>  'catalogue/detail.tmpl',
55         query           => $query,
56         type            => "intranet",
57         authnotrequired => 0,
58         flagsrequired   => { catalogue => 1 },
59     }
60 );
61
62 my $biblionumber = $query->param('biblionumber');
63 my $record       = GetMarcBiblio($biblionumber);
64
65 if ( not defined $record ) {
66     # biblionumber invalid -> report and exit
67     $template->param( unknownbiblionumber => 1,
68                       biblionumber => $biblionumber );
69     output_html_with_http_headers $query, $cookie, $template->output;
70     exit;
71 }
72
73 if($query->cookie("holdfor")){ 
74     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
75     $template->param(
76         holdfor => $query->cookie("holdfor"),
77         holdfor_surname => $holdfor_patron->{'surname'},
78         holdfor_firstname => $holdfor_patron->{'firstname'},
79         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
80     );
81 }
82
83 my $fw           = GetFrameworkCode($biblionumber);
84 my $showallitems = $query->param('showallitems');
85 my $marcflavour  = C4::Context->preference("marcflavour");
86
87 # XSLT processing of some stuff
88 if (C4::Context->preference("XSLTDetailsDisplay") ) {
89     $template->param('XSLTDetailsDisplay' =>'1',
90         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, "XSLTDetailsDisplay") );
91 }
92
93 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
94 $template->param( ocoins => GetCOinSBiblio($record) );
95
96 # some useful variables for enhanced content;
97 # in each case, we're grabbing the first value we find in
98 # the record and normalizing it
99 my $upc = GetNormalizedUPC($record,$marcflavour);
100 my $ean = GetNormalizedEAN($record,$marcflavour);
101 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
102 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
103
104 $template->param(
105     normalized_upc => $upc,
106     normalized_ean => $ean,
107     normalized_oclc => $oclc,
108     normalized_isbn => $isbn,
109 );
110
111 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
112 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
113 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
114 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
115 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
116 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
117 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
118 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
119
120 # Get Branches, Itemtypes and Locations
121 my $branches = GetBranches();
122 my $itemtypes = GetItemTypes();
123 my $dbh = C4::Context->dbh;
124
125 my @all_items = GetItemsInfo( $biblionumber );
126 my @items;
127 for my $itm (@all_items) {
128     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
129 }
130
131 # flag indicating existence of at least one item linked via a host record
132 my $hostrecords;
133 # adding items linked via host biblios
134 my @hostitems = GetHostItemsInfo($record);
135 if (@hostitems){
136         $hostrecords =1;
137         push (@items,@hostitems);
138 }
139
140 my $dat = &GetBiblioData($biblionumber);
141
142 #coping with subscriptions
143 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
144 my @subscriptions       = GetSubscriptions( $dat->{title}, $dat->{issn}, undef, $biblionumber );
145 my @subs;
146
147 foreach my $subscription (@subscriptions) {
148     my %cell;
149         my $serials_to_display;
150     $cell{subscriptionid}    = $subscription->{subscriptionid};
151     $cell{subscriptionnotes} = $subscription->{internalnotes};
152     $cell{missinglist}       = $subscription->{missinglist};
153     $cell{librariannote}     = $subscription->{librariannote};
154     $cell{branchcode}        = $subscription->{branchcode};
155     $cell{branchname}        = GetBranchName($subscription->{branchcode});
156     $cell{hasalert}          = $subscription->{hasalert};
157     $cell{callnumber}        = $subscription->{callnumber};
158     $cell{closed}            = $subscription->{closed};
159     #get the three latest serials.
160         $serials_to_display = $subscription->{staffdisplaycount};
161         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
162         $cell{staffdisplaycount} = $serials_to_display;
163     $cell{latestserials} =
164       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
165     push @subs, \%cell;
166 }
167
168 if ( defined $dat->{'itemtype'} ) {
169     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
170 }
171
172 $dat->{'count'} = scalar @all_items + @hostitems;
173 $dat->{'showncount'} = scalar @items + @hostitems;
174 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
175
176 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
177 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
178 my $copynumbers    = GetKohaAuthorisedValues('items.copynumber', $fw);
179 my (@itemloop, @otheritemloop, %itemfields);
180 my $norequests = 1;
181 my $authvalcode_items_itemlost = GetAuthValCode('items.itemlost',$fw);
182 my $authvalcode_items_damaged  = GetAuthValCode('items.damaged', $fw);
183
184 my $analytics_flag;
185 my $materials_flag; # set this if the items have anything in the materials field
186 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
187 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
188     $template->param(SeparateHoldings => 1);
189 }
190 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
191 foreach my $item (@items) {
192     my $itembranchcode = $item->{$separatebranch};
193     $item->{homebranch}        = GetBranchName($item->{homebranch});
194
195     # can place holds defaults to yes
196     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
197
198     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
199                                                : '';
200
201         foreach (qw(datelastseen onloan)) {
202                 $item->{$_} = format_date($item->{$_});
203     }
204     $item->{datedue} = format_sqldatetime($item->{datedue});
205     # item damaged, lost, withdrawn loops
206     $item->{itemlostloop} = GetAuthorisedValues($authvalcode_items_itemlost, $item->{itemlost}) if $authvalcode_items_itemlost;
207     if ($item->{damaged}) {
208         $item->{itemdamagedloop} = GetAuthorisedValues($authvalcode_items_damaged, $item->{damaged}) if $authvalcode_items_damaged;
209     }
210     #get shelf location and collection code description if they are authorised value.
211     # same thing for copy number
212     my $shelfcode = $item->{'location'};
213     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
214     my $ccode = $item->{'ccode'};
215     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
216     my $copynumber = $item->{'copynumber'};
217     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
218     foreach (qw(ccode enumchron copynumber itemnotes uri)) {
219         $itemfields{$_} = 1 if ( $item->{$_} );
220     }
221
222     # checking for holds
223     my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($item->{itemnumber});
224     my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
225     
226     if (C4::Context->preference('HidePatronName')){
227         $item->{'hidepatronname'} = 1;
228     }
229
230     if ( defined $reservedate ) {
231         $item->{backgroundcolor} = 'reserved';
232         $item->{reservedate}     = format_date($reservedate);
233         $item->{ReservedForBorrowernumber}     = $reservedfor;
234         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
235         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
236         $item->{ExpectedAtLibrary}      = $branches->{$expectedAt}{branchname};
237         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
238     }
239
240         # Check the transit status
241     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
242     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
243         $item->{transfertwhen} = format_date($transfertwhen);
244         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
245         $item->{transfertto}   = $branches->{$transfertto}{branchname};
246         $item->{nocancel} = 1;
247     }
248
249     # FIXME: move this to a pm, check waiting status for holds
250     my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
251     $sth2->execute($item->{ReservedForBorrowernumber},$item->{itemnumber});
252     while (my $wait_hashref = $sth2->fetchrow_hashref) {
253         $item->{waitingdate} = format_date($wait_hashref->{waitingdate});
254     }
255
256     # item has a host number if its biblio number does not match the current bib
257     if ($item->{biblionumber} ne $biblionumber){
258         $item->{hostbiblionumber} = $item->{biblionumber};
259         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
260     }
261         
262     #count if item is used in analytical bibliorecords
263     my $countanalytics= GetAnalyticsCount($item->{itemnumber});
264     if ($countanalytics > 0){
265         $analytics_flag=1;
266         $item->{countanalytics} = $countanalytics;
267     }
268
269     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
270         $materials_flag = 1;
271     }
272
273     if ( C4::Context->preference('UseCourseReserves') ) {
274         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
275     }
276
277     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
278     and C4::Context->preference('SeparateHoldings')) {
279         if ($itembranchcode and $itembranchcode eq $currentbranch) {
280             push @itemloop, $item;
281         } else {
282             push @otheritemloop, $item;
283         }
284     } else {
285         push @itemloop, $item;
286     }
287 }
288
289 # Display only one tab if one items list is empty
290 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
291     $template->param(SeparateHoldings => 0);
292     if (scalar(@itemloop) == 0) {
293         @itemloop = @otheritemloop;
294     }
295 }
296
297 $template->param( norequests => $norequests );
298 $template->param(
299         MARCNOTES   => $marcnotesarray,
300         MARCSUBJCTS => $marcsubjctsarray,
301         MARCAUTHORS => $marcauthorsarray,
302         MARCSERIES  => $marcseriesarray,
303         MARCURLS => $marcurlsarray,
304     MARCISBNS => $marcisbnsarray,
305         MARCHOSTS => $marchostsarray,
306         subtitle    => $subtitle,
307         itemdata_ccode      => $itemfields{ccode},
308         itemdata_enumchron  => $itemfields{enumchron},
309         itemdata_uri        => $itemfields{uri},
310         itemdata_copynumber => $itemfields{copynumber},
311         volinfo                         => $itemfields{enumchron},
312     itemdata_itemnotes  => $itemfields{itemnotes},
313         z3950_search_params     => C4::Search::z3950_search_args($dat),
314         hostrecords         => $hostrecords,
315         analytics_flag  => $analytics_flag,
316         C4::Search::enabled_staff_search_views,
317         materials       => $materials_flag,
318 );
319
320 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
321     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
322     my $subfields = substr $fieldspec, 3;
323     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
324     my @alternateholdingsinfo = ();
325     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
326
327     for my $field (@holdingsfields) {
328         my %holding = ( holding => '' );
329         my $havesubfield = 0;
330         for my $subfield ($field->subfields()) {
331             if ((index $subfields, $$subfield[0]) >= 0) {
332                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
333                 $holding{'holding'} .= $$subfield[1];
334                 $havesubfield++;
335             }
336         }
337         if ($havesubfield) {
338             push(@alternateholdingsinfo, \%holding);
339         }
340     }
341
342     $template->param(
343         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
344         );
345 }
346
347 my @results = ( $dat, );
348 foreach ( keys %{$dat} ) {
349     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
350 }
351
352 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
353 # method query not found?!?!
354 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
355 $template->param(
356     itemloop        => \@itemloop,
357     otheritemloop   => \@otheritemloop,
358     biblionumber        => $biblionumber,
359     ($analyze? 'analyze':'detailview') =>1,
360     subscriptions       => \@subs,
361     subscriptionsnumber => $subscriptionsnumber,
362     subscriptiontitle   => $dat->{title},
363 );
364
365 # $debug and $template->param(debug_display => 1);
366
367 # Lists
368
369 if (C4::Context->preference("virtualshelves") ) {
370    $template->param( 'GetShelves' => GetBibliosShelves( $biblionumber ) );
371 }
372
373 # XISBN Stuff
374 if (C4::Context->preference("FRBRizeEditions")==1) {
375     eval {
376         $template->param(
377             XISBNS => get_xisbns($isbn)
378         );
379     };
380     if ($@) { warn "XISBN Failed $@"; }
381 }
382
383 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
384     my @images = ListImagesForBiblio($biblionumber);
385     $template->{VARS}->{localimages} = \@images;
386 }
387
388 # HTML5 Media
389 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
390     $template->param( C4::HTML5Media->gethtml5media($record));
391 }
392
393
394 # Get OPAC URL
395 if (C4::Context->preference('OPACBaseURL')){
396      $template->param( OpacUrl => C4::Context->preference('OPACBaseURL') );
397 }
398
399 # Displaying tags
400
401 my $tag_quantity;
402 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
403     $template->param(
404         TagsEnabled => 1,
405         TagsShowOnDetail => $tag_quantity
406     );
407     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
408                                 'sort'=>'-weight', limit=>$tag_quantity}));
409 }
410
411 my ( $holdcount, $holds ) = C4::Reserves::GetReservesFromBiblionumber($biblionumber,1);
412 $template->param( holdcount => $holdcount, holds => $holds );
413
414 output_html_with_http_headers $query, $cookie, $template->output;