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