Bug 15504: Add triggers to instances of track_login_daily
[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::RecordProcessor;
32 use Koha::XSLT::Base;
33 use Koha::Libraries;
34 use Koha::Recalls;
35
36 my $engine; #XSLT Handler object
37
38 our (@ISA, @EXPORT_OK);
39 BEGIN {
40     require Exporter;
41     @ISA = qw(Exporter);
42     @EXPORT_OK = qw(
43         buildKohaItemsNamespace
44         XSLTParse4Display
45     );
46     $engine=Koha::XSLT::Base->new( { do_not_return_source => 1 } );
47 }
48
49 =head1 NAME
50
51 C4::XSLT - Functions for displaying XSLT-generated content
52
53 =head1 FUNCTIONS
54
55 =head2 XSLTParse4Display
56
57 Returns xml for biblionumber and requested XSLT transformation.
58 Returns undef if the transform fails.
59
60 Used in OPAC results and detail, intranet results and detail, list display.
61 (Depending on the settings of your XSLT preferences.)
62
63 The helper function _get_best_default_xslt_filename is used in a unit test.
64
65 =cut
66
67 sub _get_best_default_xslt_filename {
68     my ($htdocs, $theme, $lang, $base_xslfile) = @_;
69
70     my @candidates = (
71         "$htdocs/$theme/$lang/xslt/${base_xslfile}", # exact match
72         "$htdocs/$theme/en/xslt/${base_xslfile}",    # if not, preferred theme in English
73         "$htdocs/prog/$lang/xslt/${base_xslfile}",   # if not, 'prog' theme in preferred language
74         "$htdocs/prog/en/xslt/${base_xslfile}",      # otherwise, prog theme in English; should always
75                                                      # exist
76     );
77     my $xslfilename;
78     foreach my $filename (@candidates) {
79         $xslfilename = $filename;
80         if (-f $filename) {
81             last; # we have a winner!
82         }
83     }
84     return $xslfilename;
85 }
86
87 sub get_xslt_sysprefs {
88     my $sysxml = "<sysprefs>\n";
89     foreach my $syspref ( qw/ hidelostitems OPACURLOpenInNewWindow
90                               DisplayOPACiconsXSLT URLLinkText viewISBD
91                               OPACBaseURL TraceCompleteSubfields UseICUStyleQuotes
92                               UseAuthoritiesForTracings TraceSubjectSubdivisions
93                               Display856uAsImage OPACDisplay856uAsImage 
94                               UseControlNumber IntranetBiblioDefaultView BiblioDefaultView
95                               OPACItemLocation DisplayIconsXSLT
96                               AlternateHoldingsField AlternateHoldingsSeparator
97                               TrackClicks opacthemes IdRef OpacSuppression
98                               OPACResultsLibrary OPACShowOpenURL
99                               OpenURLResolverURL OpenURLImageLocation
100                               OPACResultsMaxItems OPACResultsMaxItemsUnavailable OPACResultsUnavailableGroupingBy
101                               OpenURLText OPACShowMusicalInscripts OPACPlayMusicalInscripts ContentWarningField / )
102     {
103         my $sp = C4::Context->preference( $syspref );
104         next unless defined($sp);
105         $sysxml .= "<syspref name=\"$syspref\">$sp</syspref>\n";
106     }
107
108     # singleBranchMode was a system preference, but no longer is
109     # we can retain it here for compatibility
110     my $singleBranchMode = Koha::Libraries->search->count == 1 ? 1 : 0;
111     $sysxml .= "<syspref name=\"singleBranchMode\">$singleBranchMode</syspref>\n";
112
113     $sysxml .= "</sysprefs>\n";
114     return $sysxml;
115 }
116
117 sub get_xsl_filename {
118     my ( $xslsyspref ) = @_;
119
120     my $lang   = C4::Languages::getlanguage();
121
122     my $xslfilename = C4::Context->preference($xslsyspref) || "default";
123
124     if ( $xslfilename =~ /^\s*"?default"?\s*$/i ) {
125
126         my ( $htdocs, $theme, $xslfile );
127
128         if ($xslsyspref eq "XSLTDetailsDisplay") {
129             $htdocs  = C4::Context->config('intrahtdocs');
130             $theme   = C4::Context->preference("template");
131             $xslfile = C4::Context->preference('marcflavour') .
132                        "slim2intranetDetail.xsl";
133         } elsif ($xslsyspref eq "XSLTResultsDisplay") {
134             $htdocs  = C4::Context->config('intrahtdocs');
135             $theme   = C4::Context->preference("template");
136             $xslfile = C4::Context->preference('marcflavour') .
137                         "slim2intranetResults.xsl";
138         } elsif ($xslsyspref eq "OPACXSLTDetailsDisplay") {
139             $htdocs  = C4::Context->config('opachtdocs');
140             $theme   = C4::Context->preference("opacthemes");
141             $xslfile = C4::Context->preference('marcflavour') .
142                        "slim2OPACDetail.xsl";
143         } elsif ($xslsyspref eq "OPACXSLTResultsDisplay") {
144             $htdocs  = C4::Context->config('opachtdocs');
145             $theme   = C4::Context->preference("opacthemes");
146             $xslfile = C4::Context->preference('marcflavour') .
147                        "slim2OPACResults.xsl";
148         } elsif ($xslsyspref eq 'XSLTListsDisplay') {
149             # Lists default to *Results.xslt
150             $htdocs  = C4::Context->config('intrahtdocs');
151             $theme   = C4::Context->preference("template");
152             $xslfile = C4::Context->preference('marcflavour') .
153                         "slim2intranetResults.xsl";
154         } elsif ($xslsyspref eq 'OPACXSLTListsDisplay') {
155             # Lists default to *Results.xslt
156             $htdocs  = C4::Context->config('opachtdocs');
157             $theme   = C4::Context->preference("opacthemes");
158             $xslfile = C4::Context->preference('marcflavour') .
159                        "slim2OPACResults.xsl";
160         }
161         $xslfilename = _get_best_default_xslt_filename($htdocs, $theme, $lang, $xslfile);
162     }
163
164     if ( $xslfilename =~ m/\{langcode\}/ ) {
165         $xslfilename =~ s/\{langcode\}/$lang/;
166     }
167
168     return $xslfilename;
169 }
170
171 sub XSLTParse4Display {
172     my ( $params ) = @_;
173
174     my $biblionumber = $params->{biblionumber};
175     my $record       = $params->{record};
176     my $xslsyspref   = $params->{xsl_syspref};
177     my $fixamps      = $params->{fix_amps};
178     my $hidden_items = $params->{hidden_items} || [];
179     my $variables    = $params->{xslt_variables};
180     my $items_rs     = $params->{items_rs};
181     my $interface    = C4::Context->interface;
182
183     die "Mandatory \$params->{xsl_syspref} was not provided, called with biblionumber $params->{biblionumber}"
184         if not defined $params->{xsl_syspref};
185
186     my $xslfilename = get_xsl_filename( $xslsyspref);
187
188     my $frameworkcode = GetFrameworkCode($biblionumber) || '';
189     my $record_processor = Koha::RecordProcessor->new(
190         {
191             filters => [ 'ExpandCodedFields' ],
192             options => {
193                 interface     => $interface,
194                 frameworkcode => $frameworkcode
195             }
196         }
197     );
198     $record_processor->process($record);
199
200     # grab the XML, run it through our stylesheet, push it out to the browser
201     my $itemsxml;
202     if ( $xslsyspref eq "OPACXSLTDetailsDisplay" || $xslsyspref eq "XSLTDetailsDisplay" || $xslsyspref eq "XSLTResultsDisplay" ) {
203         $itemsxml = ""; #We don't use XSLT for items display on these pages
204     } else {
205         $itemsxml = buildKohaItemsNamespace($biblionumber, $hidden_items, $items_rs);
206     }
207     my $xmlrecord = $record->as_xml(C4::Context->preference('marcflavour'));
208
209     $variables ||= {};
210     my $biblio;
211     if ( $interface eq 'opac' && C4::Context->preference('OPACShowOpenURL')) {
212         my @biblio_itemtypes;
213         $biblio //= Koha::Biblios->find($biblionumber);
214         if (C4::Context->preference('item-level_itypes')) {
215             @biblio_itemtypes = $biblio->items->get_column("itype");
216         } else {
217             push @biblio_itemtypes, $biblio->itemtype;
218         }
219         my @itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') );
220         my %original = ();
221         map { $original{$_} = 1 } @biblio_itemtypes;
222         if ( grep { $original{$_} } @itypes ) {
223             $variables->{OpenURLResolverURL} = $biblio->get_openurl;
224         }
225     }
226
227     # embed variables
228     my $varxml = "<variables>\n";
229     while (my ($key, $value) = each %$variables) {
230         $value //= q{};
231         $varxml .= "<variable name=\"$key\">$value</variable>\n";
232     }
233     $varxml .= "</variables>\n";
234
235     my $sysxml = get_xslt_sysprefs();
236     $xmlrecord =~ s/\<\/record\>/$itemsxml$sysxml$varxml\<\/record\>/;
237     if ($fixamps) { # We need to correct the ampersand entities that Zebra outputs
238         $xmlrecord =~ s/\&amp;amp;/\&amp;/g;
239         $xmlrecord =~ s/\&amp\;lt\;/\&lt\;/g;
240         $xmlrecord =~ s/\&amp\;gt\;/\&gt\;/g;
241     }
242     $xmlrecord =~ s/\& /\&amp\; /;
243     $xmlrecord =~ s/\&amp\;amp\; /\&amp\; /;
244
245     #If the xslt should fail, we will return undef (old behavior was
246     #raw MARC)
247     #Note that we did set do_not_return_source at object construction
248     return $engine->transform($xmlrecord, $xslfilename ); #file or URL
249 }
250
251 =head2 buildKohaItemsNamespace
252
253     my $items_xml = buildKohaItemsNamespace( $biblionumber, [ $hidden_items, $items ] );
254
255 Returns XML for items. It accepts two optional parameters:
256 - I<$hidden_items>: An arrayref of itemnumber values, for items that should be hidden
257 - I<$items>: A Koha::Items resultset, for the items to be returned
258
259 If both parameters are passed, I<$items> is used as the basis resultset, and I<$hidden_items>
260 are filtered out of it.
261
262 Is only used in this module currently.
263
264 =cut
265
266 sub buildKohaItemsNamespace {
267     my ($biblionumber, $hidden_items, $items_rs) = @_;
268
269     $hidden_items ||= [];
270
271     my $query = {};
272     $query = { 'me.itemnumber' => { not_in => $hidden_items } }
273       if $hidden_items;
274
275     unless ( $items_rs && ref($items_rs) eq 'Koha::Items' ) {
276         $query->{'me.biblionumber'} = $biblionumber;
277         $items_rs = Koha::Items->new;
278     }
279
280     my $items = $items_rs->search( $query, { prefetch => [ 'branchtransfers', 'reserves' ] } );
281
282     my $shelflocations =
283       { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.location' } ) };
284     my $ccodes =
285       { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.ccode' } ) };
286
287     my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' })->as_list;
288
289     my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
290     my $xml = '';
291     my %descs = map { $_->{authorised_value} => $_ } Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.notforloan' } );
292     my $ref_status = C4::Context->preference('Reference_NFL_Statuses') // q{}; # fallback to 1|2 removed
293
294     while ( my $item = $items->next ) {
295         my $status;
296         my $substatus = '';
297         my $recalls_count;
298
299         if ( C4::Context->preference('UseRecalls') ) {
300             $recalls_count = Koha::Recalls->search({ item_id => $item->itemnumber, status => 'waiting' })->count;
301         }
302
303         if ($recalls_count) {
304             # recalls take priority over holds
305             $status = 'other';
306             $substatus = 'Recall waiting';
307         }
308         elsif ( $item->has_pending_hold ) {
309             $status = 'other';
310             $substatus = 'Pending hold';
311         }
312         elsif ( $item->holds->waiting->count ) {
313             $status = 'other';
314             $substatus = 'Hold waiting';
315         }
316         elsif ($item->get_transfer) {
317             $status = 'other';
318             $substatus = 'In transit';
319         }
320         elsif ($item->damaged) {
321             $status = 'other';
322             $substatus = "Damaged";
323         }
324         elsif ($item->itemlost) {
325             $status = 'other';
326             $substatus = "Lost";
327         }
328         elsif ( $item->withdrawn) {
329             $status = 'other';
330             $substatus = "Withdrawn";
331         }
332         elsif ($item->onloan) {
333             $status = 'other';
334             $substatus = "Checked out";
335         }
336         elsif ( $item->notforloan ) {
337             $status = $item->notforloan =~ /^($ref_status)$/
338                 ? "reference"
339                 : "reallynotforloan";
340             $substatus = exists $descs{$item->notforloan} ? $descs{$item->notforloan}->{opac_description} : "Not for loan";
341         }
342         elsif ( exists $itemtypes->{ $item->effective_itemtype }
343             && $itemtypes->{ $item->effective_itemtype }->{notforloan}
344             && $itemtypes->{ $item->effective_itemtype }->{notforloan} == 1 )
345         {
346             $status = "1" =~ /^($ref_status)$/
347                 ? "reference"
348                 : "reallynotforloan";
349             $substatus = "Not for loan";
350         }
351         else {
352             $status = "available";
353         }
354         my $homebranch     = C4::Koha::xml_escape($branches{$item->homebranch});
355         my $holdingbranch  = C4::Koha::xml_escape($branches{$item->holdingbranch});
356         my $resultbranch   = C4::Context->preference('OPACResultsLibrary') eq 'homebranch' ? $homebranch : $holdingbranch;
357         my $location       = C4::Koha::xml_escape($item->location && exists $shelflocations->{$item->location} ? $shelflocations->{$item->location} : $item->location);
358         my $ccode          = C4::Koha::xml_escape($item->ccode    && exists $ccodes->{$item->ccode}            ? $ccodes->{$item->ccode}            : $item->ccode);
359         my $itemcallnumber = C4::Koha::xml_escape($item->itemcallnumber);
360         my $stocknumber    = C4::Koha::xml_escape($item->stocknumber);
361         $xml .=
362             "<item>"
363           . "<homebranch>$homebranch</homebranch>"
364           . "<holdingbranch>$holdingbranch</holdingbranch>"
365           . "<resultbranch>$resultbranch</resultbranch>"
366           . "<location>$location</location>"
367           . "<ccode>$ccode</ccode>"
368           . "<status>".( $status // q{} )."</status>"
369           . "<substatus>$substatus</substatus>"
370           . "<itemcallnumber>$itemcallnumber</itemcallnumber>"
371           . "<stocknumber>$stocknumber</stocknumber>"
372           . "</item>";
373     }
374     $xml = "<items xmlns=\"http://www.koha-community.org/items\">".$xml."</items>";
375     return $xml;
376 }
377
378 =head2 engine
379
380 Returns reference to XSLT handler object.
381
382 =cut
383
384 sub engine {
385     return $engine;
386 }
387
388 1;
389
390 __END__
391
392 =head1 AUTHOR
393
394 Joshua Ferraro <jmf@liblime.com>
395
396 Koha Development Team <http://koha-community.org/>
397
398 =cut