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