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