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