3 # Copyright (C) 2006 LibLime
4 # <jmf at liblime dot com>
5 # Parts Copyright Katrin Fischer 2011
6 # Parts Copyright ByWater Solutions 2011
7 # Parts Copyright Biblibre 2012
9 # This file is part of Koha.
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
27 use C4::Koha qw( xml_escape );
28 use C4::Biblio qw( GetAuthorisedValueDesc GetFrameworkCode GetMarcStructure );
29 use Koha::AuthorisedValues;
35 my $engine; #XSLT Handler object
36 my %authval_per_framework;
37 # Cache for tagfield-tagsubfield to decode per framework.
38 # Should be preferably be placed in Koha-core...
40 our (@ISA, @EXPORT_OK);
46 getAuthorisedValues4MARCSubfields
47 buildKohaItemsNamespace
50 $engine=Koha::XSLT::Base->new( { do_not_return_source => 1 } );
55 C4::XSLT - Functions for displaying XSLT-generated content
59 =head2 transformMARCXML4XSLT
61 Replaces codes with authorized values in a MARC::Record object
65 sub transformMARCXML4XSLT {
66 my ($biblionumber, $record, $opac) = @_;
67 my $frameworkcode = GetFrameworkCode($biblionumber) || '';
68 my $tagslib = &GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
70 # FIXME: wish there was a better way to handle exceptions
72 @fields = $record->fields();
74 if ($@) { warn "PROBLEM WITH RECORD"; next; }
75 my $marcflavour = C4::Context->preference('marcflavour');
76 my $av = getAuthorisedValues4MARCSubfields($frameworkcode);
77 foreach my $tag ( keys %$av ) {
78 foreach my $field ( $record->field( $tag ) ) {
79 if ( $av->{ $tag } ) {
80 my @new_subfields = ();
81 for my $subfield ( $field->subfields() ) {
82 my ( $letter, $value ) = @$subfield;
83 # Replace the field value with the authorised value *except* for MARC21 field 942$n (suppression in opac)
84 if ( !( $tag eq '942' && $subfield->[0] eq 'n' ) || $marcflavour eq 'UNIMARC' ) {
85 $value = GetAuthorisedValueDesc( $tag, $letter, $value, '', $tagslib, undef, $opac )
86 if $av->{ $tag }->{ $letter };
88 push( @new_subfields, $letter, $value );
90 $field ->replace_with( MARC::Field->new(
102 =head2 getAuthorisedValues4MARCSubfields
104 Returns a ref of hash of ref of hash for tag -> letter controlled by authorised values
105 Is only used in this module currently.
109 sub getAuthorisedValues4MARCSubfields {
110 my ($frameworkcode) = @_;
111 unless ( $authval_per_framework{ $frameworkcode } ) {
112 my $dbh = C4::Context->dbh;
113 my $sth = $dbh->prepare("SELECT DISTINCT tagfield, tagsubfield
114 FROM marc_subfield_structure
115 WHERE authorised_value IS NOT NULL
116 AND authorised_value!=''
117 AND frameworkcode=?");
118 $sth->execute( $frameworkcode );
120 while ( my ( $tag, $letter ) = $sth->fetchrow() ) {
121 $av->{ $tag }->{ $letter } = 1;
123 $authval_per_framework{ $frameworkcode } = $av;
125 return $authval_per_framework{ $frameworkcode };
128 =head2 XSLTParse4Display
130 Returns xml for biblionumber and requested XSLT transformation.
131 Returns undef if the transform fails.
133 Used in OPAC results and detail, intranet results and detail, list display.
134 (Depending on the settings of your XSLT preferences.)
136 The helper function _get_best_default_xslt_filename is used in a unit test.
140 sub _get_best_default_xslt_filename {
141 my ($htdocs, $theme, $lang, $base_xslfile) = @_;
144 "$htdocs/$theme/$lang/xslt/${base_xslfile}", # exact match
145 "$htdocs/$theme/en/xslt/${base_xslfile}", # if not, preferred theme in English
146 "$htdocs/prog/$lang/xslt/${base_xslfile}", # if not, 'prog' theme in preferred language
147 "$htdocs/prog/en/xslt/${base_xslfile}", # otherwise, prog theme in English; should always
151 foreach my $filename (@candidates) {
152 $xslfilename = $filename;
154 last; # we have a winner!
160 sub get_xslt_sysprefs {
161 my $sysxml = "<sysprefs>\n";
162 foreach my $syspref ( qw/ hidelostitems OPACURLOpenInNewWindow
163 DisplayOPACiconsXSLT URLLinkText viewISBD
164 OPACBaseURL TraceCompleteSubfields UseICUStyleQuotes
165 UseAuthoritiesForTracings TraceSubjectSubdivisions
166 Display856uAsImage OPACDisplay856uAsImage
167 UseControlNumber IntranetBiblioDefaultView BiblioDefaultView
168 OPACItemLocation DisplayIconsXSLT
169 AlternateHoldingsField AlternateHoldingsSeparator
170 TrackClicks opacthemes IdRef OpacSuppression
171 OPACResultsLibrary OPACShowOpenURL
172 OpenURLResolverURL OpenURLImageLocation
173 OPACResultsMaxItems OPACResultsMaxItemsUnavailable OPACResultsUnavailableGroupingBy
174 OpenURLText OPACShowMusicalInscripts OPACPlayMusicalInscripts / )
176 my $sp = C4::Context->preference( $syspref );
177 next unless defined($sp);
178 $sysxml .= "<syspref name=\"$syspref\">$sp</syspref>\n";
181 # singleBranchMode was a system preference, but no longer is
182 # we can retain it here for compatibility
183 my $singleBranchMode = Koha::Libraries->search->count == 1 ? 1 : 0;
184 $sysxml .= "<syspref name=\"singleBranchMode\">$singleBranchMode</syspref>\n";
186 $sysxml .= "</sysprefs>\n";
190 sub get_xsl_filename {
191 my ( $xslsyspref ) = @_;
193 my $lang = C4::Languages::getlanguage();
195 my $xslfilename = C4::Context->preference($xslsyspref) || "default";
197 if ( $xslfilename =~ /^\s*"?default"?\s*$/i ) {
199 my ( $htdocs, $theme, $xslfile );
201 if ($xslsyspref eq "XSLTDetailsDisplay") {
202 $htdocs = C4::Context->config('intrahtdocs');
203 $theme = C4::Context->preference("template");
204 $xslfile = C4::Context->preference('marcflavour') .
205 "slim2intranetDetail.xsl";
206 } elsif ($xslsyspref eq "XSLTResultsDisplay") {
207 $htdocs = C4::Context->config('intrahtdocs');
208 $theme = C4::Context->preference("template");
209 $xslfile = C4::Context->preference('marcflavour') .
210 "slim2intranetResults.xsl";
211 } elsif ($xslsyspref eq "OPACXSLTDetailsDisplay") {
212 $htdocs = C4::Context->config('opachtdocs');
213 $theme = C4::Context->preference("opacthemes");
214 $xslfile = C4::Context->preference('marcflavour') .
215 "slim2OPACDetail.xsl";
216 } elsif ($xslsyspref eq "OPACXSLTResultsDisplay") {
217 $htdocs = C4::Context->config('opachtdocs');
218 $theme = C4::Context->preference("opacthemes");
219 $xslfile = C4::Context->preference('marcflavour') .
220 "slim2OPACResults.xsl";
221 } elsif ($xslsyspref eq 'XSLTListsDisplay') {
222 # Lists default to *Results.xslt
223 $htdocs = C4::Context->config('intrahtdocs');
224 $theme = C4::Context->preference("template");
225 $xslfile = C4::Context->preference('marcflavour') .
226 "slim2intranetResults.xsl";
227 } elsif ($xslsyspref eq 'OPACXSLTListsDisplay') {
228 # Lists default to *Results.xslt
229 $htdocs = C4::Context->config('opachtdocs');
230 $theme = C4::Context->preference("opacthemes");
231 $xslfile = C4::Context->preference('marcflavour') .
232 "slim2OPACResults.xsl";
234 $xslfilename = _get_best_default_xslt_filename($htdocs, $theme, $lang, $xslfile);
237 if ( $xslfilename =~ m/\{langcode\}/ ) {
238 $xslfilename =~ s/\{langcode\}/$lang/;
244 sub XSLTParse4Display {
247 my $biblionumber = $params->{biblionumber};
248 my $orig_record = $params->{record};
249 my $xslsyspref = $params->{xsl_syspref};
250 my $fixamps = $params->{fix_amps};
251 my $hidden_items = $params->{hidden_items} || [];
252 my $variables = $params->{xslt_variables};
253 my $items_rs = $params->{items_rs};
255 die "Mandatory \$params->{xsl_syspref} was not provided, called with biblionumber $params->{biblionumber}"
256 if not defined $params->{xsl_syspref};
258 my $xslfilename = get_xsl_filename( $xslsyspref);
260 # grab the XML, run it through our stylesheet, push it out to the browser
261 my $record = transformMARCXML4XSLT($biblionumber, $orig_record);
263 if ( $xslsyspref eq "OPACXSLTDetailsDisplay" || $xslsyspref eq "XSLTDetailsDisplay" || $xslsyspref eq "XSLTResultsDisplay" ) {
264 $itemsxml = ""; #We don't use XSLT for items display on these pages
266 $itemsxml = buildKohaItemsNamespace($biblionumber, $hidden_items, $items_rs);
268 my $xmlrecord = $record->as_xml(C4::Context->preference('marcflavour'));
272 if (C4::Context->preference('OPACShowOpenURL')) {
273 my @biblio_itemtypes;
274 $biblio //= Koha::Biblios->find($biblionumber);
275 if (C4::Context->preference('item-level_itypes')) {
276 @biblio_itemtypes = $biblio->items->get_column("itype");
278 push @biblio_itemtypes, $biblio->itemtype;
280 my @itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') );
282 map { $original{$_} = 1 } @biblio_itemtypes;
283 if ( grep { $original{$_} } @itypes ) {
284 $variables->{OpenURLResolverURL} = $biblio->get_openurl;
288 my $varxml = "<variables>\n";
289 while (my ($key, $value) = each %$variables) {
291 $varxml .= "<variable name=\"$key\">$value</variable>\n";
293 $varxml .= "</variables>\n";
295 my $sysxml = get_xslt_sysprefs();
296 $xmlrecord =~ s/\<\/record\>/$itemsxml$sysxml$varxml\<\/record\>/;
297 if ($fixamps) { # We need to correct the ampersand entities that Zebra outputs
298 $xmlrecord =~ s/\&amp;/\&/g;
299 $xmlrecord =~ s/\&\;lt\;/\<\;/g;
300 $xmlrecord =~ s/\&\;gt\;/\>\;/g;
302 $xmlrecord =~ s/\& /\&\; /;
303 $xmlrecord =~ s/\&\;amp\; /\&\; /;
305 #If the xslt should fail, we will return undef (old behavior was
307 #Note that we did set do_not_return_source at object construction
308 return $engine->transform($xmlrecord, $xslfilename ); #file or URL
311 =head2 buildKohaItemsNamespace
313 my $items_xml = buildKohaItemsNamespace( $biblionumber, [ $hidden_items, $items ] );
315 Returns XML for items. It accepts two optional parameters:
316 - I<$hidden_items>: An arrayref of itemnumber values, for items that should be hidden
317 - I<$items>: A Koha::Items resultset, for the items to be returned
319 If both parameters are passed, I<$items> is used as the basis resultset, and I<$hidden_items>
320 are filtered out of it.
322 Is only used in this module currently.
326 sub buildKohaItemsNamespace {
327 my ($biblionumber, $hidden_items, $items_rs) = @_;
329 $hidden_items ||= [];
332 $query = { 'me.itemnumber' => { not_in => $hidden_items } }
335 unless ( $items_rs && ref($items_rs) eq 'Koha::Items' ) {
336 $query->{'me.biblionumber'} = $biblionumber;
337 $items_rs = Koha::Items->new;
340 my $items = $items_rs->search( $query, { prefetch => [ 'branchtransfers', 'reserves' ] } );
343 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.location' } ) };
345 { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.ccode' } ) };
347 my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' })->as_list;
349 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
351 my %descs = map { $_->{authorised_value} => $_ } Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.notforloan' } );
352 my $ref_status = C4::Context->preference('Reference_NFL_Statuses') || '1|2';
354 while ( my $item = $items->next ) {
359 if ( C4::Context->preference('UseRecalls') ) {
360 $recalls_count = Koha::Recalls->search({ itemnumber => $item->itemnumber, status => 'waiting' })->count;
363 if ($recalls_count) {
364 # recalls take priority over holds
366 $substatus = 'Recall waiting';
368 elsif ( $item->has_pending_hold ) {
370 $substatus = 'Pending hold';
372 elsif ( $item->holds->waiting->count ) {
374 $substatus = 'Hold waiting';
376 elsif ($item->get_transfer) {
378 $substatus = 'In transit';
380 elsif ($item->damaged) {
382 $substatus = "Damaged";
384 elsif ($item->itemlost) {
388 elsif ( $item->withdrawn) {
390 $substatus = "Withdrawn";
392 elsif ($item->onloan) {
394 $substatus = "Checked out";
396 elsif ( $item->notforloan ) {
397 $status = $item->notforloan =~ /^($ref_status)$/
399 : "reallynotforloan";
400 $substatus = exists $descs{$item->notforloan} ? $descs{$item->notforloan}->{opac_description} : "Not for loan";
402 elsif ( exists $itemtypes->{ $item->effective_itemtype }
403 && $itemtypes->{ $item->effective_itemtype }->{notforloan}
404 && $itemtypes->{ $item->effective_itemtype }->{notforloan} == 1 )
406 $status = "1" =~ /^($ref_status)$/
408 : "reallynotforloan";
409 $substatus = "Not for loan";
412 $status = "available";
414 my $homebranch = C4::Koha::xml_escape($branches{$item->homebranch});
415 my $holdingbranch = C4::Koha::xml_escape($branches{$item->holdingbranch});
416 my $resultbranch = C4::Context->preference('OPACResultsLibrary') eq 'homebranch' ? $homebranch : $holdingbranch;
417 my $location = C4::Koha::xml_escape($item->location && exists $shelflocations->{$item->location} ? $shelflocations->{$item->location} : $item->location);
418 my $ccode = C4::Koha::xml_escape($item->ccode && exists $ccodes->{$item->ccode} ? $ccodes->{$item->ccode} : $item->ccode);
419 my $itemcallnumber = C4::Koha::xml_escape($item->itemcallnumber);
420 my $stocknumber = C4::Koha::xml_escape($item->stocknumber);
423 . "<homebranch>$homebranch</homebranch>"
424 . "<holdingbranch>$holdingbranch</holdingbranch>"
425 . "<resultbranch>$resultbranch</resultbranch>"
426 . "<location>$location</location>"
427 . "<ccode>$ccode</ccode>"
428 . "<status>".( $status // q{} )."</status>"
429 . "<substatus>$substatus</substatus>"
430 . "<itemcallnumber>$itemcallnumber</itemcallnumber>"
431 . "<stocknumber>$stocknumber</stocknumber>"
434 $xml = "<items xmlns=\"http://www.koha-community.org/items\">".$xml."</items>";
440 Returns reference to XSLT handler object.
454 Joshua Ferraro <jmf@liblime.com>
456 Koha Development Team <http://koha-community.org/>