PhraseLimiter.php
9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
/**
* SearchWP Phrase Limiter.
*
* @package SearchWP
* @author Jon Christopher
*/
namespace SearchWP\Logic;
use SearchWP\Utils;
use SearchWP\Query;
use SearchWP\Tokens;
use SearchWP\Attribute;
/**
* Class PhraseLimiter is responsible for generating a phrase logic clause.
*
* @since 4.0
*/
class PhraseLimiter {
/**
* Query for the limiter.
*
* @since 4.0
* @var Query
*/
private $query;
/**
* Phrases to consider.
*
* @since 4.0
* @var array
*/
private $phrases;
// These are placeholder vars for Issue #329.
// @link https://github.com/searchwp/searchwp/issues/329
private $do_and_logic;
private $and_logic_strict;
private $and_logic_tokens = [];
/**
* Index
*
* @since 4.0
* @var Index
*/
private $index;
/**
* Attributes that support phrases.
*
* @since 4.0
* @var array
*/
private $attributes;
/**
* SQL values storage.
*
* @since 4.0
* @var array
*/
private $values;
/**
* PhraseLimiter constructor.
*
* @since 4.0
*/
function __construct( Query $query, $do_and_logic = true, $and_logic_strict = false ) {
$this->query = $query;
$this->phrases = Utils::get_phrases_from_string( $query->get_keywords() );
$this->index = \SearchWP::$index;
$this->do_and_logic = $do_and_logic;
$this->and_logic_strict = $and_logic_strict;
$this->and_logic_tokens = array_filter( explode( ' ', trim(
str_ireplace( array_merge( $this->phrases, [ '"' ] ), '', $query->get_keywords() )
) ) );
if ( empty( $this->and_logic_tokens ) ) {
$this->do_and_logic = false;
}
$this->parse_sources_attributes();
}
/**
* Generate the (prepared) SQL for Phrase logic.
*
* @since 4.0
* @return false|string
*/
public function get_sql() {
global $wpdb;
$phrase_results = $this->get_entries();
// If there are no phrase results, bail out. Returning false will progress to the next algorithm.
if ( empty( $phrase_results ) ) {
return false;
}
do_action( 'searchwp\debug\log', 'Performing phrase search', 'query' );
$clauses = [];
foreach ( $phrase_results as $source_name => $ids ) {
$clauses[] = $wpdb->prepare(
"(s.source = %s AND s.id IN (" . implode( ', ', array_fill( 0, count( $ids ), '%s' ) ) . '))',
array_merge( [ $source_name ], $ids )
);
}
return ! empty( $clauses ) ? '(' . implode( ' OR ', $clauses ) . ')' : '';
}
/**
* Finds IDs that have our phrases.
*
* @since 4.0
* @return string
*/
public function get_entries() {
global $wpdb;
$results = [];
$site_in = '1=1';
if ( 'all' !== $this->query->get_args()['site'] ) {
$site_in = $this->query->get_site_limit_sql();
}
foreach( $this->group_sources_attributes() as $source_name => $source_phrases ) {
$subqueries = [];
$attributes = [];
$this->values = [];
$attribute_values = [];
foreach ( $source_phrases as $table => $ids ) {
foreach ( $ids as $id => $columns ) {
$wheres = [];
foreach ( $columns as $column => $source_attribute ) {
$wheres[] = implode( ' OR ', array_map( function( $phrase ) use ( $column, $source_attribute, $wpdb ) {
$this->values[] = '%' . $wpdb->esc_like( trim( $phrase ) ) . '%';
// If this attribute is a meta_value, we must include the meta_keys on the sql as well.
if ( $column === 'meta_value' ) {
if ( ! empty( $source_attribute['value'] ) && is_array( $source_attribute['value'] ) ) {
$meta_keys = array_key_exists( '*', $source_attribute['value'] ) ? [] : array_keys( $source_attribute['value'] );
if ( ! empty( $meta_keys ) ) {
return "{$column} LIKE %s AND meta_key IN ('" . implode( "','", $meta_keys ) . "')";
}
}
}
// Default sql for all other cases.
return "{$column} LIKE %s";
}, $this->phrases ) );
if ( $source_attribute['attribute']->get_options() ) {
$attributes[] = 's.attribute LIKE %s';
$attribute_values[] = $wpdb->esc_like( $source_attribute['attribute']->get_name() . SEARCHWP_SEPARATOR ) . '%';
} else {
$attributes[] = 's.attribute = %s';
$attribute_values[] = $source_attribute['attribute']->get_name();
}
}
$subqueries[] = "SELECT {$id} AS id FROM {$table} WHERE 1=1 AND (" . implode( ' OR ', $wheres ) . ')';
}
}
$sql = "
SELECT p.id
FROM (" . implode( ' UNION ', $subqueries ) . ") AS p
LEFT JOIN {$this->index->get_tables()['index']->table_name} s ON s.id = p.id
WHERE {$site_in}
AND s.source = %s
AND (" . implode( ' OR ', $attributes ) . ")
GROUP BY id";
if ( 'all' !== $this->query->get_args()['site'] ) {
$this->values = array_merge(
$this->values,
$this->query->get_args()['site'],
[ $source_name ],
$attribute_values
);
} else {
$this->values = array_merge(
$this->values,
[ $source_name ],
$attribute_values
);
}
$results[ $source_name ] = $wpdb->get_col( $wpdb->prepare( $sql, $this->values ) );
}
$results = array_filter( $results );
// Apply AND logic if applicable.
if ( ! empty( $results ) && $this->do_and_logic ) {
$mods = [];
foreach ( $results as $source_name => $ids ) {
$mod = new \SearchWP\Mod( $source_name );
$mod->set_where( [ [
'column' => 'id',
'value' => $ids,
'compare' => 'IN',
] ] );
$mods[] = $mod;
}
// Prevent recursion caused by quoted/phrase searches set by synonyms.
add_filter( 'searchwp\synonyms', '__return_empty_array' );
$and_logic_results = new \SearchWP\Query( implode( ' ', $this->and_logic_tokens ), [
'engine' => $this->query->get_engine()->get_name(),
'per_page' => -1,
'mods' => $mods,
] );
remove_filter( 'searchwp\synonyms', '__return_empty_array' );
if (
empty( $and_logic_results->get_results() )
&& apply_filters( 'searchwp\query\logic\phrase\and_logic_strict', $this->and_logic_strict )
) {
$results = [];
} elseif ( ! empty( $and_logic_results->get_results() ) ) {
$and_logic_results_normalized = [];
foreach ( $and_logic_results->get_results() as $and_logic_result ) {
if ( ! array_key_exists( $and_logic_result->source, $and_logic_results_normalized ) ) {
$and_logic_results_normalized[ $and_logic_result->source ] = [];
}
$and_logic_results_normalized[ $and_logic_result->source ][] = $and_logic_result->id;
}
if ( ! empty( $and_logic_results_normalized ) ) {
$results = $and_logic_results_normalized;
}
}
}
// If there were no results and we're not strict about that, tell the Query the search is revised.
if ( empty( $results ) && ! apply_filters( 'searchwp\query\logic\phrase\strict', false ) ) {
$this->query->set_suggested_search(
new Tokens( str_replace( '"', '', $this->query->get_keywords() ) )
);
}
return $results;
}
/**
* Groups Phrases configs into associative array of tables and columns.
*
* @since 4.0
* @return array
*/
private function group_sources_attributes() {
$groups = [];
foreach ( $this->attributes as $source_name => $attributes ) {
if ( ! array_key_exists( $source_name, $groups ) ) {
$groups[ $source_name ] = [];
}
foreach ( $attributes as $attribute => $phrase_cols ) {
foreach ( $phrase_cols as $phrase_col ) {
if ( ! array_key_exists( $phrase_col['table'], $groups[ $source_name ] ) ) {
$groups[ $source_name ][ $phrase_col['table'] ] = [];
}
if ( ! array_key_exists( $phrase_col['id'], $groups[ $source_name ][ $phrase_col['table'] ] ) ) {
$groups[ $source_name ][ $phrase_col['table'] ][ $phrase_col['id'] ] = [];
}
if ( ! array_key_exists( $phrase_col['column'], $groups[ $source_name ][ $phrase_col['table'] ][ $phrase_col['id'] ] ) ) {
$groups[ $source_name ][ $phrase_col['table'] ][ $phrase_col['id'] ][ $phrase_col['column'] ] = [];
}
$source = $this->index->get_source_by_name( $source_name );
$groups[ $source_name ][ $phrase_col['table'] ][ $phrase_col['id'] ][ $phrase_col['column'] ] = [
'attribute' => $source->get_attribute( $attribute ),
'value' => $phrase_col['value']
];
}
}
}
return $groups;
}
/**
* Retrieves Source Attributes that have Phrases support.
*
* @since 4.0
* @return array
*/
private function parse_sources_attributes() {
foreach ( $this->query->get_engine()->get_sources() as $source ) {
$applicable_source_attributes = array_filter(
array_map( function( Attribute $attribute ) use ( $source ) {
$phrases = $attribute->get_phrases();
$settings = $attribute->get_settings();
if ( is_string( $phrases ) ) {
$table = $source->get_db_table();
if ( ! Utils::valid_db_column( $table, $phrases ) ) {
return false;
}
$phrases = [ [
'table' => $source->get_db_table(),
'column' => $phrases,
'value' => $settings,
'id' => $source->get_db_id_column(),
] ];
}
else if( is_array( $phrases ) ){
$phrases[0]['value'] = $settings;
}
// We need to verify that the Attribute with phrase support has been added to the engine.
return $phrases && ! empty( $attribute->get_settings() ) ? $phrases : false;
}, $source->get_attributes() )
);
if ( ! empty( $applicable_source_attributes ) ) {
$this->attributes[ $source->get_name() ] = $applicable_source_attributes;
}
}
}
}