Bug 15851: (QA follow-up) Fix booleans to uppercase to make this work for Elasticsear...
[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 Try::Tiny;
24 use C4::Auth;
25 use C4::Context;
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::Reserves;
33 use C4::Serials;
34 use C4::XISBN qw(get_xisbns);
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::Illrequests;
47 use Koha::Items;
48 use Koha::ItemTypes;
49 use Koha::Patrons;
50 use Koha::Virtualshelves;
51 use Koha::Plugins;
52 use Koha::SearchEngine::Search;
53
54 my $query = CGI->new();
55
56 my $analyze = $query->param('analyze');
57
58 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
59     {
60     template_name   =>  'catalogue/detail.tt',
61         query           => $query,
62         type            => "intranet",
63         flagsrequired   => { catalogue => 1 },
64     }
65 );
66
67 # Determine if we should be offering any enhancement plugin buttons
68 if ( C4::Context->config('enable_plugins') ) {
69     # Only pass plugins that can offer a toolbar button
70     my @plugins = Koha::Plugins->new()->GetPlugins({
71         method => 'intranet_catalog_biblio_enhancements_toolbar_button'
72     });
73
74     my @tab_plugins = Koha::Plugins->new()->GetPlugins({
75         method => 'intranet_catalog_biblio_tab',
76     });
77     my @tabs;
78     foreach my $tab_plugin (@tab_plugins) {
79         my @biblio_tabs;
80
81         try {
82             @biblio_tabs = $tab_plugin->intranet_catalog_biblio_tab();
83             foreach my $tab (@biblio_tabs) {
84                 my $tab_id = 'tab-' . $tab->title;
85                 $tab_id =~ s/[^0-9A-Za-z]+/-/g;
86                 $tab->id( $tab_id );
87                 push @tabs, $tab,
88             }
89         }
90         catch {
91             warn "Error calling 'intranet_catalog_biblio_tab' on the " . $tab_plugin->{class} . "plugin ($_)";
92         };
93     }
94
95     $template->param(
96         plugins => \@plugins,
97         tabs => \@tabs,
98     );
99 }
100
101 my $biblionumber = $query->param('biblionumber');
102 $biblionumber = HTML::Entities::encode($biblionumber);
103 my $record       = GetMarcBiblio({ biblionumber => $biblionumber });
104 my $biblio = Koha::Biblios->find( $biblionumber );
105 $template->param( 'biblio', $biblio );
106
107 if ( not defined $record ) {
108     # biblionumber invalid -> report and exit
109     $template->param( unknownbiblionumber => 1,
110                       biblionumber => $biblionumber );
111     output_html_with_http_headers $query, $cookie, $template->output;
112     exit;
113 }
114
115 eval { $biblio->metadata->record };
116 $template->param( decoding_error => $@ );
117
118 if($query->cookie("holdfor")){ 
119     my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") );
120     $template->param(
121         # FIXME Should pass the patron object
122         holdfor => $query->cookie("holdfor"),
123         holdfor_surname => $holdfor_patron->surname,
124         holdfor_firstname => $holdfor_patron->firstname,
125         holdfor_cardnumber => $holdfor_patron->cardnumber,
126     );
127 }
128
129 if($query->cookie("searchToOrder")){
130     my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") );
131     $template->param(
132         searchtoorder_basketno => $basketno,
133         searchtoorder_vendorid => $vendorid
134     );
135 }
136
137 my $fw           = GetFrameworkCode($biblionumber);
138 my $showallitems = $query->param('showallitems');
139 my $marcflavour  = C4::Context->preference("marcflavour");
140
141 # XSLT processing of some stuff
142 my $xslfile = C4::Context->preference('XSLTDetailsDisplay') || "default";
143 my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
144 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
145
146 if ( $xslfile ) {
147
148     my $searcher = Koha::SearchEngine::Search->new(
149         { index => $Koha::SearchEngine::BIBLIOS_INDEX }
150     );
151     my $cleaned_title = $biblio->title;
152     $cleaned_title =~ tr|/||;
153     my $query =
154       ( C4::Context->preference('UseControlNumber') and $record->field('001') )
155       ? 'rcn:'. $record->field('001')->data . ' AND (bib-level:a OR bib-level:b)'
156       : "Host-item:$cleaned_title";
157     my ( $err, $result, $count ) = $searcher->simple_search_compat( $query, 0, 0 );
158
159     warn "Warning from simple_search_compat: $err"
160         if $err;
161
162     my $variables = {
163         show_analytics_link => $count > 0 ? 1 : 0
164     };
165
166     $template->param(
167         XSLTDetailsDisplay => '1',
168         XSLTBloc           => XSLTParse4Display(
169             $biblionumber, $record, "XSLTDetailsDisplay", 1,
170             undef,         $sysxml, $xslfile,             $lang,
171             $variables
172         )
173     );
174 }
175
176 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
177
178 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
179 # Do not propagate it as we already deal with it previously in this script
180 my $coins = eval { $biblio->get_coins };
181 $template->param( ocoins => $coins );
182
183 # some useful variables for enhanced content;
184 # in each case, we're grabbing the first value we find in
185 # the record and normalizing it
186 my $upc = GetNormalizedUPC($record,$marcflavour);
187 my $ean = GetNormalizedEAN($record,$marcflavour);
188 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
189 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
190
191 $template->param(
192     normalized_upc => $upc,
193     normalized_ean => $ean,
194     normalized_oclc => $oclc,
195     normalized_isbn => $isbn,
196 );
197
198 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
199
200 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
201
202 my $dbh = C4::Context->dbh;
203
204 my @all_items = GetItemsInfo( $biblionumber );
205 my @items;
206 my $patron = Koha::Patrons->find( $borrowernumber );
207 for my $itm (@all_items) {
208     push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
209 }
210
211 # flag indicating existence of at least one item linked via a host record
212 my $hostrecords;
213 # adding items linked via host biblios
214 my @hostitems = GetHostItemsInfo($record);
215 if (@hostitems){
216     $hostrecords =1;
217     push (@items,@hostitems);
218 }
219
220 my $dat = &GetBiblioData($biblionumber);
221
222 #coping with subscriptions
223 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
224 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
225 my @subs;
226
227 foreach my $subscription (@subscriptions) {
228     my %cell;
229     my $serials_to_display;
230     $cell{subscriptionid}    = $subscription->{subscriptionid};
231     $cell{subscriptionnotes} = $subscription->{internalnotes};
232     $cell{missinglist}       = $subscription->{missinglist};
233     $cell{librariannote}     = $subscription->{librariannote};
234     $cell{branchcode}        = $subscription->{branchcode};
235     $cell{hasalert}          = $subscription->{hasalert};
236     $cell{callnumber}        = $subscription->{callnumber};
237     $cell{location}          = $subscription->{location};
238     $cell{closed}            = $subscription->{closed};
239     #get the three latest serials.
240     $serials_to_display = $subscription->{staffdisplaycount};
241     $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
242     $cell{staffdisplaycount} = $serials_to_display;
243     $cell{latestserials} =
244       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
245     push @subs, \%cell;
246 }
247
248
249 # Get acquisition details
250 if ( C4::Context->preference('AcquisitionDetails') ) {
251     my $orders = Koha::Acquisition::Orders->search(
252         { biblionumber => $biblionumber },
253         {
254             join => 'basketno',
255             order_by => 'basketno.booksellerid'
256         }
257     );    # GetHistory sorted by aqbooksellerid, but does it make sense?
258
259     $template->param(
260         orders => $orders,
261     );
262 }
263
264 if ( C4::Context->preference('suggestion') ) {
265     my $suggestions = Koha::Suggestions->search(
266         {
267             biblionumber => $biblionumber,
268             archived     => 0,
269         },
270         {
271             order_by => { -desc => 'suggesteddate' }
272         }
273     );
274     my $nb_archived_suggestions = Koha::Suggestions->search({ biblionumber => $biblionumber, archived => 1 })->count;
275     $template->param( suggestions => $suggestions, nb_archived_suggestions => $nb_archived_suggestions );
276 }
277
278 if ( defined $dat->{'itemtype'} ) {
279     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
280 }
281
282 $dat->{'count'} = scalar @all_items + @hostitems;
283 $dat->{'showncount'} = scalar @items + @hostitems;
284 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
285
286 my $shelflocations =
287   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
288 my $collections =
289   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
290 my $copynumbers =
291   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
292 my (@itemloop, @otheritemloop, %itemfields);
293
294 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
295 if ( $mss->count ) {
296     $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
297 }
298 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
299 if ( $mss->count ) {
300     $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
301 }
302 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
303 if ( $mss->count ) {
304     $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
305 }
306
307 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
308 my %materials_map;
309 if ($mss->count) {
310     my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
311     if ($materials_authvals) {
312         foreach my $value (@$materials_authvals) {
313             $materials_map{$value->{authorised_value}} = $value->{lib};
314         }
315     }
316 }
317
318 my $analytics_flag;
319 my $materials_flag; # set this if the items have anything in the materials field
320 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
321 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
322     $template->param(SeparateHoldings => 1);
323 }
324 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
325 foreach my $item (@items) {
326     my $itembranchcode = $item->{$separatebranch};
327
328     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
329                                                : '';
330
331     $item->{datedue} = format_sqldatetime($item->{datedue});
332
333     #get shelf location and collection code description if they are authorised value.
334     # same thing for copy number
335     my $shelfcode = $item->{'location'};
336     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
337     my $ccode = $item->{'ccode'};
338     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
339     my $copynumber = $item->{'copynumber'};
340     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
341     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri publisheddate)) { # Warning when removing GetItemsInfo - publisheddate (at least) is not part of the items table
342         $itemfields{$_} = 1 if ( $item->{$_} );
343     }
344
345     # checking for holds
346     my $item_object = Koha::Items->find( $item->{itemnumber} );
347     my $holds = $item_object->current_holds;
348     if ( my $first_hold = $holds->next ) {
349         $item->{first_hold} = $first_hold;
350     }
351
352     if ( my $checkout = $item_object->checkout ) {
353         $item->{CheckedOutFor} = $checkout->patron;
354     }
355
356     # Check the transit status
357     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
358     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
359         $item->{transfertwhen} = $transfertwhen;
360         $item->{transfertfrom} = $transfertfrom;
361         $item->{transfertto}   = $transfertto;
362         $item->{nocancel} = 1;
363     }
364
365     foreach my $f (qw( itemnotes )) {
366         if ($item->{$f}) {
367             $item->{$f} =~ s|\n|<br />|g;
368             $itemfields{$f} = 1;
369         }
370     }
371
372     #item has a host number if its biblio number does not match the current bib
373
374     if ($item->{biblionumber} ne $biblionumber){
375         $item->{hostbiblionumber} = $item->{biblionumber};
376         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
377     }
378         
379
380     if ( $analyze ) {
381         # count if item is used in analytical bibliorecords
382         # The 'countanalytics' flag is only used in the templates if analyze is set
383         my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
384         if ($countanalytics > 0){
385             $analytics_flag=1;
386             $item->{countanalytics} = $countanalytics;
387         }
388     }
389
390     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
391         $materials_flag = 1;
392         if (defined $materials_map{ $item->{materials} }) {
393             $item->{materials} = $materials_map{ $item->{materials} };
394         }
395     }
396
397     if ( C4::Context->preference('UseCourseReserves') ) {
398         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
399     }
400
401     if ( C4::Context->preference('IndependentBranches') ) {
402         my $userenv = C4::Context->userenv();
403         if ( not C4::Context->IsSuperLibrarian()
404             and $userenv->{branch} ne $item->{homebranch} ) {
405             $item->{cannot_be_edited} = 1;
406         }
407     }
408
409     if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
410         if ($itembranchcode and $itembranchcode eq $currentbranch) {
411             push @itemloop, $item;
412         } else {
413             push @otheritemloop, $item;
414         }
415     } else {
416         push @itemloop, $item;
417     }
418 }
419
420 # Display only one tab if one items list is empty
421 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
422     $template->param(SeparateHoldings => 0);
423     if (scalar(@itemloop) == 0) {
424         @itemloop = @otheritemloop;
425     }
426 }
427
428 $template->param(
429     MARCNOTES   => $marcnotesarray,
430     itemdata_ccode      => $itemfields{ccode},
431     itemdata_enumchron  => $itemfields{enumchron},
432     itemdata_uri        => $itemfields{uri},
433     itemdata_copynumber => $itemfields{copynumber},
434     itemdata_stocknumber => $itemfields{stocknumber},
435     itemdata_publisheddate => $itemfields{publisheddate},
436     volinfo                => $itemfields{enumchron},
437         itemdata_itemnotes  => $itemfields{itemnotes},
438         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
439     z3950_search_params    => C4::Search::z3950_search_args($dat),
440         hostrecords         => $hostrecords,
441     analytics_flag    => $analytics_flag,
442     C4::Search::enabled_staff_search_views,
443         materials       => $materials_flag,
444 );
445
446 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
447     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
448     my $subfields = substr $fieldspec, 3;
449     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
450     my @alternateholdingsinfo = ();
451     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
452
453     for my $field (@holdingsfields) {
454         my %holding = ( holding => '' );
455         my $havesubfield = 0;
456         for my $subfield ($field->subfields()) {
457             if ((index $subfields, $$subfield[0]) >= 0) {
458                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
459                 $holding{'holding'} .= $$subfield[1];
460                 $havesubfield++;
461             }
462         }
463         if ($havesubfield) {
464             push(@alternateholdingsinfo, \%holding);
465         }
466     }
467
468     $template->param(
469         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
470         );
471 }
472
473 my @results = ( $dat, );
474 foreach ( keys %{$dat} ) {
475     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
476 }
477
478 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
479 # method query not found?!?!
480 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
481 $template->param(
482     itemloop        => \@itemloop,
483     otheritemloop   => \@otheritemloop,
484     biblionumber        => $biblionumber,
485     ($analyze? 'analyze':'detailview') =>1,
486     subscriptions       => \@subs,
487     subscriptionsnumber => $subscriptionsnumber,
488     subscriptiontitle   => $dat->{title},
489     searchid            => scalar $query->param('searchid'),
490 );
491
492 # $debug and $template->param(debug_display => 1);
493
494 # Lists
495
496 if (C4::Context->preference("virtualshelves") ) {
497     my $shelves = Koha::Virtualshelves->search(
498         {
499             biblionumber => $biblionumber,
500             category => 2,
501         },
502         {
503             join => 'virtualshelfcontents',
504         }
505     );
506     $template->param( 'shelves' => $shelves );
507 }
508
509 # XISBN Stuff
510 if (C4::Context->preference("FRBRizeEditions")==1) {
511     eval {
512         $template->param(
513             XISBNS => scalar get_xisbns($isbn, $biblionumber)
514         );
515     };
516     if ($@) { warn "XISBN Failed $@"; }
517 }
518
519 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
520     my @images = ListImagesForBiblio($biblionumber);
521     $template->{VARS}->{localimages} = \@images;
522 }
523
524 # HTML5 Media
525 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
526     $template->param( C4::HTML5Media->gethtml5media($record));
527 }
528
529 # Displaying tags
530 my $tag_quantity;
531 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
532     $template->param(
533         TagsEnabled => 1,
534         TagsShowOnDetail => $tag_quantity
535     );
536     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
537                                 'sort'=>'-weight', limit=>$tag_quantity}));
538 }
539
540 #we only need to pass the number of holds to the template
541 my $holds = $biblio->holds;
542 $template->param( holdcount => $holds->count );
543
544 # Check if there are any ILL requests connected to the biblio
545 my $illrequests =
546     C4::Context->preference('ILLModule')
547   ? Koha::Illrequests->search( { biblio_id => $biblionumber } )
548   : [];
549 $template->param( illrequests => $illrequests );
550
551 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
552 if ($StaffDetailItemSelection) {
553     # Only enable item selection if user can execute at least one action
554     if (
555         $flags->{superlibrarian}
556         || (
557             ref $flags->{tools} eq 'HASH' && (
558                 $flags->{tools}->{items_batchmod}       # Modify selected items
559                 || $flags->{tools}->{items_batchdel}    # Delete selected items
560             )
561         )
562         || ( ref $flags->{tools} eq '' && $flags->{tools} )
563       )
564     {
565         $template->param(
566             StaffDetailItemSelection => $StaffDetailItemSelection );
567     }
568 }
569
570 $template->param(biblio => $biblio);
571
572 output_html_with_http_headers $query, $cookie, $template->output;