SearchQuery.php 20.2 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\search;

5
use Drupal\Core\Database\Query\Condition;
6
use Drupal\Core\Database\Query\SelectExtender;
7
use Drupal\Core\Database\Query\SelectInterface;
8 9

/**
10 11
 * Search query extender and helper functions.
 *
12
 * Performs a query on the full-text search index for a word or words.
13
 *
14 15 16 17 18
 * This query is used by search plugins that use the search index (not all
 * search plugins do, as some use a different searching mechanism). It
 * assumes you have set up a query on the {search_index} table with alias 'i',
 * and will only work if the user is searching for at least one "positive"
 * keyword or phrase.
19
 *
20 21 22 23 24
 * For efficiency, users of this query can run the prepareAndNormalize()
 * method to figure out if there are any search results, before fully setting
 * up and calling execute() to execute the query. The scoring expressions are
 * not needed until the execute() step. However, it's not really necessary
 * to do this, because this class's execute() method does that anyway.
25
 *
26 27
 * During both the prepareAndNormalize() and execute() steps, there can be
 * problems. Call getStatus() to figure out if the query is OK or not.
28
 *
29
 * The query object is given the tag 'search_$type' and can be further
30 31 32
 * extended with hook_query_alter().
 */
class SearchQuery extends SelectExtender {
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

  /**
   * Indicates no positive keywords were in the search expression.
   *
   * Positive keywords are words that are searched for, as opposed to negative
   * keywords, which are words that are excluded. To count as a keyword, a
   * word must be at least
   * \Drupal::config('search.settings')->get('index.minimum_word_size')
   * characters.
   *
   * @see SearchQuery::getStatus()
   */
  const NO_POSITIVE_KEYWORDS = 1;

  /**
   * Indicates that part of the search expression was ignored.
   *
   * To prevent Denial of Service attacks, only
   * \Drupal::config('search.settings')->get('and_or_limit') expressions
   * (positive keywords, phrases, negative keywords) are allowed; this flag
   * indicates that expressions existed past that limit and they were removed.
   *
   * @see SearchQuery::getStatus()
   */
  const EXPRESSIONS_IGNORED = 2;

  /**
   * Indicates that lower-case "or" was in the search expression.
   *
   * The word "or" in lower case was found in the search expression. This
   * probably means someone was trying to do an OR search but used lower-case
   * instead of upper-case.
   *
   * @see SearchQuery::getStatus()
   */
  const LOWER_CASE_OR = 4;

70
  /**
71 72 73 74 75 76 77 78
   * Indicates that no positive keyword matches were found.
   *
   * @see SearchQuery::getStatus()
   */
  const NO_KEYWORD_MATCHES = 8;

  /**
   * The keywords and advanced search options that are entered by the user.
79 80 81 82 83 84
   *
   * @var string
   */
  protected $searchExpression;

  /**
85
   * The type of search (search type).
86
   *
87 88
   * This maps to the value of the type column in search_index, and is usually
   * equal to the machine-readable name of the plugin or the search page.
89 90 91 92 93 94
   *
   * @var string
   */
  protected $type;

  /**
95
   * Parsed-out positive and negative search keys.
96 97 98
   *
   * @var array
   */
99
  protected $keys = ['positive' => [], 'negative' => []];
100 101

  /**
102
   * Indicates whether the query conditions are simple or complex (LIKE).
103
   *
104
   * @var bool
105 106 107 108 109 110
   */
  protected $simple = TRUE;

  /**
   * Conditions that are used for exact searches.
   *
111 112
   * This is always used for the second step in the query, but is not part of
   * the preparation step unless $this->simple is FALSE.
113
   *
114
   * @var Drupal\Core\Database\Query\ConditionInterface[]
115 116 117 118 119 120 121 122 123 124 125
   */
  protected $conditions;

  /**
   * Indicates how many matches for a search query are necessary.
   *
   * @var int
   */
  protected $matches = 0;

  /**
126
   * Array of positive search words.
127 128 129 130 131
   *
   * These words have to match against {search_index}.word.
   *
   * @var array
   */
132
  protected $words = [];
133 134

  /**
135
   * Multiplier to normalize the keyword score.
136
   *
137 138
   * This value is calculated by the preparation step, and is used as a
   * multiplier of the word scores to make sure they are between 0 and 1.
139 140 141
   *
   * @var float
   */
142
  protected $normalize = 0;
143 144

