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