Bug 23414: Unit tests
[koha.git] / catalogue / detail.pl
blob3e2ca01cf59e78cabad1cdc58664d7499e1238ec
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 Try::Tiny;
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;
52 my $query = CGI->new();
54 my $analyze = $query->param('analyze');
56 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
58 template_name => 'catalogue/detail.tt',
59 query => $query,
60 type => "intranet",
61 authnotrequired => 0,
62 flagsrequired => { catalogue => 1 },
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 });
74 my @tab_plugins = Koha::Plugins->new()->GetPlugins({
75 method => 'intranet_catalog_biblio_tab',
76 });
77 my @tabs;
78 foreach my $tab_plugin (@tab_plugins) {
79 my @biblio_tabs;
81 try {
82 @biblio_tabs = $tab_plugin->intranet_catalog_biblio_tab();
83 foreach my $tab (@biblio_tabs) {
84 my $tab_id = 'tab-' . $tab->title;
85 $tab_id =~ s/[^0-9A-Za-z]+/-/g;
86 $tab->id( $tab_id );
87 push @tabs, $tab,
90 catch {
91 warn "Error calling 'intranet_catalog_biblio_tab' on the " . $tab_plugin->{class} . "plugin ($_)";
95 $template->param(
96 plugins => \@plugins,
97 tabs => \@tabs,
101 my $biblionumber = $query->param('biblionumber');
102 $biblionumber = HTML::Entities::encode($biblionumber);
103 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
104 my $biblio = Koha::Biblios->find( $biblionumber );
105 $template->param( 'biblio', $biblio );
107 if ( not defined $record ) {
108 # biblionumber invalid -> report and exit
109 $template->param( unknownbiblionumber => 1,
110 biblionumber => $biblionumber );
111 output_html_with_http_headers $query, $cookie, $template->output;
112 exit;
115 if($query->cookie("holdfor")){
116 my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") );
117 $template->param(
118 # FIXME Should pass the patron object
119 holdfor => $query->cookie("holdfor"),
120 holdfor_surname => $holdfor_patron->surname,
121 holdfor_firstname => $holdfor_patron->firstname,
122 holdfor_cardnumber => $holdfor_patron->cardnumber,
126 my $fw = GetFrameworkCode($biblionumber);
127 my $showallitems = $query->param('showallitems');
128 my $marcflavour = C4::Context->preference("marcflavour");
130 # XSLT processing of some stuff
131 my $xslfile = C4::Context->preference('XSLTDetailsDisplay') || "default";
132 my $lang = $xslfile ? C4::Languages::getlanguage() : undef;
133 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
135 if ( $xslfile ) {
136 $template->param(
137 XSLTDetailsDisplay => '1',
138 XSLTBloc => XSLTParse4Display(
139 $biblionumber, $record, "XSLTDetailsDisplay",
140 1, undef, $sysxml, $xslfile, $lang
145 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
146 $template->param( ocoins => $biblio->get_coins );
148 # some useful variables for enhanced content;
149 # in each case, we're grabbing the first value we find in
150 # the record and normalizing it
151 my $upc = GetNormalizedUPC($record,$marcflavour);
152 my $ean = GetNormalizedEAN($record,$marcflavour);
153 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
154 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
156 $template->param(
157 normalized_upc => $upc,
158 normalized_ean => $ean,
159 normalized_oclc => $oclc,
160 normalized_isbn => $isbn,
163 my $marcnotesarray = GetMarcNotes( $record, $marcflavour );
164 my $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
165 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
166 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
167 my $marcseriesarray = GetMarcSeries($record,$marcflavour);
168 my $marcurlsarray = GetMarcUrls ($record,$marcflavour);
169 my $marchostsarray = GetMarcHosts($record,$marcflavour);
171 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
173 my $dbh = C4::Context->dbh;
175 my @all_items = GetItemsInfo( $biblionumber );
176 my @items;
177 my $patron = Koha::Patrons->find( $borrowernumber );
178 for my $itm (@all_items) {
179 push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
182 # flag indicating existence of at least one item linked via a host record
183 my $hostrecords;
184 # adding items linked via host biblios
185 my @hostitems = GetHostItemsInfo($record);
186 if (@hostitems){
187 $hostrecords =1;
188 push (@items,@hostitems);
191 my $dat = &GetBiblioData($biblionumber);
193 #coping with subscriptions
194 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
195 my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
196 my @subs;
198 foreach my $subscription (@subscriptions) {
199 my %cell;
200 my $serials_to_display;
201 $cell{subscriptionid} = $subscription->{subscriptionid};
202 $cell{subscriptionnotes} = $subscription->{internalnotes};
203 $cell{missinglist} = $subscription->{missinglist};
204 $cell{librariannote} = $subscription->{librariannote};
205 $cell{branchcode} = $subscription->{branchcode};
206 $cell{hasalert} = $subscription->{hasalert};
207 $cell{callnumber} = $subscription->{callnumber};
208 $cell{location} = $subscription->{location};
209 $cell{closed} = $subscription->{closed};
210 #get the three latest serials.
211 $serials_to_display = $subscription->{staffdisplaycount};
212 $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
213 $cell{staffdisplaycount} = $serials_to_display;
214 $cell{latestserials} =
215 GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
216 push @subs, \%cell;
220 # Get acquisition details
221 if ( C4::Context->preference('AcquisitionDetails') ) {
222 my $orders = Koha::Acquisition::Orders->search(
223 { biblionumber => $biblionumber },
225 join => 'basketno',
226 order_by => 'basketno.booksellerid'
228 ); # GetHistory sorted by aqbooksellerid, but does it make sense?
230 $template->param(
231 orders => $orders,
235 if ( defined $dat->{'itemtype'} ) {
236 $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
239 $dat->{'count'} = scalar @all_items + @hostitems;
240 $dat->{'showncount'} = scalar @items + @hostitems;
241 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
243 my $shelflocations =
244 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
245 my $collections =
246 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
247 my $copynumbers =
248 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
249 my (@itemloop, @otheritemloop, %itemfields);
250 my $norequests = 1;
252 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
253 if ( $mss->count ) {
254 $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
256 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
257 if ( $mss->count ) {
258 $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
260 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
261 if ( $mss->count ) {
262 $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
265 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
266 my %materials_map;
267 if ($mss->count) {
268 my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
269 if ($materials_authvals) {
270 foreach my $value (@$materials_authvals) {
271 $materials_map{$value->{authorised_value}} = $value->{lib};
276 my $analytics_flag;
277 my $materials_flag; # set this if the items have anything in the materials field
278 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
279 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
280 $template->param(SeparateHoldings => 1);
282 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
283 foreach my $item (@items) {
284 my $itembranchcode = $item->{$separatebranch};
286 # can place holds defaults to yes
287 $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
289 $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
290 : '';
292 $item->{datedue} = format_sqldatetime($item->{datedue});
294 #get shelf location and collection code description if they are authorised value.
295 # same thing for copy number
296 my $shelfcode = $item->{'location'};
297 $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
298 my $ccode = $item->{'ccode'};
299 $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
300 my $copynumber = $item->{'copynumber'};
301 $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
302 foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
303 $itemfields{$_} = 1 if ( $item->{$_} );
306 # checking for holds
307 my $item_object = Koha::Items->find( $item->{itemnumber} );
308 my $holds = $item_object->current_holds;
309 if ( my $first_hold = $holds->next ) {
310 my $patron = Koha::Patrons->find( $first_hold->borrowernumber );
311 $item->{backgroundcolor} = 'reserved';
312 $item->{reservedate} = $first_hold->reservedate;
313 $item->{ReservedFor} = $patron,
314 $item->{ExpectedAtLibrary} = $first_hold->branchcode;
315 # Check waiting status
316 $item->{waitingdate} = $first_hold->waitingdate;
319 if ( my $checkout = $item_object->checkout ) {
320 $item->{CheckedOutFor} = $checkout->patron;
323 # Check the transit status
324 my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
325 if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
326 $item->{transfertwhen} = $transfertwhen;
327 $item->{transfertfrom} = $transfertfrom;
328 $item->{transfertto} = $transfertto;
329 $item->{nocancel} = 1;
332 foreach my $f (qw( itemnotes )) {
333 if ($item->{$f}) {
334 $item->{$f} =~ s|\n|<br />|g;
335 $itemfields{$f} = 1;
339 #item has a host number if its biblio number does not match the current bib
341 if ($item->{biblionumber} ne $biblionumber){
342 $item->{hostbiblionumber} = $item->{biblionumber};
343 $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
347 if ( $analyze ) {
348 # count if item is used in analytical bibliorecords
349 # The 'countanalytics' flag is only used in the templates if analyze is set
350 my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
351 if ($countanalytics > 0){
352 $analytics_flag=1;
353 $item->{countanalytics} = $countanalytics;
357 if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
358 $materials_flag = 1;
359 if (defined $materials_map{ $item->{materials} }) {
360 $item->{materials} = $materials_map{ $item->{materials} };
364 if ( C4::Context->preference('UseCourseReserves') ) {
365 $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
368 if ( C4::Context->preference('IndependentBranches') ) {
369 my $userenv = C4::Context->userenv();
370 if ( not C4::Context->IsSuperLibrarian()
371 and $userenv->{branch} ne $item->{homebranch} ) {
372 $item->{cannot_be_edited} = 1;
376 if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
377 and C4::Context->preference('SeparateHoldings')) {
378 if ($itembranchcode and $itembranchcode eq $currentbranch) {
379 push @itemloop, $item;
380 } else {
381 push @otheritemloop, $item;
383 } else {
384 push @itemloop, $item;
388 # Display only one tab if one items list is empty
389 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
390 $template->param(SeparateHoldings => 0);
391 if (scalar(@itemloop) == 0) {
392 @itemloop = @otheritemloop;
396 $template->param( norequests => $norequests );
397 $template->param(
398 MARCNOTES => $marcnotesarray,
399 MARCSUBJCTS => $marcsubjctsarray,
400 MARCAUTHORS => $marcauthorsarray,
401 MARCSERIES => $marcseriesarray,
402 MARCURLS => $marcurlsarray,
403 MARCISBNS => $marcisbnsarray,
404 MARCHOSTS => $marchostsarray,
405 itemdata_ccode => $itemfields{ccode},
406 itemdata_enumchron => $itemfields{enumchron},
407 itemdata_uri => $itemfields{uri},
408 itemdata_copynumber => $itemfields{copynumber},
409 itemdata_stocknumber => $itemfields{stocknumber},
410 volinfo => $itemfields{enumchron},
411 itemdata_itemnotes => $itemfields{itemnotes},
412 itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
413 z3950_search_params => C4::Search::z3950_search_args($dat),
414 hostrecords => $hostrecords,
415 analytics_flag => $analytics_flag,
416 C4::Search::enabled_staff_search_views,
417 materials => $materials_flag,
420 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
421 my $fieldspec = C4::Context->preference("AlternateHoldingsField");
422 my $subfields = substr $fieldspec, 3;
423 my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
424 my @alternateholdingsinfo = ();
425 my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
427 for my $field (@holdingsfields) {
428 my %holding = ( holding => '' );
429 my $havesubfield = 0;
430 for my $subfield ($field->subfields()) {
431 if ((index $subfields, $$subfield[0]) >= 0) {
432 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
433 $holding{'holding'} .= $$subfield[1];
434 $havesubfield++;
437 if ($havesubfield) {
438 push(@alternateholdingsinfo, \%holding);
442 $template->param(
443 ALTERNATEHOLDINGS => \@alternateholdingsinfo,
447 my @results = ( $dat, );
448 foreach ( keys %{$dat} ) {
449 $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
452 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
453 # method query not found?!?!
454 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
455 $template->param(
456 itemloop => \@itemloop,
457 otheritemloop => \@otheritemloop,
458 biblionumber => $biblionumber,
459 ($analyze? 'analyze':'detailview') =>1,
460 subscriptions => \@subs,
461 subscriptionsnumber => $subscriptionsnumber,
462 subscriptiontitle => $dat->{title},
463 searchid => scalar $query->param('searchid'),
466 # $debug and $template->param(debug_display => 1);
468 # Lists
470 if (C4::Context->preference("virtualshelves") ) {
471 my $shelves = Koha::Virtualshelves->search(
473 biblionumber => $biblionumber,
474 category => 2,
477 join => 'virtualshelfcontents',
480 $template->param( 'shelves' => $shelves );
483 # XISBN Stuff
484 if (C4::Context->preference("FRBRizeEditions")==1) {
485 eval {
486 $template->param(
487 XISBNS => scalar get_xisbns($isbn, $biblionumber)
490 if ($@) { warn "XISBN Failed $@"; }
493 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
494 my @images = ListImagesForBiblio($biblionumber);
495 $template->{VARS}->{localimages} = \@images;
498 # HTML5 Media
499 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
500 $template->param( C4::HTML5Media->gethtml5media($record));
503 # Displaying tags
505 my $tag_quantity;
506 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
507 $template->param(
508 TagsEnabled => 1,
509 TagsShowOnDetail => $tag_quantity
511 $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
512 'sort'=>'-weight', limit=>$tag_quantity}));
515 #we only need to pass the number of holds to the template
516 my $holds = $biblio->holds;
517 $template->param( holdcount => $holds->count );
519 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
520 if ($StaffDetailItemSelection) {
521 # Only enable item selection if user can execute at least one action
522 if (
523 $flags->{superlibrarian}
524 || (
525 ref $flags->{tools} eq 'HASH' && (
526 $flags->{tools}->{items_batchmod} # Modify selected items
527 || $flags->{tools}->{items_batchdel} # Delete selected items
530 || ( ref $flags->{tools} eq '' && $flags->{tools} )
533 $template->param(
534 StaffDetailItemSelection => $StaffDetailItemSelection );
538 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
539 my @deletedorders_using_biblio;
540 my @orders_using_biblio;
541 my @baskets_orders;
542 my @baskets_deletedorders;
544 foreach my $myorder (@allorders_using_biblio) {
545 my $basket = $myorder->{'basketno'};
546 if ((defined $myorder->{'datecancellationprinted'}) and ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
547 push @deletedorders_using_biblio, $myorder;
548 unless (grep(/^$basket$/, @baskets_deletedorders)){
549 push @baskets_deletedorders,$myorder->{'basketno'};
552 else {
553 push @orders_using_biblio, $myorder;
554 unless (grep(/^$basket$/, @baskets_orders)){
555 push @baskets_orders,$myorder->{'basketno'};
560 $template->param(biblio => $biblio);
562 my $count_orders_using_biblio = scalar @orders_using_biblio ;
563 $template->param (countorders => $count_orders_using_biblio);
565 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
566 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
568 $template->param (basketsorders => \@baskets_orders);
569 $template->param (basketsdeletedorders => \@baskets_deletedorders);
571 output_html_with_http_headers $query, $cookie, $template->output;