Bug 14544: Get rid of GetBibliosShelves
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
19 use strict;
20 use warnings;
21
22 use CGI qw ( -utf8 );
23 use C4::Acquisition qw( GetHistory );
24 use C4::Auth;
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 use C4::Acquisition qw(GetOrdersByBiblionumber);
46
47 use Koha::Virtualshelves;
48
49 my $query = CGI->new();
50
51 my $analyze = $query->param('analyze');
52
53 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
54     {
55     template_name   =>  'catalogue/detail.tt',
56         query           => $query,
57         type            => "intranet",
58         authnotrequired => 0,
59         flagsrequired   => { catalogue => 1 },
60     }
61 );
62
63 my $biblionumber = $query->param('biblionumber');
64 my $record       = GetMarcBiblio($biblionumber);
65
66 if ( not defined $record ) {
67     # biblionumber invalid -> report and exit
68     $template->param( unknownbiblionumber => 1,
69                       biblionumber => $biblionumber );
70     output_html_with_http_headers $query, $cookie, $template->output;
71     exit;
72 }
73
74 if($query->cookie("holdfor")){ 
75     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
76     $template->param(
77         holdfor => $query->cookie("holdfor"),
78         holdfor_surname => $holdfor_patron->{'surname'},
79         holdfor_firstname => $holdfor_patron->{'firstname'},
80         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
81     );
82 }
83
84 my $fw           = GetFrameworkCode($biblionumber);
85 my $showallitems = $query->param('showallitems');
86 my $marcflavour  = C4::Context->preference("marcflavour");
87
88 # XSLT processing of some stuff
89 if (C4::Context->preference("XSLTDetailsDisplay") ) {
90     $template->param('XSLTDetailsDisplay' =>'1',
91         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, "XSLTDetailsDisplay") );
92 }
93
94 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
95 $template->param( ocoins => GetCOinSBiblio($record) );
96
97 # some useful variables for enhanced content;
98 # in each case, we're grabbing the first value we find in
99 # the record and normalizing it
100 my $upc = GetNormalizedUPC($record,$marcflavour);
101 my $ean = GetNormalizedEAN($record,$marcflavour);
102 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
103 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
104
105 $template->param(
106     normalized_upc => $upc,
107     normalized_ean => $ean,
108     normalized_oclc => $oclc,
109     normalized_isbn => $isbn,
110 );
111
112 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
113 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
114 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
115 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
116 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
117 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
118 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
119 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
120
121 # Get Branches, Itemtypes and Locations
122 my $branches = GetBranches();
123 my $itemtypes = GetItemTypes();
124 my $dbh = C4::Context->dbh;
125
126 my @all_items = GetItemsInfo( $biblionumber );
127 my @items;
128 for my $itm (@all_items) {
129     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
130 }
131
132 # flag indicating existence of at least one item linked via a host record
133 my $hostrecords;
134 # adding items linked via host biblios
135 my @hostitems = GetHostItemsInfo($record);
136 if (@hostitems){
137         $hostrecords =1;
138         push (@items,@hostitems);
139 }
140
141 my $dat = &GetBiblioData($biblionumber);
142
143 #coping with subscriptions
144 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
145 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
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     $cell{callnumber}        = $subscription->{callnumber};
159     $cell{closed}            = $subscription->{closed};
160     #get the three latest serials.
161         $serials_to_display = $subscription->{staffdisplaycount};
162         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
163         $cell{staffdisplaycount} = $serials_to_display;
164     $cell{latestserials} =
165       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
166     push @subs, \%cell;
167 }
168
169
170 # Get acquisition details
171 if ( C4::Context->preference('AcquisitionDetails') ) {
172     my $orders = C4::Acquisition::GetHistory( biblionumber => $biblionumber, get_canceled_order => 1 );
173     $template->param(
174         orders => $orders,
175     );
176 }
177
178 if ( defined $dat->{'itemtype'} ) {
179     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
180 }
181
182 $dat->{'count'} = scalar @all_items + @hostitems;
183 $dat->{'showncount'} = scalar @items + @hostitems;
184 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
185
186 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
187 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
188 my $copynumbers    = GetKohaAuthorisedValues('items.copynumber', $fw);
189 my (@itemloop, @otheritemloop, %itemfields);
190 my $norequests = 1;
191 my $authvalcode_items_itemlost = GetAuthValCode('items.itemlost',$fw);
192 my $authvalcode_items_damaged  = GetAuthValCode('items.damaged', $fw);
193
194 my $analytics_flag;
195 my $materials_flag; # set this if the items have anything in the materials field
196 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
197 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
198     $template->param(SeparateHoldings => 1);
199 }
200 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
201 foreach my $item (@items) {
202     my $itembranchcode = $item->{$separatebranch};
203
204     # can place holds defaults to yes
205     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
206
207     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
208                                                : '';
209
210     $item->{datedue} = format_sqldatetime($item->{datedue});
211     # item damaged, lost, withdrawn loops
212     $item->{itemlostloop} = GetAuthorisedValues($authvalcode_items_itemlost, $item->{itemlost}) if $authvalcode_items_itemlost;
213     if ($item->{damaged}) {
214         $item->{itemdamagedloop} = GetAuthorisedValues($authvalcode_items_damaged, $item->{damaged}) if $authvalcode_items_damaged;
215     }
216     #get shelf location and collection code description if they are authorised value.
217     # same thing for copy number
218     my $shelfcode = $item->{'location'};
219     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
220     my $ccode = $item->{'ccode'};
221     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
222     my $copynumber = $item->{'copynumber'};
223     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
224     foreach (qw(ccode enumchron copynumber stocknumber itemnotes uri)) {
225         $itemfields{$_} = 1 if ( $item->{$_} );
226     }
227
228     # checking for holds
229     my ($reservedate,$reservedfor,$expectedAt,undef,$wait) = GetReservesFromItemnumber($item->{itemnumber});
230     my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
231     
232     if (C4::Context->preference('HidePatronName')){
233         $item->{'hidepatronname'} = 1;
234     }
235
236     if ( defined $reservedate ) {
237         $item->{backgroundcolor} = 'reserved';
238         $item->{reservedate}     = $reservedate;
239         $item->{ReservedForBorrowernumber}     = $reservedfor;
240         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
241         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
242         $item->{ExpectedAtLibrary}      = $branches->{$expectedAt}{branchname};
243         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
244         # Check waiting status
245         $item->{waitingdate} = $wait;
246     }
247
248
249         # Check the transit status
250     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
251     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
252         $item->{transfertwhen} = $transfertwhen;
253         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
254         $item->{transfertto}   = $branches->{$transfertto}{branchname};
255         $item->{nocancel} = 1;
256     }
257
258     # item has a host number if its biblio number does not match the current bib
259     if ($item->{biblionumber} ne $biblionumber){
260         $item->{hostbiblionumber} = $item->{biblionumber};
261         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
262     }
263         
264     #count if item is used in analytical bibliorecords
265     my $countanalytics= GetAnalyticsCount($item->{itemnumber});
266     if ($countanalytics > 0){
267         $analytics_flag=1;
268         $item->{countanalytics} = $countanalytics;
269     }
270
271     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
272         $materials_flag = 1;
273     }
274
275     if ( C4::Context->preference('UseCourseReserves') ) {
276         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
277     }
278
279     if ( C4::Context->preference('IndependentBranches') ) {
280         my $userenv = C4::Context->userenv();
281         if ( not C4::Context->IsSuperLibrarian()
282             and $userenv->{branch} ne $item->{homebranch} ) {
283             $item->{cannot_be_edited} = 1;
284         }
285     }
286
287     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
288     and C4::Context->preference('SeparateHoldings')) {
289         if ($itembranchcode and $itembranchcode eq $currentbranch) {
290             push @itemloop, $item;
291         } else {
292             push @otheritemloop, $item;
293         }
294     } else {
295         push @itemloop, $item;
296     }
297 }
298
299 # Display only one tab if one items list is empty
300 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
301     $template->param(SeparateHoldings => 0);
302     if (scalar(@itemloop) == 0) {
303         @itemloop = @otheritemloop;
304     }
305 }
306
307 $template->param( norequests => $norequests );
308 $template->param(
309         MARCNOTES   => $marcnotesarray,
310         MARCSUBJCTS => $marcsubjctsarray,
311         MARCAUTHORS => $marcauthorsarray,
312         MARCSERIES  => $marcseriesarray,
313         MARCURLS => $marcurlsarray,
314     MARCISBNS => $marcisbnsarray,
315         MARCHOSTS => $marchostsarray,
316         subtitle    => $subtitle,
317         itemdata_ccode      => $itemfields{ccode},
318         itemdata_enumchron  => $itemfields{enumchron},
319         itemdata_uri        => $itemfields{uri},
320         itemdata_copynumber => $itemfields{copynumber},
321         itemdata_stocknumber => $itemfields{stocknumber},
322         volinfo                         => $itemfields{enumchron},
323     itemdata_itemnotes  => $itemfields{itemnotes},
324         z3950_search_params     => C4::Search::z3950_search_args($dat),
325         hostrecords         => $hostrecords,
326         analytics_flag  => $analytics_flag,
327         C4::Search::enabled_staff_search_views,
328         materials       => $materials_flag,
329 );
330
331 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
332     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
333     my $subfields = substr $fieldspec, 3;
334     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
335     my @alternateholdingsinfo = ();
336     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
337
338     for my $field (@holdingsfields) {
339         my %holding = ( holding => '' );
340         my $havesubfield = 0;
341         for my $subfield ($field->subfields()) {
342             if ((index $subfields, $$subfield[0]) >= 0) {
343                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
344                 $holding{'holding'} .= $$subfield[1];
345                 $havesubfield++;
346             }
347         }
348         if ($havesubfield) {
349             push(@alternateholdingsinfo, \%holding);
350         }
351     }
352
353     $template->param(
354         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
355         );
356 }
357
358 my @results = ( $dat, );
359 foreach ( keys %{$dat} ) {
360     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
361 }
362
363 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
364 # method query not found?!?!
365 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
366 $template->param(
367     itemloop        => \@itemloop,
368     otheritemloop   => \@otheritemloop,
369     biblionumber        => $biblionumber,
370     ($analyze? 'analyze':'detailview') =>1,
371     subscriptions       => \@subs,
372     subscriptionsnumber => $subscriptionsnumber,
373     subscriptiontitle   => $dat->{title},
374     searchid            => $query->param('searchid'),
375 );
376
377 # $debug and $template->param(debug_display => 1);
378
379 # Lists
380
381 if (C4::Context->preference("virtualshelves") ) {
382     my $shelves = Koha::Virtualshelves->search(
383         {
384             biblionumber => $biblionumber,
385             category => 2,
386         },
387         {
388             join => 'virtualshelfcontents',
389         }
390     );
391     $template->param( 'shelves' => $shelves );
392 }
393
394 # XISBN Stuff
395 if (C4::Context->preference("FRBRizeEditions")==1) {
396     eval {
397         $template->param(
398             XISBNS => get_xisbns($isbn)
399         );
400     };
401     if ($@) { warn "XISBN Failed $@"; }
402 }
403
404 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
405     my @images = ListImagesForBiblio($biblionumber);
406     $template->{VARS}->{localimages} = \@images;
407 }
408
409 # HTML5 Media
410 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
411     $template->param( C4::HTML5Media->gethtml5media($record));
412 }
413
414 # Displaying tags
415
416 my $tag_quantity;
417 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
418     $template->param(
419         TagsEnabled => 1,
420         TagsShowOnDetail => $tag_quantity
421     );
422     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
423                                 'sort'=>'-weight', limit=>$tag_quantity}));
424 }
425
426 #we only need to pass the number of holds to the template
427 my $holds = C4::Reserves::GetReservesFromBiblionumber({ biblionumber => $biblionumber, all_dates => 1 });
428 $template->param( holdcount => scalar ( @$holds ) );
429
430 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
431 if ($StaffDetailItemSelection) {
432     # Only enable item selection if user can execute at least one action
433     if (
434         $flags->{superlibrarian}
435         || (
436             ref $flags->{tools} eq 'HASH' && (
437                 $flags->{tools}->{items_batchmod}       # Modify selected items
438                 || $flags->{tools}->{items_batchdel}    # Delete selected items
439             )
440         )
441         || ( ref $flags->{tools} eq '' && $flags->{tools} )
442       )
443     {
444         $template->param(
445             StaffDetailItemSelection => $StaffDetailItemSelection );
446     }
447 }
448
449 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
450 my @deletedorders_using_biblio;
451 my @orders_using_biblio;
452 my @baskets_orders;
453 my @baskets_deletedorders;
454
455 foreach my $myorder (@allorders_using_biblio) {
456     my $basket = $myorder->{'basketno'};
457     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
458         push @deletedorders_using_biblio, $myorder;
459         unless (grep(/^$basket$/, @baskets_deletedorders)){
460             push @baskets_deletedorders,$myorder->{'basketno'};
461         }
462     }
463     else {
464         push @orders_using_biblio, $myorder;
465         unless (grep(/^$basket$/, @baskets_orders)){
466             push @baskets_orders,$myorder->{'basketno'};
467             }
468     }
469 }
470
471 my $count_orders_using_biblio = scalar @orders_using_biblio ;
472 $template->param (countorders => $count_orders_using_biblio);
473
474 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
475 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
476
477 $template->param (basketsorders => \@baskets_orders);
478 $template->param (basketsdeletedorders => \@baskets_deletedorders);
479
480 output_html_with_http_headers $query, $cookie, $template->output;