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