Bug 20623: Fix basket group PDF when itemtype not itemtype table
[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::Serials;
33 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
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
50 my $query = CGI->new();
51
52 my $analyze = $query->param('analyze');
53
54 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
55     {
56     template_name   =>  'catalogue/detail.tt',
57         query           => $query,
58         type            => "intranet",
59         authnotrequired => 0,
60         flagsrequired   => { catalogue => 1 },
61     }
62 );
63
64 my $biblionumber = $query->param('biblionumber');
65 $biblionumber = HTML::Entities::encode($biblionumber);
66 my $record       = GetMarcBiblio({ biblionumber => $biblionumber });
67
68 if ( not defined $record ) {
69     # biblionumber invalid -> report and exit
70     $template->param( unknownbiblionumber => 1,
71                       biblionumber => $biblionumber );
72     output_html_with_http_headers $query, $cookie, $template->output;
73     exit;
74 }
75
76 if($query->cookie("holdfor")){ 
77     my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") );
78     $template->param(
79         # FIXME Should pass the patron object
80         holdfor => $query->cookie("holdfor"),
81         holdfor_surname => $holdfor_patron->surname,
82         holdfor_firstname => $holdfor_patron->firstname,
83         holdfor_cardnumber => $holdfor_patron->cardnumber,
84     );
85 }
86
87 my $fw           = GetFrameworkCode($biblionumber);
88 my $showallitems = $query->param('showallitems');
89 my $marcflavour  = C4::Context->preference("marcflavour");
90
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;
95
96 if ( $xslfile ) {
97     $template->param(
98         XSLTDetailsDisplay => '1',
99         XSLTBloc => XSLTParse4Display(
100                         $biblionumber, $record, "XSLTDetailsDisplay",
101                         1, undef, $sysxml, $xslfile, $lang
102                     )
103     );
104 }
105
106 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
107 $template->param( ocoins => GetCOinSBiblio($record) );
108
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);
116
117 $template->param(
118     normalized_upc => $upc,
119     normalized_ean => $ean,
120     normalized_oclc => $oclc,
121     normalized_isbn => $isbn,
122 );
123
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);
132
133 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
134
135 my $dbh = C4::Context->dbh;
136
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);
142 }
143
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);
151 }
152
153 my $dat = &GetBiblioData($biblionumber);
154
155 #coping with subscriptions
156 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
157 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
158 my @subs;
159
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;
178 }
179
180
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,
186     );
187 }
188
189 if ( defined $dat->{'itemtype'} ) {
190     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
191 }
192
193 $dat->{'count'} = scalar @all_items + @hostitems;
194 $dat->{'showncount'} = scalar @items + @hostitems;
195 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
196
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;
205
206 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
207 if ( $mss->count ) {
208     $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
209 }
210 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
211 if ( $mss->count ) {
212     $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
213 }
214 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
215 if ( $mss->count ) {
216     $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
217 }
218
219 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
220 my %materials_map;
221 if ($mss->count) {
222     my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
223     if ($materials_authvals) {
224         foreach my $value (@$materials_authvals) {
225             $materials_map{$value->{authorised_value}} = $value->{lib};
226         }
227     }
228 }
229
230 my $analytics_flag;
231 my $materials_flag; # set this if the items have anything in the materials field
232 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
233 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
234     $template->param(SeparateHoldings => 1);
235 }
236 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
237 foreach my $item (@items) {
238     my $itembranchcode = $item->{$separatebranch};
239
240     # can place holds defaults to yes
241     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
242
243     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
244                                                : '';
245
246     $item->{datedue} = format_sqldatetime($item->{datedue});
247
248     #get shelf location and collection code description if they are authorised value.
249     # same thing for copy number
250     my $shelfcode = $item->{'location'};
251     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
252     my $ccode = $item->{'ccode'};
253     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
254     my $copynumber = $item->{'copynumber'};
255     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
256     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
257         $itemfields{$_} = 1 if ( $item->{$_} );
258     }
259
260     if (C4::Context->preference('HidePatronName')){
261         $item->{'hidepatronname'} = 1;
262     }
263
264
265     # checking for holds
266     my $item_object = Koha::Items->find( $item->{itemnumber} );
267     my $holds = $item_object->current_holds;
268     if ( my $first_hold = $holds->next ) {
269         my $patron = Koha::Patrons->find( $first_hold->borrowernumber );
270         $item->{backgroundcolor} = 'reserved';
271         $item->{reservedate}     = $first_hold->reservedate;
272         $item->{ReservedForBorrowernumber}     = $first_hold->borrowernumber;
273         $item->{ReservedForSurname}     = $patron->surname;
274         $item->{ReservedForFirstname}   = $patron->firstname;
275         $item->{ExpectedAtLibrary}      = $first_hold->branchcode;
276         $item->{Reservedcardnumber}     = $patron->cardnumber;
277         # Check waiting status
278         $item->{waitingdate} = $first_hold->waitingdate;
279     }
280
281
282         # Check the transit status
283     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
284     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
285         $item->{transfertwhen} = $transfertwhen;
286         $item->{transfertfrom} = $transfertfrom;
287         $item->{transfertto}   = $transfertto;
288         $item->{nocancel} = 1;
289     }
290
291     foreach my $f (qw( itemnotes )) {
292         if ($item->{$f}) {
293             $item->{$f} =~ s|\n|<br />|g;
294             $itemfields{$f} = 1;
295         }
296     }
297
298     #item has a host number if its biblio number does not match the current bib
299
300     if ($item->{biblionumber} ne $biblionumber){
301         $item->{hostbiblionumber} = $item->{biblionumber};
302         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
303     }
304         
305
306     if ( $analyze ) {
307         # count if item is used in analytical bibliorecords
308         # The 'countanalytics' flag is only used in the templates if analyze is set
309         my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
310         if ($countanalytics > 0){
311             $analytics_flag=1;
312             $item->{countanalytics} = $countanalytics;
313         }
314     }
315
316     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
317         $materials_flag = 1;
318         if (defined $materials_map{ $item->{materials} }) {
319             $item->{materials} = $materials_map{ $item->{materials} };
320         }
321     }
322
323     if ( C4::Context->preference('UseCourseReserves') ) {
324         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
325     }
326
327     if ( C4::Context->preference('IndependentBranches') ) {
328         my $userenv = C4::Context->userenv();
329         if ( not C4::Context->IsSuperLibrarian()
330             and $userenv->{branch} ne $item->{homebranch} ) {
331             $item->{cannot_be_edited} = 1;
332         }
333     }
334
335     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
336     and C4::Context->preference('SeparateHoldings')) {
337         if ($itembranchcode and $itembranchcode eq $currentbranch) {
338             push @itemloop, $item;
339         } else {
340             push @otheritemloop, $item;
341         }
342     } else {
343         push @itemloop, $item;
344     }
345 }
346
347 # Display only one tab if one items list is empty
348 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
349     $template->param(SeparateHoldings => 0);
350     if (scalar(@itemloop) == 0) {
351         @itemloop = @otheritemloop;
352     }
353 }
354
355 $template->param( norequests => $norequests );
356 $template->param(
357         MARCNOTES   => $marcnotesarray,
358         MARCSUBJCTS => $marcsubjctsarray,
359         MARCAUTHORS => $marcauthorsarray,
360         MARCSERIES  => $marcseriesarray,
361         MARCURLS => $marcurlsarray,
362     MARCISBNS => $marcisbnsarray,
363         MARCHOSTS => $marchostsarray,
364         subtitle    => $subtitle,
365         itemdata_ccode      => $itemfields{ccode},
366         itemdata_enumchron  => $itemfields{enumchron},
367         itemdata_uri        => $itemfields{uri},
368         itemdata_copynumber => $itemfields{copynumber},
369         itemdata_stocknumber => $itemfields{stocknumber},
370         volinfo                         => $itemfields{enumchron},
371         itemdata_itemnotes  => $itemfields{itemnotes},
372         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
373         z3950_search_params     => C4::Search::z3950_search_args($dat),
374         hostrecords         => $hostrecords,
375         analytics_flag  => $analytics_flag,
376         C4::Search::enabled_staff_search_views,
377         materials       => $materials_flag,
378 );
379
380 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
381     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
382     my $subfields = substr $fieldspec, 3;
383     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
384     my @alternateholdingsinfo = ();
385     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
386
387     for my $field (@holdingsfields) {
388         my %holding = ( holding => '' );
389         my $havesubfield = 0;
390         for my $subfield ($field->subfields()) {
391             if ((index $subfields, $$subfield[0]) >= 0) {
392                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
393                 $holding{'holding'} .= $$subfield[1];
394                 $havesubfield++;
395             }
396         }
397         if ($havesubfield) {
398             push(@alternateholdingsinfo, \%holding);
399         }
400     }
401
402     $template->param(
403         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
404         );
405 }
406
407 my @results = ( $dat, );
408 foreach ( keys %{$dat} ) {
409     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
410 }
411
412 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
413 # method query not found?!?!
414 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
415 $template->param(
416     itemloop        => \@itemloop,
417     otheritemloop   => \@otheritemloop,
418     biblionumber        => $biblionumber,
419     ($analyze? 'analyze':'detailview') =>1,
420     subscriptions       => \@subs,
421     subscriptionsnumber => $subscriptionsnumber,
422     subscriptiontitle   => $dat->{title},
423     searchid            => scalar $query->param('searchid'),
424 );
425
426 # $debug and $template->param(debug_display => 1);
427
428 # Lists
429
430 if (C4::Context->preference("virtualshelves") ) {
431     my $shelves = Koha::Virtualshelves->search(
432         {
433             biblionumber => $biblionumber,
434             category => 2,
435         },
436         {
437             join => 'virtualshelfcontents',
438         }
439     );
440     $template->param( 'shelves' => $shelves );
441 }
442
443 # XISBN Stuff
444 if (C4::Context->preference("FRBRizeEditions")==1) {
445     eval {
446         $template->param(
447             XISBNS => scalar get_xisbns($isbn)
448         );
449     };
450     if ($@) { warn "XISBN Failed $@"; }
451 }
452
453 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
454     my @images = ListImagesForBiblio($biblionumber);
455     $template->{VARS}->{localimages} = \@images;
456 }
457
458 # HTML5 Media
459 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
460     $template->param( C4::HTML5Media->gethtml5media($record));
461 }
462
463 # Displaying tags
464
465 my $tag_quantity;
466 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
467     $template->param(
468         TagsEnabled => 1,
469         TagsShowOnDetail => $tag_quantity
470     );
471     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
472                                 'sort'=>'-weight', limit=>$tag_quantity}));
473 }
474
475 #we only need to pass the number of holds to the template
476 my $biblio = Koha::Biblios->find( $biblionumber );
477 my $holds = $biblio->holds;
478 $template->param( holdcount => $holds->count );
479
480 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
481 if ($StaffDetailItemSelection) {
482     # Only enable item selection if user can execute at least one action
483     if (
484         $flags->{superlibrarian}
485         || (
486             ref $flags->{tools} eq 'HASH' && (
487                 $flags->{tools}->{items_batchmod}       # Modify selected items
488                 || $flags->{tools}->{items_batchdel}    # Delete selected items
489             )
490         )
491         || ( ref $flags->{tools} eq '' && $flags->{tools} )
492       )
493     {
494         $template->param(
495             StaffDetailItemSelection => $StaffDetailItemSelection );
496     }
497 }
498
499 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
500 my @deletedorders_using_biblio;
501 my @orders_using_biblio;
502 my @baskets_orders;
503 my @baskets_deletedorders;
504
505 foreach my $myorder (@allorders_using_biblio) {
506     my $basket = $myorder->{'basketno'};
507     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
508         push @deletedorders_using_biblio, $myorder;
509         unless (grep(/^$basket$/, @baskets_deletedorders)){
510             push @baskets_deletedorders,$myorder->{'basketno'};
511         }
512     }
513     else {
514         push @orders_using_biblio, $myorder;
515         unless (grep(/^$basket$/, @baskets_orders)){
516             push @baskets_orders,$myorder->{'basketno'};
517             }
518     }
519 }
520
521 my $count_orders_using_biblio = scalar @orders_using_biblio ;
522 $template->param (countorders => $count_orders_using_biblio);
523
524 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
525 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
526
527 $template->param (basketsorders => \@baskets_orders);
528 $template->param (basketsdeletedorders => \@baskets_deletedorders);
529
530 output_html_with_http_headers $query, $cookie, $template->output;