1 package Koha::REST::Plugin::Query;
3 # This file is part of Koha.
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.
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.
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>.
20 use Mojo::Base 'Mojolicious::Plugin';
21 use List::MoreUtils qw( any );
22 use Scalar::Util qw( reftype );
23 use JSON qw( decode_json );
29 Koha::REST::Plugin::Query
33 =head2 Mojolicious::Plugin methods
40 my ( $self, $app ) = @_;
44 =head3 extract_reserved_params
46 my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($params);
48 Generates the DBIC query from the query parameters.
53 'extract_reserved_params' => sub {
54 my ( $c, $params ) = @_;
60 my $reserved_words = _reserved_words();
61 my @query_param_names = keys %{$c->req->params->to_hash};
63 foreach my $param ( keys %{$params} ) {
64 if ( grep { $param eq $_ } @{$reserved_words} ) {
65 $reserved_params->{$param} = $params->{$param};
67 elsif ( grep { $param eq $_ } @query_param_names ) {
68 $filtered_params->{$param} = $params->{$param};
71 $path_params->{$param} = $params->{$param};
75 return ( $filtered_params, $reserved_params, $path_params );
79 =head3 dbic_merge_sorting
81 $attributes = $c->dbic_merge_sorting({ attributes => $attributes, params => $params });
83 Generates the DBIC order_by attributes based on I<$params>, and merges into I<$attributes>.
88 'dbic_merge_sorting' => sub {
89 my ( $c, $args ) = @_;
90 my $attributes = $args->{attributes};
91 my $result_set = $args->{result_set};
93 my @order_by_styles = (
99 foreach my $order_by_style ( @order_by_styles ) {
100 if ( defined $args->{params}->{$order_by_style} and ref($args->{params}->{$order_by_style}) eq 'ARRAY' ) {
101 push( @order_by_params, @{$args->{params}->{$order_by_style} });
104 push @order_by_params, $args->{params}->{$order_by_style}
105 if defined $args->{params}->{$order_by_style};
111 foreach my $order_by_param ( @order_by_params ) {
113 $order_by = [ split(/,/, $order_by_param) ]
114 if ( !reftype($order_by_param) && index(',',$order_by_param) == -1);
117 if ( reftype($order_by) and reftype($order_by) eq 'ARRAY' ) {
118 my @order_by = map { _build_order_atom({ string => $_, result_set => $result_set }) } @{ $order_by };
119 push( @THE_order_by, @order_by);
122 push @THE_order_by, _build_order_atom({ string => $order_by, result_set => $result_set });
127 $attributes->{order_by} = \@THE_order_by
128 if scalar @THE_order_by > 0;
134 =head3 dbic_merge_prefetch
136 $attributes = $c->dbic_merge_prefetch({ attributes => $attributes, result_set => $result_set });
138 Generates the DBIC prefetch attribute based on embedded relations, and merges into I<$attributes>.
143 'dbic_merge_prefetch' => sub {
144 my ( $c, $args ) = @_;
145 my $attributes = $args->{attributes};
146 my $result_set = $args->{result_set};
147 my $embed = $c->stash('koha.embed');
148 return unless defined $embed;
151 foreach my $key (sort keys(%{$embed})) {
152 my $parsed = _parse_prefetch($key, $embed, $result_set);
153 push @prefetches, $parsed if defined $parsed;
156 if(scalar(@prefetches)) {
157 $attributes->{prefetch} = \@prefetches;
162 =head3 _build_query_params_from_api
164 my $params = _build_query_params_from_api( $filtered_params, $reserved_params );
166 Builds the params for searching on DBIC based on the selected matching algorithm.
167 Valid options are I<contains>, I<starts_with>, I<ends_with> and I<exact>. Default is
168 I<contains>. If other value is passed, a Koha::Exceptions::WrongParameter exception
174 'build_query_params' => sub {
176 my ( $c, $filtered_params, $reserved_params ) = @_;
179 my $match = $reserved_params->{_match} // 'contains';
181 foreach my $param ( keys %{$filtered_params} ) {
182 if ( $match eq 'contains' ) {
184 { like => '%' . $filtered_params->{$param} . '%' };
186 elsif ( $match eq 'starts_with' ) {
187 $params->{$param} = { like => $filtered_params->{$param} . '%' };
189 elsif ( $match eq 'ends_with' ) {
190 $params->{$param} = { like => '%' . $filtered_params->{$param} };
192 elsif ( $match eq 'exact' ) {
193 $params->{$param} = $filtered_params->{$param};
196 # We should never reach here, because the OpenAPI plugin should
197 # prevent invalid params to be passed
198 Koha::Exceptions::WrongParameter->throw(
199 "Invalid value for _match param ($match)");
207 =head3 merge_q_params
209 $c->merge_q_params( $filtered_params, $q_params, $result_set );
211 Merges parameters from $q_params into $filtered_params.
216 'merge_q_params' => sub {
218 my ( $c, $filtered_params, $q_params, $result_set ) = @_;
220 $q_params = decode_json($q_params) unless reftype $q_params;
222 my $params = _parse_dbic_query($q_params, $result_set);
224 return $params unless scalar(keys %{$filtered_params});
225 return {'-and' => [$params, $filtered_params ]};
233 Unwraps and stashes the x-koha-embed headers for use later query construction
238 'stash_embed' => sub {
241 my $embed_header = $c->req->headers->header('x-koha-embed');
244 foreach my $embed_req ( split /\s*,\s*/, $embed_header ) {
245 _merge_embed( _parse_embed($embed_req), $THE_embed );
248 $c->stash( 'koha.embed' => $THE_embed )
256 =head3 stash_overrides
258 # Stash the overrides
259 $c->stash_overrides();
261 my $overrides = $c->stash('koha.overrides');
262 if ( $overrides->{pickup_location} ) { ... }
264 This helper method parses 'x-koha-override' headers and stashes the passed overriders
265 in the for of a I<hashref> for easy use in controller methods.
267 FIXME: With the currently used JSON::Validator version we use, it is not possible to
268 use the validated and coerced data (it doesn't validate array-type headers) so this
269 implementation relies on manual parsing. Look at the JSON::Validator changelog for
270 reference: https://metacpan.org/changes/distribution/JSON-Validator#L14
275 'stash_overrides' => sub {
279 my $override_header = $c->req->headers->header('x-koha-override') || q{};
281 my $overrides = { map { $_ => 1 } split /\s*,\s*/, $override_header };
283 $c->stash( 'koha.overrides' => $overrides );
290 =head2 Internal methods
292 =head3 _reserved_words
294 my $reserved_words = _reserved_words();
298 sub _reserved_words {
300 my @reserved_words = qw( _match _order_by _order_by[] _page _per_page q query x-koha-query x-koha-request-id x-koha-embed);
301 return \@reserved_words;
304 =head3 _build_order_atom
306 my $order_atom = _build_order_atom( $string );
308 Parses I<$string> and outputs data valid for using in SQL::Abstract order_by attribute
309 according to the following rules:
312 +string -> I<{ -asc => string }>
313 -string -> I<{ -desc => string }>
317 sub _build_order_atom {
319 my $string = $args->{string};
320 my $result_set = $args->{result_set};
323 $param =~ s/^(\+|\-|\s)//;
325 my $model_param = _from_api_param($param, $result_set);
326 $param = $model_param if defined $model_param;
329 if ( $string =~ m/^\+/ or
330 $string =~ m/^\s/ ) {
331 # asc order operator present
332 return { -asc => $param };
334 elsif ( $string =~ m/^\-/ ) {
335 # desc order operator present
336 return { -desc => $param };
339 # no order operator present
346 my $embed = _parse_embed( $string );
348 Parses I<$string> and outputs data valid for passing to the Kohaa::Object(s)->to_api
357 my ( $curr, $next ) = split /\s*\.\s*/, $string, 2;
360 $result->{$curr} = { children => _parse_embed( $next ) };
363 if ( $curr =~ m/^(?<relation>.*)\+count/ ) {
364 my $key = $+{relation} . "_count";
365 $result->{$key} = { is_count => 1 };
368 $result->{$curr} = {};
377 _merge_embed( $parsed_embed, $global_embed );
379 Merges the hash referenced by I<$parsed_embed> into I<$global_embed>.
384 my ( $structure, $embed ) = @_;
386 my ($root) = keys %{ $structure };
388 if ( any { $root eq $_ } keys %{ $embed } ) {
390 _merge_embed( $structure->{$root}, $embed->{$root} );
394 $embed->{$root} = $structure->{$root};
398 sub _parse_prefetch {
399 my ( $key, $embed, $result_set) = @_;
402 $pref_key =~ s/_count$// if $embed->{$key}->{is_count};
403 return unless exists $result_set->prefetch_whitelist->{$pref_key};
405 my $ko_class = $result_set->prefetch_whitelist->{$pref_key};
406 return $pref_key unless defined $embed->{$key}->{children} && defined $ko_class;
409 foreach my $child (sort keys(%{$embed->{$key}->{children}})) {
410 my $parsed = _parse_prefetch($child, $embed->{$key}->{children}, $ko_class->new);
411 push @prefetches, $parsed if defined $parsed;
414 return $pref_key unless scalar(@prefetches);
416 return {$pref_key => $prefetches[0]} if scalar(@prefetches) eq 1;
418 return {$pref_key => \@prefetches};
421 sub _from_api_param {
422 my ($key, $result_set) = @_;
426 my ($curr, $next) = split /\s*\.\s*/, $key, 2;
428 return $curr.'.'._from_api_param($next, $result_set) if $curr eq 'me';
430 my $ko_class = $result_set->prefetch_whitelist->{$curr};
432 Koha::Exceptions::BadParameter->throw("Cannot find Koha::Object class for $curr")
433 unless defined $ko_class;
435 $result_set = $ko_class->new;
438 return _from_api_param($next, $result_set);
440 return $curr.'.'.($result_set->from_api_mapping && defined $result_set->from_api_mapping->{$next} ? $result_set->from_api_mapping->{$next}:$next);
443 return defined $result_set->from_api_mapping->{$key} ? $result_set->from_api_mapping->{$key} : $key;
447 sub _parse_dbic_query {
448 my ($q_params, $result_set) = @_;
450 if(reftype($q_params) && reftype($q_params) eq 'HASH') {
452 foreach my $key (keys %{$q_params}) {
453 if($key =~ /-?(not_?)?bool/i ) {
454 $parsed_hash->{$key} = _from_api_param($q_params->{$key}, $result_set);
457 my $k = _from_api_param($key, $result_set);
458 $parsed_hash->{$k} = _parse_dbic_query($q_params->{$key}, $result_set);
461 } elsif (reftype($q_params) && reftype($q_params) eq 'ARRAY') {
462 my @mapped = map{ _parse_dbic_query($_, $result_set) } @$q_params;