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