Bug 27981: Adjust imported records, svc/import_bibs, records from Z3950
[koha.git] / C4 / XSLT.pm
1 package C4::XSLT;
2
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
8 #
9 # This file is part of Koha.
10 #
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.
15 #
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.
20 #
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>.
23
24 use Modern::Perl;
25
26 use C4::Context;
27 use C4::Koha qw( xml_escape );
28 use C4::Biblio qw( GetAuthorisedValueDesc GetFrameworkCode GetMarcStructure );
29 use Koha::AuthorisedValues;
30 use Koha::ItemTypes;
31 use Koha::XSLT::Base;
32 use Koha::Libraries;
33 use Koha::Recalls;
34
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...
39
40 our (@ISA, @EXPORT_OK);
41 BEGIN {
42     require Exporter;
43     @ISA = qw(Exporter);
44     @EXPORT_OK = qw(
45         transformMARCXML4XSLT
46         getAuthorisedValues4MARCSubfields
47         buildKohaItemsNamespace
48         XSLTParse4Display
49     );
50     $engine=Koha::XSLT::Base->new( { do_not_return_source => 1 } );
51 }
52
53 =head1 NAME
54
55 C4::XSLT - Functions for displaying XSLT-generated content
56
57 =head1 FUNCTIONS
58
59 =head2 transformMARCXML4XSLT
60
61 Replaces codes with authorized values in a MARC::Record object
62
63 =cut
64
65 sub transformMARCXML4XSLT {
66     my ($biblionumber, $record, $opac) = @_;
67     my $frameworkcode = GetFrameworkCode($biblionumber) || '';
68     my $tagslib = &GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
69     my @fields;
70     # FIXME: wish there was a better way to handle exceptions
71     eval {
72         @fields = $record->fields();
73     };
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 };
87                     }
88                     push( @new_subfields, $letter, $value );
89                 } 
90                 $field ->replace_with( MARC::Field->new(
91                     $tag,
92                     $field->indicator(1),
93                     $field->indicator(2),
94                     @new_subfields
95                 ) );
96             }
97         }
98     }
99     return $record;
100 }
101
102 =head2 getAuthorisedValues4MARCSubfields
103
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.
106
107 =cut
108
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 );
119         my $av = { };
120         while ( my ( $tag, $letter ) = $sth->fetchrow() ) {
121             $av->{ $tag }->{ $letter } = 1;
122         }
123         $authval_per_framework{ $frameworkcode } = $av;
124     }
125     return $authval_per_framework{ $frameworkcode };
126 }
127
128 =head2 XSLTParse4Display
129
130 Returns xml for biblionumber and requested XSLT transformation.
131 Returns undef if the transform fails.
132
133 Used in OPAC results and detail, intranet results and detail, list display.
134 (Depending on the settings of your XSLT preferences.)
135
136 The helper function _get_best_default_xslt_filename is used in a unit test.
137
138 =cut
139
140 sub _get_best_default_xslt_filename {
141     my ($htdocs, $theme, $lang, $base_xslfile) = @_;
142
143     my @candidates = (
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
148                                                      # exist
149     );
150     my $xslfilename;
151     foreach my $filename (@candidates) {
152         $xslfilename = $filename;
153         if (-f $filename) {
154             last; # we have a winner!
155         }
156     }
157     return $xslfilename;
158 }
159
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 / )
175     {
176         my $sp = C4::Context->preference( $syspref );
177         next unless defined($sp);
178         $sysxml .= "<syspref name=\"$syspref\">$sp</syspref>\n";
179     }
180
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";
185
186     $sysxml .= "</sysprefs>\n";
187     return $sysxml;
188 }
189
190 sub get_xsl_filename {
191     my ( $xslsyspref ) = @_;
192
193     my $lang   = C4::Languages::getlanguage();
194
195     my $xslfilename = C4::Context->preference($xslsyspref) || "default";
196
197     if ( $xslfilename =~ /^\s*"?default"?\s*$/i ) {
198
199         my ( $htdocs, $theme, $xslfile );
200
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";
233         }
234         $xslfilename = _get_best_default_xslt_filename($htdocs, $theme, $lang, $xslfile);
235     }
236
237     if ( $xslfilename =~ m/\{langcode\}/ ) {
238         $xslfilename =~ s/\{langcode\}/$lang/;
239     }
240
241     return $xslfilename;
242 }
243
244 sub XSLTParse4Display {
245     my ( $params ) = @_;
246
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};
254
255     die "Mandatory \$params->{xsl_syspref} was not provided, called with biblionumber $params->{biblionumber}"
256         if not defined $params->{xsl_syspref};
257
258     my $xslfilename = get_xsl_filename( $xslsyspref);
259
260     # grab the XML, run it through our stylesheet, push it out to the browser
261     my $record = transformMARCXML4XSLT($biblionumber, $orig_record);
262     my $itemsxml;
263     if ( $xslsyspref eq "OPACXSLTDetailsDisplay" || $xslsyspref eq "XSLTDetailsDisplay" || $xslsyspref eq "XSLTResultsDisplay" ) {
264         $itemsxml = ""; #We don't use XSLT for items display on these pages
265     } else {
266         $itemsxml = buildKohaItemsNamespace($biblionumber, $hidden_items, $items_rs);
267     }
268     my $xmlrecord = $record->as_xml(C4::Context->preference('marcflavour'));
269
270     $variables ||= {};
271     my $biblio;
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");
277         } else {
278             push @biblio_itemtypes, $biblio->itemtype;
279         }
280         my @itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') );
281         my %original = ();
282         map { $original{$_} = 1 } @biblio_itemtypes;
283         if ( grep { $original{$_} } @itypes ) {
284             $variables->{OpenURLResolverURL} = $biblio->get_openurl;
285         }
286     }
287
288     my $varxml = "<variables>\n";
289     while (my ($key, $value) = each %$variables) {
290         $value //= q{};
291         $varxml .= "<variable name=\"$key\">$value</variable>\n";
292     }
293     $varxml .= "</variables>\n";
294
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;amp;/\&amp;/g;
299         $xmlrecord =~ s/\&amp\;lt\;/\&lt\;/g;
300         $xmlrecord =~ s/\&amp\;gt\;/\&gt\;/g;
301     }
302     $xmlrecord =~ s/\& /\&amp\; /;
303     $xmlrecord =~ s/\&amp\;amp\; /\&amp\; /;
304
305     #If the xslt should fail, we will return undef (old behavior was
306     #raw MARC)
307     #Note that we did set do_not_return_source at object construction
308     return $engine->transform($xmlrecord, $xslfilename ); #file or URL
309 }
310
311 =head2 buildKohaItemsNamespace
312
313     my $items_xml = buildKohaItemsNamespace( $biblionumber, [ $hidden_items, $items ] );
314
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
318
319 If both parameters are passed, I<$items> is used as the basis resultset, and I<$hidden_items>
320 are filtered out of it.
321
322 Is only used in this module currently.
323
324 =cut
325
326 sub buildKohaItemsNamespace {
327     my ($biblionumber, $hidden_items, $items_rs) = @_;
328
329     $hidden_items ||= [];
330
331     my $query = {};
332     $query = { 'me.itemnumber' => { not_in => $hidden_items } }
333       if $hidden_items;
334
335     unless ( $items_rs && ref($items_rs) eq 'Koha::Items' ) {
336         $query->{'me.biblionumber'} = $biblionumber;
337         $items_rs = Koha::Items->new;
338     }
339
340     my $items = $items_rs->search( $query, { prefetch => [ 'branchtransfers', 'reserves' ] } );
341
342     my $shelflocations =
343       { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.location' } ) };
344     my $ccodes =
345       { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.ccode' } ) };
346
347     my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' })->as_list;
348
349     my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
350     my $xml = '';
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';
353
354     while ( my $item = $items->next ) {
355         my $status;
356         my $substatus = '';
357         my $recalls_count;
358
359         if ( C4::Context->preference('UseRecalls') ) {
360             $recalls_count = Koha::Recalls->search({ item_id => $item->itemnumber, status => 'waiting' })->count;
361         }
362
363         if ($recalls_count) {
364             # recalls take priority over holds
365             $status = 'other';
366             $substatus = 'Recall waiting';
367         }
368         elsif ( $item->has_pending_hold ) {
369             $status = 'other';
370             $substatus = 'Pending hold';
371         }
372         elsif ( $item->holds->waiting->count ) {
373             $status = 'other';
374             $substatus = 'Hold waiting';
375         }
376         elsif ($item->get_transfer) {
377             $status = 'other';
378             $substatus = 'In transit';
379         }
380         elsif ($item->damaged) {
381             $status = 'other';
382             $substatus = "Damaged";
383         }
384         elsif ($item->itemlost) {
385             $status = 'other';
386             $substatus = "Lost";
387         }
388         elsif ( $item->withdrawn) {
389             $status = 'other';
390             $substatus = "Withdrawn";
391         }
392         elsif ($item->onloan) {
393             $status = 'other';
394             $substatus = "Checked out";
395         }
396         elsif ( $item->notforloan ) {
397             $status = $item->notforloan =~ /^($ref_status)$/
398                 ? "reference"
399                 : "reallynotforloan";
400             $substatus = exists $descs{$item->notforloan} ? $descs{$item->notforloan}->{opac_description} : "Not for loan";
401         }
402         elsif ( exists $itemtypes->{ $item->effective_itemtype }
403             && $itemtypes->{ $item->effective_itemtype }->{notforloan}
404             && $itemtypes->{ $item->effective_itemtype }->{notforloan} == 1 )
405         {
406             $status = "1" =~ /^($ref_status)$/
407                 ? "reference"
408                 : "reallynotforloan";
409             $substatus = "Not for loan";
410         }
411         else {
412             $status = "available";
413         }
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);
421         $xml .=
422             "<item>"
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>"
432           . "</item>";
433     }
434     $xml = "<items xmlns=\"http://www.koha-community.org/items\">".$xml."</items>";
435     return $xml;
436 }
437
438 =head2 engine
439
440 Returns reference to XSLT handler object.
441
442 =cut
443
444 sub engine {
445     return $engine;
446 }
447
448 1;
449
450 __END__
451
452 =head1 AUTHOR
453
454 Joshua Ferraro <jmf@liblime.com>
455
456 Koha Development Team <http://koha-community.org/>
457
458 =cut