  /**
145
   * Indicates whether the preparation step has been executed.
146
   *
147
   * @var bool
148
   */
149
  protected $executedPrepare = FALSE;
150 151

  /**
152
   * A bitmap of status conditions, described in getStatus().
153
   *
154
   * @var int
155
   *
156
   * @see SearchQuery::getStatus()
157
   */
158
  protected $status = 0;
159 160

  /**
161
   * The word score expressions.
162 163
   *
   * @var array
164 165
   *
   * @see SearchQuery::addScore()
166
   */
167
  protected $scores = [];
168 169

  /**
170
   * Arguments for the score expressions.
171 172 173
   *
   * @var array
   */
174
  protected $scoresArguments = [];
175

176 177 178 179 180 181 182
  /**
   * The number of 'i.relevance' occurrences in score expressions.
   *
   * @var int
   */
  protected $relevance_count = 0;

183
  /**
184
   * Multipliers for score expressions.
185
   *
186
   * @var array
187
   */
188
  protected $multiply = [];
189 190

  /**
191
   * Sets the search query expression.
192
   *
193
   * @param string $expression
194
   *   A search string, which can contain keywords and options.
195
   * @param string $type
196
   *   The search type. This maps to {search_index}.type in the database.
197
   *
198
   * @return $this
199
   */
200
  public function searchExpression($expression, $type) {
201
    $this->searchExpression = $expression;
202
    $this->type = $type;
203

204 205 206 207
    // Add query tag.
    $this->addTag('search_' . $type);

    // Initialize conditions and status.
208
    $this->conditions = new Condition('AND');
209 210
    $this->status = 0;

211 212 213 214 215 216
    return $this;
  }

  /**
   * Parses the search query into SQL conditions.
   *
217 218 219 220 221 222
   * Sets up the following variables:
   * - $this->keys
   * - $this->words
   * - $this->conditions
   * - $this->simple
   * - $this->matches
223 224
   */
  protected function parseSearchExpression() {
225
    // Matches words optionally prefixed by a - sign. A word in this case is
226
    // something between two spaces, optionally quoted.
227
    preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $this->searchExpression, $keywords, PREG_SET_ORDER);
228

229
    if (count($keywords) == 0) {
230 231 232 233
      return;
    }

    // Classify tokens.
234
    $in_or = FALSE;
235
    $limit_combinations = \Drupal::config('search.settings')->get('and_or_limit');
236 237 238 239 240 241 242
    // The first search expression does not count as AND.
    $and_count = -1;
    $or_count = 0;
    foreach ($keywords as $match) {
      if ($or_count && $and_count + $or_count >= $limit_combinations) {
        // Ignore all further search expressions to prevent Denial-of-Service
        // attacks using a high number of AND/OR combinations.
243
        $this->status |= SearchQuery::EXPRESSIONS_IGNORED;
244 245
        break;
      }
246

247
      // Strip off phrase quotes.
248
      $phrase = FALSE;
249
      if ($match[2][0] == '"') {
250 251 252 253
        $match[2] = substr($match[2], 1, -1);
        $phrase = TRUE;
        $this->simple = FALSE;
      }
254

255 256 257 258 259 260
      // Simplify keyword according to indexing rules and external
      // preprocessors. Use same process as during search indexing, so it
      // will match search index.
      $words = search_simplify($match[2]);
      // Re-explode in case simplification added more words, except when
      // matching a phrase.
261
      $words = $phrase ? [$words] : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
262 263 264 265 266 267 268 269 270 271
      // Negative matches.
      if ($match[1] == '-') {
        $this->keys['negative'] = array_merge($this->keys['negative'], $words);
      }
      // OR operator: instead of a single keyword, we store an array of all
      // OR'd keywords.
      elseif ($match[2] == 'OR' && count($this->keys['positive'])) {
        $last = array_pop($this->keys['positive']);
        // Starting a new OR?
        if (!is_array($last)) {
272
          $last = [$last];
273 274
        }
        $this->keys['positive'][] = $last;
275
        $in_or = TRUE;
276 277 278 279 280 281 282 283 284 285 286
        $or_count++;
        continue;
      }
      // AND operator: implied, so just ignore it.
      elseif ($match[2] == 'AND' || $match[2] == 'and') {
        continue;
      }

      // Plain keyword.
      else {
        if ($match[2] == 'or') {
287 288
          // Lower-case "or" instead of "OR" is a warning condition.
          $this->status |= SearchQuery::LOWER_CASE_OR;
289
        }
290
        if ($in_or) {
291 292 293 294 295 296 297 298
          // Add to last element (which is an array).
          $this->keys['positive'][count($this->keys['positive']) - 1] = array_merge($this->keys['positive'][count($this->keys['positive']) - 1], $words);
        }
        else {
          $this->keys['positive'] = array_merge($this->keys['positive'], $words);
          $and_count++;
        }
      }
299
      $in_or = FALSE;
300 301 302
    }

