Projet

Général

Profil

Paste
Télécharger (16,5 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / search / search.extender.inc @ 85ad3d82

1
<?php
2

    
3
/**
4
 * @file
5
 * Search query extender and helper functions.
6
 */
7

    
8
/**
9
 * Do a query on the full-text search index for a word or words.
10
 *
11
 * This function is normally only called by each module that supports the
12
 * indexed search (and thus, implements hook_update_index()).
13
 *
14
 * Results are retrieved in two logical passes. However, the two passes are
15
 * joined together into a single query. And in the case of most simple
16
 * queries the second pass is not even used.
17
 *
18
 * The first pass selects a set of all possible matches, which has the benefit
19
 * of also providing the exact result set for simple "AND" or "OR" searches.
20
 *
21
 * The second portion of the query further refines this set by verifying
22
 * advanced text conditions (such as negative or phrase matches).
23
 *
24
 * The used query object has the tag 'search_$module' and can be further
25
 * extended with hook_query_alter().
26
 */
27
class SearchQuery extends SelectQueryExtender {
28
  /**
29
   * The search query that is used for searching.
30
   *
31
   * @var string
32
   */
33
  protected $searchExpression;
34

    
35
  /**
36
   * Type of search (search module).
37
   *
38
   * This maps to the value of the type column in search_index, and is equal
39
   * to the machine-readable name of the module that implements
40
   * hook_search_info().
41
   *
42
   * @var string
43
   */
44
  protected $type;
45

    
46
  /**
47
   * Positive and negative search keys.
48
   *
49
   * @var array
50
   */
51
  protected $keys = array('positive' => array(), 'negative' => array());
52

    
53
  /**
54
   * Indicates whether the first pass query requires complex conditions (LIKE).
55
   *
56
   * @var boolean.
57
   */
58
  protected $simple = TRUE;
59

    
60
  /**
61
   * Conditions that are used for exact searches.
62
   *
63
   * This is always used for the second pass query but not for the first pass,
64
   * unless $this->simple is FALSE.
65
   *
66
   * @var DatabaseCondition
67
   */
68
  protected $conditions;
69

    
70
  /**
71
   * Indicates how many matches for a search query are necessary.
72
   *
73
   * @var int
74
   */
75
  protected $matches = 0;
76

    
77
  /**
78
   * Array of search words.
79
   *
80
   * These words have to match against {search_index}.word.
81
   *
82
   * @var array
83
   */
84
  protected $words = array();
85

    
86
  /**
87
   * Multiplier for the normalized search score.
88
   *
89
   * This value is calculated by the first pass query and multiplied with the
90
   * actual score of a specific word to make sure that the resulting calculated
91
   * score is between 0 and 1.
92
   *
93
   * @var float
94
   */
95
  protected $normalize;
96

    
97
  /**
98
   * Indicates whether the first pass query has been executed.
99
   *
100
   * @var boolean
101
   */
102
  protected $executedFirstPass = FALSE;
103

    
104
  /**
105
   * Stores score expressions.
106
   *
107
   * @var array
108
   *
109
   * @see addScore()
110
   */
111
  protected $scores = array();
112

    
113
  /**
114
   * Stores arguments for score expressions.
115
   *
116
   * @var array
117
   */
118
  protected $scoresArguments = array();
119

    
120
  /**
121
   * Stores multipliers for score expressions.
122
   *
123
   * @var array
124
   */
125
  protected $multiply = array();
126

    
127
  /**
128
   * Whether or not search expressions were ignored.
129
   *
130
   * The maximum number of AND/OR combinations exceeded can be configured to
131
   * avoid Denial-of-Service attacks. Expressions beyond the limit are ignored.
132
   *
133
   * @var boolean
134
   */
135
  protected $expressionsIgnored = FALSE;
136

    
137
  /**
138
   * Sets up the search query expression.
139
   *
140
   * @param $query
141
   *   A search query string, which can contain options.
142
   * @param $module
143
   *   The search module. This maps to {search_index}.type in the database.
144
   *
145
   * @return
146
   *   The SearchQuery object.
147
   */
148
  public function searchExpression($expression, $module) {
149
    $this->searchExpression = $expression;
150
    $this->type = $module;
151

    
152
    return $this;
153
  }
154

    
155
  /**
156
   * Applies a search option and removes it from the search query string.
157
   *
158
   * These options are in the form option:value,value2,value3.
159
   *
160
   * @param $option
161
   *   Name of the option.
162
   * @param $column
163
   *   Name of the database column to which the value should be applied.
164
   *
165
   * @return
166
   *   TRUE if a value for that option was found, FALSE if not.
167
   */
168
  public function setOption($option, $column) {
169
    if ($values = search_expression_extract($this->searchExpression, $option)) {
170
      $or = db_or();
171
      foreach (explode(',', $values) as $value) {
172
        $or->condition($column, $value);
173
      }
174
      $this->condition($or);
175
      $this->searchExpression = search_expression_insert($this->searchExpression, $option);
176
      return TRUE;
177
    }
178
    return FALSE;
179
  }
180

    
181
  /**
182
   * Parses the search query into SQL conditions.
183
   *
184
   * We build two queries that match the dataset bodies.
185
   */
186
  protected function parseSearchExpression() {
187
    // Matchs words optionally prefixed by a dash. A word in this case is
188
    // something between two spaces, optionally quoted.
189
    preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' .  $this->searchExpression , $keywords, PREG_SET_ORDER);
190

    
191
    if (count($keywords) ==  0) {
192
      return;
193
    }
194

    
195
    // Classify tokens.
196
    $or = FALSE;
197
    $warning = '';
198
    $limit_combinations = variable_get('search_and_or_limit', 7);
199
    // The first search expression does not count as AND.
200
    $and_count = -1;
201
    $or_count = 0;
202
    foreach ($keywords as $match) {
203
      if ($or_count && $and_count + $or_count >= $limit_combinations) {
204
        // Ignore all further search expressions to prevent Denial-of-Service
205
        // attacks using a high number of AND/OR combinations.
206
        $this->expressionsIgnored = TRUE;
207
        break;
208
      }
209
      $phrase = FALSE;
210
      // Strip off phrase quotes.
211
      if ($match[2]{0} == '"') {
212
        $match[2] = substr($match[2], 1, -1);
213
        $phrase = TRUE;
214
        $this->simple = FALSE;
215
      }
216
      // Simplify keyword according to indexing rules and external
217
      // preprocessors. Use same process as during search indexing, so it
218
      // will match search index.
219
      $words = search_simplify($match[2]);
220
      // Re-explode in case simplification added more words, except when
221
      // matching a phrase.
222
      $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
223
      // Negative matches.
224
      if ($match[1] == '-') {
225
        $this->keys['negative'] = array_merge($this->keys['negative'], $words);
226
      }
227
      // OR operator: instead of a single keyword, we store an array of all
228
      // OR'd keywords.
229
      elseif ($match[2] == 'OR' && count($this->keys['positive'])) {
230
        $last = array_pop($this->keys['positive']);
231
        // Starting a new OR?
232
        if (!is_array($last)) {
233
          $last = array($last);
234
        }
235
        $this->keys['positive'][] = $last;
236
        $or = TRUE;
237
        $or_count++;
238
        continue;
239
      }
240
      // AND operator: implied, so just ignore it.
241
      elseif ($match[2] == 'AND' || $match[2] == 'and') {
242
        $warning = $match[2];
243
        continue;
244
      }
245

    
246
      // Plain keyword.
247
      else {
248
        if ($match[2] == 'or') {
249
          $warning = $match[2];
250
        }
251
        if ($or) {
252
          // Add to last element (which is an array).
253
          $this->keys['positive'][count($this->keys['positive']) - 1] = array_merge($this->keys['positive'][count($this->keys['positive']) - 1], $words);
254
        }
255
        else {
256
          $this->keys['positive'] = array_merge($this->keys['positive'], $words);
257
          $and_count++;
258
        }
259
      }
260
      $or = FALSE;
261
    }
262

    
263
    // Convert keywords into SQL statements.
264
    $this->conditions = db_and();
265
    $simple_and = FALSE;
266
    $simple_or = FALSE;
267
    // Positive matches.
268
    foreach ($this->keys['positive'] as $key) {
269
      // Group of ORed terms.
270
      if (is_array($key) && count($key)) {
271
        $simple_or = TRUE;
272
        $any = FALSE;
273
        $queryor = db_or();
274
        foreach ($key as $or) {
275
          list($num_new_scores) = $this->parseWord($or);
276
          $any |= $num_new_scores;
277
          $queryor->condition('d.data', "% $or %", 'LIKE');
278
        }
279
        if (count($queryor)) {
280
          $this->conditions->condition($queryor);
281
          // A group of OR keywords only needs to match once.
282
          $this->matches += ($any > 0);
283
        }
284
      }
285
      // Single ANDed term.
286
      else {
287
        $simple_and = TRUE;
288
        list($num_new_scores, $num_valid_words) = $this->parseWord($key);
289
        $this->conditions->condition('d.data', "% $key %", 'LIKE');
290
        if (!$num_valid_words) {
291
          $this->simple = FALSE;
292
        }
293
        // Each AND keyword needs to match at least once.
294
        $this->matches += $num_new_scores;
295
      }
296
    }
297
    if ($simple_and && $simple_or) {
298
      $this->simple = FALSE;
299
    }
300
    // Negative matches.
301
    foreach ($this->keys['negative'] as $key) {
302
      $this->conditions->condition('d.data', "% $key %", 'NOT LIKE');
303
      $this->simple = FALSE;
304
    }
305

    
306
    if ($warning == 'or') {
307
      drupal_set_message(t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
308
    }
309
  }
310

    
311
  /**
312
   * Helper function for parseQuery().
313
   */
314
  protected function parseWord($word) {
315
    $num_new_scores = 0;
316
    $num_valid_words = 0;
317
    // Determine the scorewords of this word/phrase.
318
    $split = explode(' ', $word);
319
    foreach ($split as $s) {
320
      $num = is_numeric($s);
321
      if ($num || drupal_strlen($s) >= variable_get('minimum_word_size', 3)) {
322
        if (!isset($this->words[$s])) {
323
          $this->words[$s] = $s;
324
          $num_new_scores++;
325
        }
326
        $num_valid_words++;
327
      }
328
    }
329
    // Return matching snippet and number of added words.
330
    return array($num_new_scores, $num_valid_words);
331
  }
332

    
333
  /**
334
   * Executes the first pass query.
335
   *
336
   * This can either be done explicitly, so that additional scores and
337
   * conditions can be applied to the second pass query, or implicitly by
338
   * addScore() or execute().
339
   *
340
   * @return
341
   *   TRUE if search items exist, FALSE if not.
342
   */
343
  public function executeFirstPass() {
344
    $this->parseSearchExpression();
345

    
346
    if (count($this->words) == 0) {
347
      form_set_error('keys', format_plural(variable_get('minimum_word_size', 3), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.'));
348
      return FALSE;
349
    }
350
    if ($this->expressionsIgnored) {
351
      drupal_set_message(t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => variable_get('search_and_or_limit', 7))), 'warning');
352
    }
353
    $this->executedFirstPass = TRUE;
354

    
355
    if (!empty($this->words)) {
356
      $or = db_or();
357
      foreach ($this->words as $word) {
358
        $or->condition('i.word', $word);
359
      }
360
      $this->condition($or);
361
    }
362
    // Build query for keyword normalization.
363
    $this->join('search_total', 't', 'i.word = t.word');
364
    $this
365
      ->condition('i.type', $this->type)
366
      ->groupBy('i.type')
367
      ->groupBy('i.sid')
368
      ->having('COUNT(*) >= :matches', array(':matches' => $this->matches));
369

    
370
    // Clone the query object to do the firstPass query;
371
    $first = clone $this->query;
372

    
373
    // For complex search queries, add the LIKE conditions to the first pass query.
374
    if (!$this->simple) {
375
      $first->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
376
      $first->condition($this->conditions);
377
    }
378

    
379
    // Calculate maximum keyword relevance, to normalize it.
380
    $first->addExpression('SUM(i.score * t.count)', 'calculated_score');
381
    $this->normalize = $first
382
      ->range(0, 1)
383
      ->orderBy('calculated_score', 'DESC')
384
      ->execute()
385
      ->fetchField();
386

    
387
    if ($this->normalize) {
388
      return TRUE;
389
    }
390
    return FALSE;
391
  }
392

    
393
  /**
394
   * Adds a custom score expression to the search query.
395
   *
396
   * Score expressions are used to order search results. If no calls to
397
   * addScore() have taken place, a default keyword relevance score will be
398
   * used. However, if at least one call to addScore() has taken place, the
399
   * keyword relevance score is not automatically added.
400
   *
401
   * Also note that if you call orderBy() directly on the query, search scores
402
   * will not automatically be used to order search results. Your orderBy()
403
   * expression can reference 'calculated_score', which will be the total
404
   * calculated score value.
405
   *
406
   * @param $score
407
   *   The score expression, which should evaluate to a number between 0 and 1.
408
   *   The string 'i.relevance' in a score expression will be replaced by a
409
   *   measure of keyword relevance between 0 and 1.
410
   * @param $arguments
411
   *   Query arguments needed to provide values to the score expression.
412
   * @param $multiply
413
   *   If set, the score is multiplied with this value. However, all scores
414
   *   with multipliers are then divided by the total of all multipliers, so
415
   *   that overall, the normalization is maintained.
416
   *
417
   * @return object
418
   *   The updated query object.
419
   */
420
  public function addScore($score, $arguments = array(), $multiply = FALSE) {
421
    if ($multiply) {
422
      $i = count($this->multiply);
423
      // Modify the score expression so it is multiplied by the multiplier,
424
      // with a divisor to renormalize.
425
      $score = "CAST(:multiply_$i AS DECIMAL) * COALESCE(( " . $score . "), 0) / CAST(:total_$i AS DECIMAL)";
426
      // Add an argument for the multiplier. The :total_$i argument is taken
427
      // care of in the execute() method, which is when the total divisor is
428
      // calculated.
429
      $arguments[':multiply_' . $i] = $multiply;
430
      $this->multiply[] = $multiply;
431
    }
432

    
433
    $this->scores[] = $score;
434
    $this->scoresArguments += $arguments;
435

    
436
    return $this;
437
  }
438

    
439
  /**
440
   * Executes the search.
441
   *
442
   * If not already done, this executes the first pass query. Then the complex
443
   * conditions are applied to the query including score expressions and
444
   * ordering.
445
   *
446
   * @return
447
   *   FALSE if the first pass query returned no results, and a database result
448
   *   set if there were results.
449
   */
450
  public function execute()
451
  {
452
    if (!$this->executedFirstPass) {
453
      $this->executeFirstPass();
454
    }
455
    if (!$this->normalize) {
456
      return new DatabaseStatementEmpty();
457
    }
458

    
459
    // Add conditions to query.
460
    $this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
461
    $this->condition($this->conditions);
462

    
463
    if (empty($this->scores)) {
464
      // Add default score.
465
      $this->addScore('i.relevance');
466
    }
467

    
468
    if (count($this->multiply)) {
469
      // Re-normalize scores with multipliers by dividing by the total of all
470
      // multipliers. The expressions were altered in addScore(), so here just
471
      // add the arguments for the total.
472
      $i = 0;
473
      $sum = array_sum($this->multiply);
474
      foreach ($this->multiply as $total) {
475
        $this->scoresArguments[':total_' . $i] = $sum;
476
        $i++;
477
      }
478
    }
479

    
480
    // Replace the pseudo-expression 'i.relevance' with a measure of keyword
481
    // relevance in all score expressions, using string replacement. Careful
482
    // though! If you just print out a float, some locales use ',' as the
483
    // decimal separator in PHP, while SQL always uses '.'. So, make sure to
484
    // set the number format correctly.
485
    $relevance = number_format((1.0 / $this->normalize), 10, '.', '');
486
    $this->scores = str_replace('i.relevance', '(' . $relevance . ' * i.score * t.count)', $this->scores);
487

    
488
    // Add all scores together to form a query field.
489
    $this->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);
490

    
491
    // If an order has not yet been set for this query, add a default order
492
    // that sorts by the calculated sum of scores.
493
    if (count($this->getOrderBy()) == 0) {
494
      $this->orderBy('calculated_score', 'DESC');
495
    }
496

    
497
    // Add tag and useful metadata.
498
    $this
499
      ->addTag('search_' . $this->type)
500
      ->addMetaData('normalize', $this->normalize)
501
      ->fields('i', array('type', 'sid'));
502

    
503
    return $this->query->execute();
504
  }
505

    
506
  /**
507
   * Builds the default count query for SearchQuery.
508
   *
509
   * Since SearchQuery always uses GROUP BY, we can default to a subquery. We
510
   * also add the same conditions as execute() because countQuery() is called
511
   * first.
512
   */
513
  public function countQuery() {
514
    // Clone the inner query.
515
    $inner = clone $this->query;
516

    
517
    // Add conditions to query.
518
    $inner->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
519
    $inner->condition($this->conditions);
520

    
521
    // Remove existing fields and expressions, they are not needed for a count
522
    // query.
523
    $fields =& $inner->getFields();
524
    $fields = array();
525
    $expressions =& $inner->getExpressions();
526
    $expressions = array();
527

    
528
    // Add the sid as the only field and count them as a subquery.
529
    $count = db_select($inner->fields('i', array('sid')), NULL, array('target' => 'slave'));
530

    
531
    // Add the COUNT() expression.
532
    $count->addExpression('COUNT(*)');
533

    
534
    return $count;
535
  }
536
}