Bug 19580: Unit tests
[koha.git] / catalogue / detail.pl
blob865da68cae2dbcbaeea89d15885f8cea763f5418
1 #!/usr/bin/perl
3 # This file is part of Koha.
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.
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.
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>.
19 use Modern::Perl;
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::AuthorisedValues;
45 use Koha::Biblios;
46 use Koha::Items;
47 use Koha::ItemTypes;
48 use Koha::Patrons;
49 use Koha::Virtualshelves;
51 my $query = CGI->new();
53 my $analyze = $query->param('analyze');
55 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
57 template_name => 'catalogue/detail.tt',
58 query => $query,
59 type => "intranet",
60 authnotrequired => 0,
61 flagsrequired => { catalogue => 1 },
65 my $biblionumber = $query->param('biblionumber');
66 $biblionumber = HTML::Entities::encode($biblionumber);
67 my $record = GetMarcBiblio($biblionumber);
69 if ( not defined $record ) {
70 # biblionumber invalid -> report and exit
71 $template->param( unknownbiblionumber => 1,
72 biblionumber => $biblionumber );
73 output_html_with_http_headers $query, $cookie, $template->output;
74 exit;
77 if($query->cookie("holdfor")){
78 my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
79 $template->param(
80 holdfor => $query->cookie("holdfor"),
81 holdfor_surname => $holdfor_patron->{'surname'},
82 holdfor_firstname => $holdfor_patron->{'firstname'},
83 holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
87 my $fw = GetFrameworkCode($biblionumber);
88 my $showallitems = $query->param('showallitems');
89 my $marcflavour = C4::Context->preference("marcflavour");
91 # XSLT processing of some stuff
92 my $xslfile = C4::Context->preference('XSLTDetailsDisplay');
93 my $lang = $xslfile ? C4::Languages::getlanguage() : undef;
94 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
96 if ( $xslfile ) {
97 $template->param(
98 XSLTDetailsDisplay => '1',
99 XSLTBloc => XSLTParse4Display(
100 $biblionumber, $record, "XSLTDetailsDisplay",
101 1, undef, $sysxml, $xslfile, $lang
106 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
107 $template->param( ocoins => GetCOinSBiblio($record) );
109 # some useful variables for enhanced content;
110 # in each case, we're grabbing the first value we find in
111 # the record and normalizing it
112 my $upc = GetNormalizedUPC($record,$marcflavour);
113 my $ean = GetNormalizedEAN($record,$marcflavour);
114 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
115 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
117 $template->param(
118 normalized_upc => $upc,
119 normalized_ean => $ean,
120 normalized_oclc => $oclc,
121 normalized_isbn => $isbn,
124 my $marcnotesarray = GetMarcNotes( $record, $marcflavour );
125 my $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
126 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
127 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
128 my $marcseriesarray = GetMarcSeries($record,$marcflavour);
129 my $marcurlsarray = GetMarcUrls ($record,$marcflavour);
130 my $marchostsarray = GetMarcHosts($record,$marcflavour);
131 my $subtitle = GetRecordValue('subtitle', $record, $fw);
133 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
135 my $dbh = C4::Context->dbh;
137 my @all_items = GetItemsInfo( $biblionumber );
138 my @items;
139 my $patron = Koha::Patrons->find( $borrowernumber );
140 for my $itm (@all_items) {
141 push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
144 # flag indicating existence of at least one item linked via a host record
145 my $hostrecords;
146 # adding items linked via host biblios
147 my @hostitems = GetHostItemsInfo($record);
148 if (@hostitems){
149 $hostrecords =1;
150 push (@items,@hostitems);
153 my $dat = &GetBiblioData($biblionumber);
155 #coping with subscriptions
156 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
157 my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
158 my @subs;
160 foreach my $subscription (@subscriptions) {
161 my %cell;
162 my $serials_to_display;
163 $cell{subscriptionid} = $subscription->{subscriptionid};
164 $cell{subscriptionnotes} = $subscription->{internalnotes};
165 $cell{missinglist} = $subscription->{missinglist};
166 $cell{librariannote} = $subscription->{librariannote};
167 $cell{branchcode} = $subscription->{branchcode};
168 $cell{hasalert} = $subscription->{hasalert};
169 $cell{callnumber} = $subscription->{callnumber};
170 $cell{closed} = $subscription->{closed};
171 #get the three latest serials.
172 $serials_to_display = $subscription->{staffdisplaycount};
173 $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
174 $cell{staffdisplaycount} = $serials_to_display;
175 $cell{latestserials} =
176 GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
177 push @subs, \%cell;
181 # Get acquisition details
182 if ( C4::Context->preference('AcquisitionDetails') ) {
183 my $orders = C4::Acquisition::GetHistory( biblionumber => $biblionumber, get_canceled_order => 1 );
184 $template->param(
185 orders => $orders,
189 if ( defined $dat->{'itemtype'} ) {
190 $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
193 $dat->{'count'} = scalar @all_items + @hostitems;
194 $dat->{'showncount'} = scalar @items + @hostitems;
195 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
197 my $shelflocations =
198 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
199 my $collections =
200 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
201 my $copynumbers =
202 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
203 my (@itemloop, @otheritemloop, %itemfields);
204 my $norequests = 1;
206 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => { not => undef } });
207 if ( $mss->count ) {
208 $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
210 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => { not => undef } });
211 if ( $mss->count ) {
212 $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
215 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => { not => undef } });
216 my %materials_map;
217 if ($mss->count) {
218 my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
219 if ($materials_authvals) {
220 foreach my $value (@$materials_authvals) {
221 $materials_map{$value->{authorised_value}} = $value->{lib};
226 my $analytics_flag;
227 my $materials_flag; # set this if the items have anything in the materials field
228 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
229 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
230 $template->param(SeparateHoldings => 1);
232 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
233 foreach my $item (@items) {
234 my $itembranchcode = $item->{$separatebranch};
236 # can place holds defaults to yes
237 $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
239 $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
240 : '';
242 $item->{datedue} = format_sqldatetime($item->{datedue});
244 #get shelf location and collection code description if they are authorised value.
245 # same thing for copy number
246 my $shelfcode = $item->{'location'};
247 $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
248 my $ccode = $item->{'ccode'};
249 $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
250 my $copynumber = $item->{'copynumber'};
251 $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
252 foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
253 $itemfields{$_} = 1 if ( $item->{$_} );
256 if (C4::Context->preference('HidePatronName')){
257 $item->{'hidepatronname'} = 1;
261 # checking for holds
262 my $item_object = Koha::Items->find( $item->{itemnumber} );
263 my $holds = $item_object->current_holds;
264 if ( my $first_hold = $holds->next ) {
265 my $ItemBorrowerReserveInfo = C4::Members::GetMember( borrowernumber => $first_hold->borrowernumber); # FIXME could be improved
266 $item->{backgroundcolor} = 'reserved';
267 $item->{reservedate} = $first_hold->reservedate;
268 $item->{ReservedForBorrowernumber} = $first_hold->borrowernumber;
269 $item->{ReservedForSurname} = $ItemBorrowerReserveInfo->{'surname'};
270 $item->{ReservedForFirstname} = $ItemBorrowerReserveInfo->{'firstname'};
271 $item->{ExpectedAtLibrary} = $first_hold->branchcode;
272 $item->{Reservedcardnumber} = $ItemBorrowerReserveInfo->{'cardnumber'};
273 # Check waiting status
274 $item->{waitingdate} = $first_hold->waitingdate;
278 # Check the transit status
279 my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
280 if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
281 $item->{transfertwhen} = $transfertwhen;
282 $item->{transfertfrom} = $transfertfrom;
283 $item->{transfertto} = $transfertto;
284 $item->{nocancel} = 1;
287 foreach my $f (qw( itemnotes )) {
288 if ($item->{$f}) {
289 $item->{$f} =~ s|\n|<br />|g;
290 $itemfields{$f} = 1;
294 #item has a host number if its biblio number does not match the current bib
296 if ($item->{biblionumber} ne $biblionumber){
297 $item->{hostbiblionumber} = $item->{biblionumber};
298 $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
301 #count if item is used in analytical bibliorecords
302 my $countanalytics= GetAnalyticsCount($item->{itemnumber});
303 if ($countanalytics > 0){
304 $analytics_flag=1;
305 $item->{countanalytics} = $countanalytics;
308 if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
309 $materials_flag = 1;
310 if (defined $materials_map{ $item->{materials} }) {
311 $item->{materials} = $materials_map{ $item->{materials} };
315 if ( C4::Context->preference('UseCourseReserves') ) {
316 $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
319 if ( C4::Context->preference('IndependentBranches') ) {
320 my $userenv = C4::Context->userenv();
321 if ( not C4::Context->IsSuperLibrarian()
322 and $userenv->{branch} ne $item->{homebranch} ) {
323 $item->{cannot_be_edited} = 1;
327 if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
328 and C4::Context->preference('SeparateHoldings')) {
329 if ($itembranchcode and $itembranchcode eq $currentbranch) {
330 push @itemloop, $item;
331 } else {
332 push @otheritemloop, $item;
334 } else {
335 push @itemloop, $item;
339 # Display only one tab if one items list is empty
340 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
341 $template->param(SeparateHoldings => 0);
342 if (scalar(@itemloop) == 0) {
343 @itemloop = @otheritemloop;
347 $template->param( norequests => $norequests );
348 $template->param(
349 MARCNOTES => $marcnotesarray,
350 MARCSUBJCTS => $marcsubjctsarray,
351 MARCAUTHORS => $marcauthorsarray,
352 MARCSERIES => $marcseriesarray,
353 MARCURLS => $marcurlsarray,
354 MARCISBNS => $marcisbnsarray,
355 MARCHOSTS => $marchostsarray,
356 subtitle => $subtitle,
357 itemdata_ccode => $itemfields{ccode},
358 itemdata_enumchron => $itemfields{enumchron},
359 itemdata_uri => $itemfields{uri},
360 itemdata_copynumber => $itemfields{copynumber},
361 itemdata_stocknumber => $itemfields{stocknumber},
362 volinfo => $itemfields{enumchron},
363 itemdata_itemnotes => $itemfields{itemnotes},
364 itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
365 z3950_search_params => C4::Search::z3950_search_args($dat),
366 hostrecords => $hostrecords,
367 analytics_flag => $analytics_flag,
368 C4::Search::enabled_staff_search_views,
369 materials => $materials_flag,
372 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
373 my $fieldspec = C4::Context->preference("AlternateHoldingsField");
374 my $subfields = substr $fieldspec, 3;
375 my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
376 my @alternateholdingsinfo = ();
377 my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
379 for my $field (@holdingsfields) {
380 my %holding = ( holding => '' );
381 my $havesubfield = 0;
382 for my $subfield ($field->subfields()) {
383 if ((index $subfields, $$subfield[0]) >= 0) {
384 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
385 $holding{'holding'} .= $$subfield[1];
386 $havesubfield++;
389 if ($havesubfield) {
390 push(@alternateholdingsinfo, \%holding);
394 $template->param(
395 ALTERNATEHOLDINGS => \@alternateholdingsinfo,
399 my @results = ( $dat, );
400 foreach ( keys %{$dat} ) {
401 $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
404 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
405 # method query not found?!?!
406 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
407 $template->param(
408 itemloop => \@itemloop,
409 otheritemloop => \@otheritemloop,
410 biblionumber => $biblionumber,
411 ($analyze? 'analyze':'detailview') =>1,
412 subscriptions => \@subs,
413 subscriptionsnumber => $subscriptionsnumber,
414 subscriptiontitle => $dat->{title},
415 searchid => scalar $query->param('searchid'),
418 # $debug and $template->param(debug_display => 1);
420 # Lists
422 if (C4::Context->preference("virtualshelves") ) {
423 my $shelves = Koha::Virtualshelves->search(
425 biblionumber => $biblionumber,
426 category => 2,
429 join => 'virtualshelfcontents',
432 $template->param( 'shelves' => $shelves );
435 # XISBN Stuff
436 if (C4::Context->preference("FRBRizeEditions")==1) {
437 eval {
438 $template->param(
439 XISBNS => scalar get_xisbns($isbn)
442 if ($@) { warn "XISBN Failed $@"; }
445 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
446 my @images = ListImagesForBiblio($biblionumber);
447 $template->{VARS}->{localimages} = \@images;
450 # HTML5 Media
451 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
452 $template->param( C4::HTML5Media->gethtml5media($record));
455 # Displaying tags
457 my $tag_quantity;
458 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
459 $template->param(
460 TagsEnabled => 1,
461 TagsShowOnDetail => $tag_quantity
463 $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
464 'sort'=>'-weight', limit=>$tag_quantity}));
467 #we only need to pass the number of holds to the template
468 my $biblio = Koha::Biblios->find( $biblionumber );
469 my $holds = $biblio->holds;
470 $template->param( holdcount => $holds->count );
472 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
473 if ($StaffDetailItemSelection) {
474 # Only enable item selection if user can execute at least one action
475 if (
476 $flags->{superlibrarian}
477 || (
478 ref $flags->{tools} eq 'HASH' && (
479 $flags->{tools}->{items_batchmod} # Modify selected items
480 || $flags->{tools}->{items_batchdel} # Delete selected items
483 || ( ref $flags->{tools} eq '' && $flags->{tools} )
486 $template->param(
487 StaffDetailItemSelection => $StaffDetailItemSelection );
491 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
492 my @deletedorders_using_biblio;
493 my @orders_using_biblio;
494 my @baskets_orders;
495 my @baskets_deletedorders;
497 foreach my $myorder (@allorders_using_biblio) {
498 my $basket = $myorder->{'basketno'};
499 if ((defined $myorder->{'datecancellationprinted'}) and ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
500 push @deletedorders_using_biblio, $myorder;
501 unless (grep(/^$basket$/, @baskets_deletedorders)){
502 push @baskets_deletedorders,$myorder->{'basketno'};
505 else {
506 push @orders_using_biblio, $myorder;
507 unless (grep(/^$basket$/, @baskets_orders)){
508 push @baskets_orders,$myorder->{'basketno'};
513 my $count_orders_using_biblio = scalar @orders_using_biblio ;
514 $template->param (countorders => $count_orders_using_biblio);
516 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
517 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
519 $template->param (basketsorders => \@baskets_orders);
520 $template->param (basketsdeletedorders => \@baskets_deletedorders);
522 output_html_with_http_headers $query, $cookie, $template->output;