    // Convert keywords into SQL statements.
303 304
    $has_and = FALSE;
    $has_or = FALSE;
305 306 307 308
    // Positive matches.
    foreach ($this->keys['positive'] as $key) {
      // Group of ORed terms.
      if (is_array($key) && count($key)) {
309 310 311 312 313 314 315
        // If we had already found one OR, this is another one AND-ed with the
        // first, meaning it is not a simple query.
        if ($has_or) {
          $this->simple = FALSE;
        }
        $has_or = TRUE;
        $has_new_scores = FALSE;
316
        $queryor = new Condition('OR');
317 318
        foreach ($key as $or) {
          list($num_new_scores) = $this->parseWord($or);
319
          $has_new_scores |= $num_new_scores;
320 321 322 323 324
          $queryor->condition('d.data', "% $or %", 'LIKE');
        }
        if (count($queryor)) {
          $this->conditions->condition($queryor);
          // A group of OR keywords only needs to match once.
325
          $this->matches += ($has_new_scores > 0);
326 327 328 329
        }
      }
      // Single ANDed term.
      else {
330
        $has_and = TRUE;
331 332 333 334 335 336 337 338 339
        list($num_new_scores, $num_valid_words) = $this->parseWord($key);
        $this->conditions->condition('d.data', "% $key %", 'LIKE');
        if (!$num_valid_words) {
          $this->simple = FALSE;
        }
        // Each AND keyword needs to match at least once.
        $this->matches += $num_new_scores;
      }
    }
340
    if ($has_and && $has_or) {
341 342
      $this->simple = FALSE;
    }
343

344 345 346 347 348 349 350 351
    // Negative matches.
    foreach ($this->keys['negative'] as $key) {
      $this->conditions->condition('d.data', "% $key %", 'NOT LIKE');
      $this->simple = FALSE;
    }
  }

  /**
352 353 354 355 356
   * Parses a word or phrase for parseQuery().
   *
   * Splits a phrase into words. Adds its words to $this->words, if it is not
   * already there. Returns a list containing the number of new words found,
   * and the total number of words in the phrase.
357 358 359 360
   */
  protected function parseWord($word) {
    $num_new_scores = 0;
    $num_valid_words = 0;
361

362 363 364 365
    // Determine the scorewords of this word/phrase.
    $split = explode(' ', $word);
    foreach ($split as $s) {
      $num = is_numeric($s);
366
      if ($num || mb_strlen($s) >= \Drupal::config('search.settings')->get('index.minimum_word_size')) {
367 368 369 370 371 372 373
        if (!isset($this->words[$s])) {
          $this->words[$s] = $s;
          $num_new_scores++;
        }
        $num_valid_words++;
      }
    }
374

375
    // Return matching snippet and number of added words.
376
    return [$num_new_scores, $num_valid_words];
377 378 379
  }

  /**
380
   * Prepares the query and calculates the normalization factor.
381
   *
382 383
   * After the query is normalized the keywords are weighted to give the results
   * a relevancy score. The query is ready for execution after this.
384
   *
385 386 387 388 389
   * Error and warning conditions can apply. Call getStatus() after calling
   * this method to retrieve them.
   *
   * @return bool
   *   TRUE if at least one keyword matched the search index; FALSE if not.
390
   */
