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