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