391
  public function prepareAndNormalize() {
392
    $this->parseSearchExpression();
393
    $this->executedPrepare = TRUE;
394 395

    if (count($this->words) == 0) {
396 397 398 399
      // Although the query could proceed, there is no point in joining
      // with other tables and attempting to normalize if there are no
      // keywords present.
      $this->status |= SearchQuery::NO_POSITIVE_KEYWORDS;
400 401
      return FALSE;
    }
402

403
    // Build the basic search query: match the entered keywords.
404
    $or = new Condition('OR');
405 406
    foreach ($this->words as $word) {
      $or->condition('i.word', $word);
407
    }
408 409 410
    $this->condition($or);

    // Add keyword normalization information to the query.
411 412 413 414
    $this->join('search_total', 't', 'i.word = t.word');
    $this
      ->condition('i.type', $this->type)
      ->groupBy('i.type')
415 416 417 418 419 420 421
      ->groupBy('i.sid');

    // If the query is simple, we should have calculated the number of
    // matching words we need to find, so impose that criterion. For non-
    // simple queries, this condition could lead to incorrectly deciding not
    // to continue with the full query.
    if ($this->simple) {
422
      $this->having('COUNT(*) >= :matches', [':matches' => $this->matches]);
423
    }
424

425 426
    // Clone the query object to calculate normalization.
    $normalize_query = clone $this->query;
427

428 429
    // For complex search queries, add the LIKE conditions; if the query is
    // simple, we do not need them for normalization.
430
    if (!$this->simple) {
431 432 433 434
      $normalize_query->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode');
      if (count($this->conditions)) {
        $normalize_query->condition($this->conditions);
      }
435 436
    }

437 438 439 440 441
    // Calculate normalization, which is the max of all the search scores for
    // positive keywords in the query. And note that the query could have other
    // fields added to it by the user of this extension.
    $normalize_query->addExpression('SUM(i.score * t.count)', 'calculated_score');
    $result = $normalize_query
442 443 444
      ->range(0, 1)
      ->orderBy('calculated_score', 'DESC')
      ->execute()
445 446 447 448
      ->fetchObject();
    if (isset($result->calculated_score)) {
      $this->normalize = (float) $result->calculated_score;
    }
449 450 451 452

    if ($this->normalize) {
      return TRUE;
    }
453 454 455 456

    // If the normalization value was zero, that indicates there were no
    // matches to the supplied positive keywords.
    $this->status |= SearchQuery::NO_KEYWORD_MATCHES;
457 458 459
    return FALSE;
  }

460
  /**
461
   * {@inheritdoc}
462 463 464 465 466 467 468 469 470 471 472 473 474
   */
  public function preExecute(SelectInterface $query = NULL) {
    if (!$this->executedPrepare) {
      $this->prepareAndNormalize();
    }

    if (!$this->normalize) {
      return FALSE;
    }

    return parent::preExecute($query);
  }

475 476 477
  /**
   * Adds a custom score expression to the search query.
   *
478 479 480 481 482
   * Score expressions are used to order search results. If no calls to
   * addScore() have taken place, a default keyword relevance score will be
   * used. However, if at least one call to addScore() has taken place, the
   * keyword relevance score is not automatically added.
   *
483 484 485 486
   * Note that you must use this method to add ordering to your searches, and
   * not call orderBy() directly, when using the SearchQuery extender. This is
   * because of the two-pass system the SearchQuery class uses to normalize
   * scores.
487
   *
488
   * @param string $score
489 490 491
   *   The score expression, which should evaluate to a number between 0 and 1.
   *   The string 'i.relevance' in a score expression will be replaced by a
   *   measure of keyword relevance between 0 and 1.
492
   * @param array $arguments
493
   *   Query arguments needed to provide values to the score expression.
494
   * @param float $multiply
495 496 497
   *   If set, the score is multiplied with this value. However, all scores
   *   with multipliers are then divided by the total of all multipliers, so
   *   that overall, the normalization is maintained.
498
   *
499
   * @return $this
500
   */
