Bug 23140: Fix typo in branchcode parameters for print slip
[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 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') || "default";
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 => $biblio->get_coins );
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{location}          = $subscription->{location};
185     $cell{closed}            = $subscription->{closed};
186     #get the three latest serials.
187     $serials_to_display = $subscription->{staffdisplaycount};
188     $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
189     $cell{staffdisplaycount} = $serials_to_display;
190     $cell{latestserials} =
191       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
192     push @subs, \%cell;
193 }
194
195
196 # Get acquisition details
197 if ( C4::Context->preference('AcquisitionDetails') ) {
198     my $orders = Koha::Acquisition::Orders->search(
199         { biblionumber => $biblionumber },
200         {
201             join => 'basketno',
202             order_by => 'basketno.booksellerid'
203         }
204     );    # GetHistory sorted by aqbooksellerid, but does it make sense?
205
206     $template->param(
207         orders => $orders,
208     );
209 }
210
211 if ( defined $dat->{'itemtype'} ) {
212     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
213 }
214
215 $dat->{'count'} = scalar @all_items + @hostitems;
216 $dat->{'showncount'} = scalar @items + @hostitems;
217 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
218
219 my $shelflocations =
220   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
221 my $collections =
222   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
223 my $copynumbers =
224   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
225 my (@itemloop, @otheritemloop, %itemfields);
226 my $norequests = 1;
227
228 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
229 if ( $mss->count ) {
230     $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
231 }
232 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
233 if ( $mss->count ) {
234     $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
235 }
236 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
237 if ( $mss->count ) {
238     $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
239 }
240
241 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
242 my %materials_map;
243 if ($mss->count) {
244     my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
245     if ($materials_authvals) {
246         foreach my $value (@$materials_authvals) {
247             $materials_map{$value->{authorised_value}} = $value->{lib};
248         }
249     }
250 }
251
252 my $analytics_flag;
253 my $materials_flag; # set this if the items have anything in the materials field
254 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
255 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
256     $template->param(SeparateHoldings => 1);
257 }
258 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
259 foreach my $item (@items) {
260     my $itembranchcode = $item->{$separatebranch};
261
262     # can place holds defaults to yes
263     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
264
265     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
266                                                : '';
267
268     $item->{datedue} = format_sqldatetime($item->{datedue});
269
270     #get shelf location and collection code description if they are authorised value.
271     # same thing for copy number
272     my $shelfcode = $item->{'location'};
273     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
274     my $ccode = $item->{'ccode'};
275     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
276     my $copynumber = $item->{'copynumber'};
277     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
278     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
279         $itemfields{$_} = 1 if ( $item->{$_} );
280     }
281
282     # checking for holds
283     my $item_object = Koha::Items->find( $item->{itemnumber} );
284     my $holds = $item_object->current_holds;
285     if ( my $first_hold = $holds->next ) {
286         my $patron = Koha::Patrons->find( $first_hold->borrowernumber );
287         $item->{backgroundcolor} = 'reserved';
288         $item->{reservedate}     = $first_hold->reservedate;
289         $item->{ReservedFor}     = $patron,
290         $item->{ExpectedAtLibrary}      = $first_hold->branchcode;
291         # Check waiting status
292         $item->{waitingdate} = $first_hold->waitingdate;
293     }
294
295     if ( my $checkout = $item_object->checkout ) {
296         $item->{CheckedOutFor} = $checkout->patron;
297     }
298
299     # Check the transit status
300     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
301     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
302         $item->{transfertwhen} = $transfertwhen;
303         $item->{transfertfrom} = $transfertfrom;
304         $item->{transfertto}   = $transfertto;
305         $item->{nocancel} = 1;
306     }
307
308     foreach my $f (qw( itemnotes )) {
309         if ($item->{$f}) {
310             $item->{$f} =~ s|\n|<br />|g;
311             $itemfields{$f} = 1;
312         }
313     }
314
315     #item has a host number if its biblio number does not match the current bib
316
317     if ($item->{biblionumber} ne $biblionumber){
318         $item->{hostbiblionumber} = $item->{biblionumber};
319         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
320     }
321         
322
323     if ( $analyze ) {
324         # count if item is used in analytical bibliorecords
325         # The 'countanalytics' flag is only used in the templates if analyze is set
326         my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
327         if ($countanalytics > 0){
328             $analytics_flag=1;
329             $item->{countanalytics} = $countanalytics;
330         }
331     }
332
333     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
334         $materials_flag = 1;
335         if (defined $materials_map{ $item->{materials} }) {
336             $item->{materials} = $materials_map{ $item->{materials} };
337         }
338     }
339
340     if ( C4::Context->preference('UseCourseReserves') ) {
341         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
342     }
343
344     if ( C4::Context->preference('IndependentBranches') ) {
345         my $userenv = C4::Context->userenv();
346         if ( not C4::Context->IsSuperLibrarian()
347             and $userenv->{branch} ne $item->{homebranch} ) {
348             $item->{cannot_be_edited} = 1;
349         }
350     }
351
352     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
353     and C4::Context->preference('SeparateHoldings')) {
354         if ($itembranchcode and $itembranchcode eq $currentbranch) {
355             push @itemloop, $item;
356         } else {
357             push @otheritemloop, $item;
358         }
359     } else {
360         push @itemloop, $item;
361     }
362 }
363
364 # Display only one tab if one items list is empty
365 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
366     $template->param(SeparateHoldings => 0);
367     if (scalar(@itemloop) == 0) {
368         @itemloop = @otheritemloop;
369     }
370 }
371
372 $template->param( norequests => $norequests );
373 $template->param(
374     MARCNOTES   => $marcnotesarray,
375     MARCSUBJCTS => $marcsubjctsarray,
376     MARCAUTHORS => $marcauthorsarray,
377     MARCSERIES  => $marcseriesarray,
378     MARCURLS => $marcurlsarray,
379     MARCISBNS => $marcisbnsarray,
380     MARCHOSTS => $marchostsarray,
381     subtitle    => $subtitle,
382     itemdata_ccode      => $itemfields{ccode},
383     itemdata_enumchron  => $itemfields{enumchron},
384     itemdata_uri        => $itemfields{uri},
385     itemdata_copynumber => $itemfields{copynumber},
386     itemdata_stocknumber => $itemfields{stocknumber},
387     volinfo                => $itemfields{enumchron},
388         itemdata_itemnotes  => $itemfields{itemnotes},
389         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
390     z3950_search_params    => C4::Search::z3950_search_args($dat),
391         hostrecords         => $hostrecords,
392     analytics_flag    => $analytics_flag,
393     C4::Search::enabled_staff_search_views,
394         materials       => $materials_flag,
395 );
396
397 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
398     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
399     my $subfields = substr $fieldspec, 3;
400     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
401     my @alternateholdingsinfo = ();
402     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
403
404     for my $field (@holdingsfields) {
405         my %holding = ( holding => '' );
406         my $havesubfield = 0;
407         for my $subfield ($field->subfields()) {
408             if ((index $subfields, $$subfield[0]) >= 0) {
409                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
410                 $holding{'holding'} .= $$subfield[1];
411                 $havesubfield++;
412             }
413         }
414         if ($havesubfield) {
415             push(@alternateholdingsinfo, \%holding);
416         }
417     }
418
419     $template->param(
420         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
421         );
422 }
423
424 my @results = ( $dat, );
425 foreach ( keys %{$dat} ) {
426     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
427 }
428
429 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
430 # method query not found?!?!
431 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
432 $template->param(
433     itemloop        => \@itemloop,
434     otheritemloop   => \@otheritemloop,
435     biblionumber        => $biblionumber,
436     ($analyze? 'analyze':'detailview') =>1,
437     subscriptions       => \@subs,
438     subscriptionsnumber => $subscriptionsnumber,
439     subscriptiontitle   => $dat->{title},
440     searchid            => scalar $query->param('searchid'),
441 );
442
443 # $debug and $template->param(debug_display => 1);
444
445 # Lists
446
447 if (C4::Context->preference("virtualshelves") ) {
448     my $shelves = Koha::Virtualshelves->search(
449         {
450             biblionumber => $biblionumber,
451             category => 2,
452         },
453         {
454             join => 'virtualshelfcontents',
455         }
456     );
457     $template->param( 'shelves' => $shelves );
458 }
459
460 # XISBN Stuff
461 if (C4::Context->preference("FRBRizeEditions")==1) {
462     eval {
463         $template->param(
464             XISBNS => scalar get_xisbns($isbn)
465         );
466     };
467     if ($@) { warn "XISBN Failed $@"; }
468 }
469
470 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
471     my @images = ListImagesForBiblio($biblionumber);
472     $template->{VARS}->{localimages} = \@images;
473 }
474
475 # HTML5 Media
476 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
477     $template->param( C4::HTML5Media->gethtml5media($record));
478 }
479
480 # Displaying tags
481
482 my $tag_quantity;
483 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
484     $template->param(
485         TagsEnabled => 1,
486         TagsShowOnDetail => $tag_quantity
487     );
488     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
489                                 'sort'=>'-weight', limit=>$tag_quantity}));
490 }
491
492 #we only need to pass the number of holds to the template
493 my $holds = $biblio->holds;
494 $template->param( holdcount => $holds->count );
495
496 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
497 if ($StaffDetailItemSelection) {
498     # Only enable item selection if user can execute at least one action
499     if (
500         $flags->{superlibrarian}
501         || (
502             ref $flags->{tools} eq 'HASH' && (
503                 $flags->{tools}->{items_batchmod}       # Modify selected items
504                 || $flags->{tools}->{items_batchdel}    # Delete selected items
505             )
506         )
507         || ( ref $flags->{tools} eq '' && $flags->{tools} )
508       )
509     {
510         $template->param(
511             StaffDetailItemSelection => $StaffDetailItemSelection );
512     }
513 }
514
515 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
516 my @deletedorders_using_biblio;
517 my @orders_using_biblio;
518 my @baskets_orders;
519 my @baskets_deletedorders;
520
521 foreach my $myorder (@allorders_using_biblio) {
522     my $basket = $myorder->{'basketno'};
523     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
524         push @deletedorders_using_biblio, $myorder;
525         unless (grep(/^$basket$/, @baskets_deletedorders)){
526             push @baskets_deletedorders,$myorder->{'basketno'};
527         }
528     }
529     else {
530         push @orders_using_biblio, $myorder;
531         unless (grep(/^$basket$/, @baskets_orders)){
532             push @baskets_orders,$myorder->{'basketno'};
533             }
534     }
535 }
536
537 my $count_orders_using_biblio = scalar @orders_using_biblio ;
538 $template->param (countorders => $count_orders_using_biblio);
539
540 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
541 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
542
543 $template->param (basketsorders => \@baskets_orders);
544 $template->param (basketsdeletedorders => \@baskets_deletedorders);
545
546 output_html_with_http_headers $query, $cookie, $template->output;