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