501
  public function addScore($score, $arguments = [], $multiply = FALSE) {
502 503
    if ($multiply) {
      $i = count($this->multiply);
504
      // Modify the score expression so it is multiplied by the multiplier,
505 506 507 508 509 510
      // with a divisor to renormalize. Note that the ROUND here is necessary
      // for PostgreSQL and SQLite in order to ensure that the :multiply_* and
      // :total_* arguments are treated as a numeric type, because the
      // PostgreSQL PDO driver sometimes puts values in as strings instead of
      // numbers in complex expressions like this.
      $score = "(ROUND(:multiply_$i, 4)) * COALESCE(($score), 0) / (ROUND(:total_$i, 4))";
511 512 513
      // Add an argument for the multiplier. The :total_$i argument is taken
      // care of in the execute() method, which is when the total divisor is
      // calculated.
514 515 516 517
      $arguments[':multiply_' . $i] = $multiply;
      $this->multiply[] = $multiply;
    }

518 519 520 521 522
    // Search scoring needs a way to include a keyword relevance in the score.
    // For historical reasons, this is done by putting 'i.relevance' into the
    // search expression. So, use string replacement to change this to a
    // calculated query expression, counting the number of occurrences so
    // in the execute() method we can add arguments.
523
    while (strpos($score, 'i.relevance') !== FALSE) {
524
      $pieces = explode('i.relevance', $score, 2);
525
      $score = implode('((ROUND(:normalization_' . $this->relevance_count . ', 4)) * i.score * t.count)', $pieces);
526 527 528
      $this->relevance_count++;
    }

529 530 531 532 533 534 535 536 537
    $this->scores[] = $score;
    $this->scoresArguments += $arguments;

    return $this;
  }

  /**
   * Executes the search.
   *
538 539
   * The complex conditions are applied to the query including score
   * expressions and ordering.
540 541 542
   *
   * Error and warning conditions can apply. Call getStatus() after calling
   * this method to retrieve them.
543
   *
544
   * @return \Drupal\Core\Database\StatementInterface|null
545
   *   A query result set containing the results of the query.
546
   */
547
  public function execute() {
548 549
    if (!$this->preExecute($this)) {
      return NULL;
550 551
    }

552 553 554 555 556
    // Add conditions to the query.
    $this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode');
    if (count($this->conditions)) {
      $this->condition($this->conditions);
    }
557

558
    // Add default score (keyword relevance) if there are not any defined.
559 560 561 562 563
    if (empty($this->scores)) {
      $this->addScore('i.relevance');
    }

    if (count($this->multiply)) {
564 565 566
      // Re-normalize scores with multipliers by dividing by the total of all
      // multipliers. The expressions were altered in addScore(), so here just
      // add the arguments for the total.
567
      $sum = array_sum($this->multiply);
568
      for ($i = 0; $i < count($this->multiply); $i++) {
569 570 571 572
        $this->scoresArguments[':total_' . $i] = $sum;
      }
    }

573 574
    // Add arguments for the keyword relevance normalization number.
    $normalization = 1.0 / $this->normalize;
575
    for ($i = 0; $i < $this->relevance_count; $i++) {
576 577
      $this->scoresArguments[':normalization_' . $i] = $normalization;
    }
578 579

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

582 583
    // If an order has not yet been set for this query, add a default order
    // that sorts by the calculated sum of scores.
584 585 586 587
    if (count($this->getOrderBy()) == 0) {
      $this->orderBy('calculated_score', 'DESC');
    }

588
    // Add query metadata.
589 590
    $this
      ->addMetaData('normalize', $this->normalize)
591
      ->fields('i', ['type', 'sid']);
592 593 594 595 596 597 598 599 600 601 602
    return $this->query->execute();
  }

  /**
   * Builds the default count query for SearchQuery.
   *
   * Since SearchQuery always uses GROUP BY, we can default to a subquery. We
   * also add the same conditions as execute() because countQuery() is called
   * first.
   */
  public function countQuery() {
603 604 605 606
    if (!$this->executedPrepare) {
      $this->prepareAndNormalize();
    }

607 608 609 610 611
    // Clone the inner query.
    $inner = clone $this->query;

    // Add conditions to query.
    $inner->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
612 613 614
    if (count($this->conditions)) {
      $inner->condition($this->conditions);
    }
615 616 617 618

    // Remove existing fields and expressions, they are not needed for a count
    // query.
    $fields =& $inner->getFields();
619
    $fields = [];
620
    $expressions =& $inner->getExpressions();
621
    $expressions = [];
622

623
    // Add sid as the only field and count them as a subquery.
624
    $count = $this->connection->select($inner->fields('i', ['sid']), NULL);
625 626 627 628 629 630

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

    return $count;
  }
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

  /**
   * Returns the query status bitmap.
   *
   * @return int
   *   A bitmap indicating query status. Zero indicates there were no problems.
   *   A non-zero value is a combination of one or more of the following flags:
   *   - SearchQuery::NO_POSITIVE_KEYWORDS
   *   - SearchQuery::EXPRESSIONS_IGNORED
   *   - SearchQuery::LOWER_CASE_OR
   *   - SearchQuery::NO_KEYWORD_MATCHES
   */
  public function getStatus() {
    return $this->status;
  }

647
}