Bug 17736: Replace GetReservesFromBiblionumber with Koha::Biblio->holds
[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 Modern::Perl;
20
21 use CGI qw ( -utf8 );
22 use HTML::Entities;
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::Reserves;
32 use C4::Members; # to use GetMember
33 use C4::Serials;
34 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
35 use C4::External::Amazon;
36 use C4::Search;         # enabled_staff_search_views
37 use C4::Tags qw(get_tags);
38 use C4::XSLT;
39 use C4::Images;
40 use Koha::DateUtils;
41 use C4::HTML5Media;
42 use C4::CourseReserves qw(GetItemCourseReservesInfo);
43 use C4::Acquisition qw(GetOrdersByBiblionumber);
44 use Koha::AuthorisedValues;
45 use Koha::Biblios;
46 use Koha::Patrons;
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 $biblionumber = HTML::Entities::encode($biblionumber);
65 my $record       = GetMarcBiblio($biblionumber);
66
67 if ( not defined $record ) {
68     # biblionumber invalid -> report and exit
69     $template->param( unknownbiblionumber => 1,
70                       biblionumber => $biblionumber );
71     output_html_with_http_headers $query, $cookie, $template->output;
72     exit;
73 }
74
75 if($query->cookie("holdfor")){ 
76     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
77     $template->param(
78         holdfor => $query->cookie("holdfor"),
79         holdfor_surname => $holdfor_patron->{'surname'},
80         holdfor_firstname => $holdfor_patron->{'firstname'},
81         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
82     );
83 }
84
85 my $fw           = GetFrameworkCode($biblionumber);
86 my $showallitems = $query->param('showallitems');
87 my $marcflavour  = C4::Context->preference("marcflavour");
88
89 # XSLT processing of some stuff
90 my $xslfile = C4::Context->preference('XSLTDetailsDisplay');
91 my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
92 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
93
94 if ( $xslfile ) {
95     $template->param(
96         XSLTDetailsDisplay => '1',
97         XSLTBloc => XSLTParse4Display(
98                         $biblionumber, $record, "XSLTDetailsDisplay",
99                         1, undef, $sysxml, $xslfile, $lang
100                     )
101     );
102 }
103
104 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
105 $template->param( ocoins => GetCOinSBiblio($record) );
106
107 # some useful variables for enhanced content;
108 # in each case, we're grabbing the first value we find in
109 # the record and normalizing it
110 my $upc = GetNormalizedUPC($record,$marcflavour);
111 my $ean = GetNormalizedEAN($record,$marcflavour);
112 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
113 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
114
115 $template->param(
116     normalized_upc => $upc,
117     normalized_ean => $ean,
118     normalized_oclc => $oclc,
119     normalized_isbn => $isbn,
120 );
121
122 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
123 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
124 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
125 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
126 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
127 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
128 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
129 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
130
131 # Get Branches, Itemtypes and Locations
132 my $itemtypes = GetItemTypes();
133 my $dbh = C4::Context->dbh;
134
135 my @all_items = GetItemsInfo( $biblionumber );
136 my @items;
137 my $patron = Koha::Patrons->find( $borrowernumber );
138 for my $itm (@all_items) {
139     push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
140 }
141
142 # flag indicating existence of at least one item linked via a host record
143 my $hostrecords;
144 # adding items linked via host biblios
145 my @hostitems = GetHostItemsInfo($record);
146 if (@hostitems){
147         $hostrecords =1;
148         push (@items,@hostitems);
149 }
150
151 my $dat = &GetBiblioData($biblionumber);
152
153 #coping with subscriptions
154 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
155 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
156 my @subs;
157
158 foreach my $subscription (@subscriptions) {
159     my %cell;
160         my $serials_to_display;
161     $cell{subscriptionid}    = $subscription->{subscriptionid};
162     $cell{subscriptionnotes} = $subscription->{internalnotes};
163     $cell{missinglist}       = $subscription->{missinglist};
164     $cell{librariannote}     = $subscription->{librariannote};
165     $cell{branchcode}        = $subscription->{branchcode};
166     $cell{hasalert}          = $subscription->{hasalert};
167     $cell{callnumber}        = $subscription->{callnumber};
168     $cell{closed}            = $subscription->{closed};
169     #get the three latest serials.
170         $serials_to_display = $subscription->{staffdisplaycount};
171         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
172         $cell{staffdisplaycount} = $serials_to_display;
173     $cell{latestserials} =
174       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
175     push @subs, \%cell;
176 }
177
178
179 # Get acquisition details
180 if ( C4::Context->preference('AcquisitionDetails') ) {
181     my $orders = C4::Acquisition::GetHistory( biblionumber => $biblionumber, get_canceled_order => 1 );
182     $template->param(
183         orders => $orders,
184     );
185 }
186
187 if ( defined $dat->{'itemtype'} ) {
188     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
189 }
190
191 $dat->{'count'} = scalar @all_items + @hostitems;
192 $dat->{'showncount'} = scalar @items + @hostitems;
193 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
194
195 my $shelflocations =
196   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
197 my $collections =
198   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
199 my $copynumbers =
200   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
201 my (@itemloop, @otheritemloop, %itemfields);
202 my $norequests = 1;
203
204 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => { not => undef } });
205 if ( $mss->count ) {
206     $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
207 }
208 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => { not => undef } });
209 if ( $mss->count ) {
210     $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
211 }
212
213 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => { not => undef } });
214 my %materials_map;
215 if ($mss->count) {
216     my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
217     if ($materials_authvals) {
218         foreach my $value (@$materials_authvals) {
219             $materials_map{$value->{authorised_value}} = $value->{lib};
220         }
221     }
222 }
223
224 my $analytics_flag;
225 my $materials_flag; # set this if the items have anything in the materials field
226 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
227 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
228     $template->param(SeparateHoldings => 1);
229 }
230 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
231 foreach my $item (@items) {
232     my $itembranchcode = $item->{$separatebranch};
233
234     # can place holds defaults to yes
235     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
236
237     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
238                                                : '';
239
240     $item->{datedue} = format_sqldatetime($item->{datedue});
241
242     #get shelf location and collection code description if they are authorised value.
243     # same thing for copy number
244     my $shelfcode = $item->{'location'};
245     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
246     my $ccode = $item->{'ccode'};
247     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
248     my $copynumber = $item->{'copynumber'};
249     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
250     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
251         $itemfields{$_} = 1 if ( $item->{$_} );
252     }
253
254     # checking for holds
255     my ($reservedate,$reservedfor,$expectedAt,undef,$wait) = GetReservesFromItemnumber($item->{itemnumber});
256     my $ItemBorrowerReserveInfo = C4::Members::GetMember( borrowernumber => $reservedfor);
257     
258     if (C4::Context->preference('HidePatronName')){
259         $item->{'hidepatronname'} = 1;
260     }
261
262     if ( defined $reservedate ) {
263         $item->{backgroundcolor} = 'reserved';
264         $item->{reservedate}     = $reservedate;
265         $item->{ReservedForBorrowernumber}     = $reservedfor;
266         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
267         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
268         $item->{ExpectedAtLibrary}      = $expectedAt;
269         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
270         # Check waiting status
271         $item->{waitingdate} = $wait;
272     }
273
274
275         # Check the transit status
276     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
277     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
278         $item->{transfertwhen} = $transfertwhen;
279         $item->{transfertfrom} = $transfertfrom;
280         $item->{transfertto}   = $transfertto;
281         $item->{nocancel} = 1;
282     }
283
284     foreach my $f (qw( itemnotes )) {
285         if ($item->{$f}) {
286             $item->{$f} =~ s|\n|<br />|g;
287             $itemfields{$f} = 1;
288         }
289     }
290
291     #item has a host number if its biblio number does not match the current bib
292
293     if ($item->{biblionumber} ne $biblionumber){
294         $item->{hostbiblionumber} = $item->{biblionumber};
295         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
296     }
297         
298     #count if item is used in analytical bibliorecords
299     my $countanalytics= GetAnalyticsCount($item->{itemnumber});
300     if ($countanalytics > 0){
301         $analytics_flag=1;
302         $item->{countanalytics} = $countanalytics;
303     }
304
305     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
306         $materials_flag = 1;
307         if (defined $materials_map{ $item->{materials} }) {
308             $item->{materials} = $materials_map{ $item->{materials} };
309         }
310     }
311
312     if ( C4::Context->preference('UseCourseReserves') ) {
313         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
314     }
315
316     if ( C4::Context->preference('IndependentBranches') ) {
317         my $userenv = C4::Context->userenv();
318         if ( not C4::Context->IsSuperLibrarian()
319             and $userenv->{branch} ne $item->{homebranch} ) {
320             $item->{cannot_be_edited} = 1;
321         }
322     }
323
324     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
325     and C4::Context->preference('SeparateHoldings')) {
326         if ($itembranchcode and $itembranchcode eq $currentbranch) {
327             push @itemloop, $item;
328         } else {
329             push @otheritemloop, $item;
330         }
331     } else {
332         push @itemloop, $item;
333     }
334 }
335
336 # Display only one tab if one items list is empty
337 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
338     $template->param(SeparateHoldings => 0);
339     if (scalar(@itemloop) == 0) {
340         @itemloop = @otheritemloop;
341     }
342 }
343
344 $template->param( norequests => $norequests );
345 $template->param(
346         MARCNOTES   => $marcnotesarray,
347         MARCSUBJCTS => $marcsubjctsarray,
348         MARCAUTHORS => $marcauthorsarray,
349         MARCSERIES  => $marcseriesarray,
350         MARCURLS => $marcurlsarray,
351     MARCISBNS => $marcisbnsarray,
352         MARCHOSTS => $marchostsarray,
353         subtitle    => $subtitle,
354         itemdata_ccode      => $itemfields{ccode},
355         itemdata_enumchron  => $itemfields{enumchron},
356         itemdata_uri        => $itemfields{uri},
357         itemdata_copynumber => $itemfields{copynumber},
358         itemdata_stocknumber => $itemfields{stocknumber},
359         volinfo                         => $itemfields{enumchron},
360         itemdata_itemnotes  => $itemfields{itemnotes},
361         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
362         z3950_search_params     => C4::Search::z3950_search_args($dat),
363         hostrecords         => $hostrecords,
364         analytics_flag  => $analytics_flag,
365         C4::Search::enabled_staff_search_views,
366         materials       => $materials_flag,
367 );
368
369 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
370     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
371     my $subfields = substr $fieldspec, 3;
372     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
373     my @alternateholdingsinfo = ();
374     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
375
376     for my $field (@holdingsfields) {
377         my %holding = ( holding => '' );
378         my $havesubfield = 0;
379         for my $subfield ($field->subfields()) {
380             if ((index $subfields, $$subfield[0]) >= 0) {
381                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
382                 $holding{'holding'} .= $$subfield[1];
383                 $havesubfield++;
384             }
385         }
386         if ($havesubfield) {
387             push(@alternateholdingsinfo, \%holding);
388         }
389     }
390
391     $template->param(
392         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
393         );
394 }
395
396 my @results = ( $dat, );
397 foreach ( keys %{$dat} ) {
398     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
399 }
400
401 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
402 # method query not found?!?!
403 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
404 $template->param(
405     itemloop        => \@itemloop,
406     otheritemloop   => \@otheritemloop,
407     biblionumber        => $biblionumber,
408     ($analyze? 'analyze':'detailview') =>1,
409     subscriptions       => \@subs,
410     subscriptionsnumber => $subscriptionsnumber,
411     subscriptiontitle   => $dat->{title},
412     searchid            => scalar $query->param('searchid'),
413 );
414
415 # $debug and $template->param(debug_display => 1);
416
417 # Lists
418
419 if (C4::Context->preference("virtualshelves") ) {
420     my $shelves = Koha::Virtualshelves->search(
421         {
422             biblionumber => $biblionumber,
423             category => 2,
424         },
425         {
426             join => 'virtualshelfcontents',
427         }
428     );
429     $template->param( 'shelves' => $shelves );
430 }
431
432 # XISBN Stuff
433 if (C4::Context->preference("FRBRizeEditions")==1) {
434     eval {
435         $template->param(
436             XISBNS => get_xisbns($isbn)
437         );
438     };
439     if ($@) { warn "XISBN Failed $@"; }
440 }
441
442 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
443     my @images = ListImagesForBiblio($biblionumber);
444     $template->{VARS}->{localimages} = \@images;
445 }
446
447 # HTML5 Media
448 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
449     $template->param( C4::HTML5Media->gethtml5media($record));
450 }
451
452 # Displaying tags
453
454 my $tag_quantity;
455 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
456     $template->param(
457         TagsEnabled => 1,
458         TagsShowOnDetail => $tag_quantity
459     );
460     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
461                                 'sort'=>'-weight', limit=>$tag_quantity}));
462 }
463
464 #we only need to pass the number of holds to the template
465 my $biblio = Koha::Biblios->find( $biblionumber );
466 my $holds = $biblio->holds;
467 $template->param( holdcount => $holds->count );
468
469 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
470 if ($StaffDetailItemSelection) {
471     # Only enable item selection if user can execute at least one action
472     if (
473         $flags->{superlibrarian}
474         || (
475             ref $flags->{tools} eq 'HASH' && (
476                 $flags->{tools}->{items_batchmod}       # Modify selected items
477                 || $flags->{tools}->{items_batchdel}    # Delete selected items
478             )
479         )
480         || ( ref $flags->{tools} eq '' && $flags->{tools} )
481       )
482     {
483         $template->param(
484             StaffDetailItemSelection => $StaffDetailItemSelection );
485     }
486 }
487
488 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
489 my @deletedorders_using_biblio;
490 my @orders_using_biblio;
491 my @baskets_orders;
492 my @baskets_deletedorders;
493
494 foreach my $myorder (@allorders_using_biblio) {
495     my $basket = $myorder->{'basketno'};
496     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
497         push @deletedorders_using_biblio, $myorder;
498         unless (grep(/^$basket$/, @baskets_deletedorders)){
499             push @baskets_deletedorders,$myorder->{'basketno'};
500         }
501     }
502     else {
503         push @orders_using_biblio, $myorder;
504         unless (grep(/^$basket$/, @baskets_orders)){
505             push @baskets_orders,$myorder->{'basketno'};
506             }
507     }
508 }
509
510 my $count_orders_using_biblio = scalar @orders_using_biblio ;
511 $template->param (countorders => $count_orders_using_biblio);
512
513 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
514 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
515
516 $template->param (basketsorders => \@baskets_orders);
517 $template->param (basketsdeletedorders => \@baskets_deletedorders);
518
519 output_html_with_http_headers $query, $cookie, $template->output;