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