123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508 |
- <?php
- class SearchQuery extends SelectQueryExtender {
-
- protected $searchExpression;
-
- protected $type;
-
- protected $keys = array('positive' => array(), 'negative' => array());
-
- protected $simple = TRUE;
-
- protected $conditions;
-
- protected $matches = 0;
-
- protected $words = array();
-
- protected $normalize;
-
- protected $executedFirstPass = FALSE;
-
- protected $scores = array();
-
- protected $scoresArguments = array();
-
- protected $multiply = array();
-
- protected $expressionsIgnored = FALSE;
-
- public function searchExpression($expression, $module) {
- $this->searchExpression = $expression;
- $this->type = $module;
- return $this;
- }
-
- public function setOption($option, $column) {
- if ($values = search_expression_extract($this->searchExpression, $option)) {
- $or = db_or();
- foreach (explode(',', $values) as $value) {
- $or->condition($column, $value);
- }
- $this->condition($or);
- $this->searchExpression = search_expression_insert($this->searchExpression, $option);
- return TRUE;
- }
- return FALSE;
- }
-
- protected function parseSearchExpression() {
-
-
- preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $this->searchExpression , $keywords, PREG_SET_ORDER);
- if (count($keywords) == 0) {
- return;
- }
-
- $or = FALSE;
- $warning = '';
- $limit_combinations = variable_get('search_and_or_limit', 7);
-
- $and_count = -1;
- $or_count = 0;
- foreach ($keywords as $match) {
- if ($or_count && $and_count + $or_count >= $limit_combinations) {
-
-
- $this->expressionsIgnored = TRUE;
- break;
- }
- $phrase = FALSE;
-
- if ($match[2]{0} == '"') {
- $match[2] = substr($match[2], 1, -1);
- $phrase = TRUE;
- $this->simple = FALSE;
- }
-
-
-
- $words = search_simplify($match[2]);
-
-
- $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
-
- if ($match[1] == '-') {
- $this->keys['negative'] = array_merge($this->keys['negative'], $words);
- }
-
-
- elseif ($match[2] == 'OR' && count($this->keys['positive'])) {
- $last = array_pop($this->keys['positive']);
-
- if (!is_array($last)) {
- $last = array($last);
- }
- $this->keys['positive'][] = $last;
- $or = TRUE;
- $or_count++;
- continue;
- }
-
- elseif ($match[2] == 'AND' || $match[2] == 'and') {
- $warning = $match[2];
- continue;
- }
-
- else {
- if ($match[2] == 'or') {
- $warning = $match[2];
- }
- if ($or) {
-
- $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++;
- }
- }
- $or = FALSE;
- }
-
- $this->conditions = db_and();
- $simple_and = FALSE;
- $simple_or = FALSE;
-
- foreach ($this->keys['positive'] as $key) {
-
- if (is_array($key) && count($key)) {
- $simple_or = TRUE;
- $any = FALSE;
- $queryor = db_or();
- foreach ($key as $or) {
- list($num_new_scores) = $this->parseWord($or);
- $any |= $num_new_scores;
- $queryor->condition('d.data', "% $or %", 'LIKE');
- }
- if (count($queryor)) {
- $this->conditions->condition($queryor);
-
- $this->matches += ($any > 0);
- }
- }
-
- else {
- $simple_and = TRUE;
- list($num_new_scores, $num_valid_words) = $this->parseWord($key);
- $this->conditions->condition('d.data', "% $key %", 'LIKE');
- if (!$num_valid_words) {
- $this->simple = FALSE;
- }
-
- $this->matches += $num_new_scores;
- }
- }
- if ($simple_and && $simple_or) {
- $this->simple = FALSE;
- }
-
- foreach ($this->keys['negative'] as $key) {
- $this->conditions->condition('d.data', "% $key %", 'NOT LIKE');
- $this->simple = FALSE;
- }
- if ($warning == 'or') {
- drupal_set_message(t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
- }
- }
-
- protected function parseWord($word) {
- $num_new_scores = 0;
- $num_valid_words = 0;
-
- $split = explode(' ', $word);
- foreach ($split as $s) {
- $num = is_numeric($s);
- if ($num || drupal_strlen($s) >= variable_get('minimum_word_size', 3)) {
- if (!isset($this->words[$s])) {
- $this->words[$s] = $s;
- $num_new_scores++;
- }
- $num_valid_words++;
- }
- }
-
- return array($num_new_scores, $num_valid_words);
- }
-
- public function executeFirstPass() {
- $this->parseSearchExpression();
- if (count($this->words) == 0) {
- 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.'));
- return FALSE;
- }
- if ($this->expressionsIgnored) {
- 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');
- }
- $this->executedFirstPass = TRUE;
- if (!empty($this->words)) {
- $or = db_or();
- foreach ($this->words as $word) {
- $or->condition('i.word', $word);
- }
- $this->condition($or);
- }
-
- $this->join('search_total', 't', 'i.word = t.word');
- $this
- ->condition('i.type', $this->type)
- ->groupBy('i.type')
- ->groupBy('i.sid')
- ->having('COUNT(*) >= :matches', array(':matches' => $this->matches));
-
- $first = clone $this->query;
-
- if (!$this->simple) {
- $first->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
- $first->condition($this->conditions);
- }
-
- $first->addExpression('SUM(i.score * t.count)', 'calculated_score');
- $this->normalize = $first
- ->range(0, 1)
- ->orderBy('calculated_score', 'DESC')
- ->execute()
- ->fetchField();
- if ($this->normalize) {
- return TRUE;
- }
- return FALSE;
- }
-
- public function addScore($score, $arguments = array(), $multiply = FALSE) {
- if ($multiply) {
- $i = count($this->multiply);
- $score = "CAST(:multiply_$i AS DECIMAL) * COALESCE(( " . $score . "), 0) / CAST(:total_$i AS DECIMAL)";
- $arguments[':multiply_' . $i] = $multiply;
- $this->multiply[] = $multiply;
- }
- $this->scores[] = $score;
- $this->scoresArguments += $arguments;
- return $this;
- }
-
- public function execute()
- {
- if (!$this->executedFirstPass) {
- $this->executeFirstPass();
- }
- if (!$this->normalize) {
- return new DatabaseStatementEmpty();
- }
-
- $this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
- $this->condition($this->conditions);
- if (empty($this->scores)) {
-
- $this->addScore('i.relevance');
- }
- if (count($this->multiply)) {
-
-
- $i = 0;
- $sum = array_sum($this->multiply);
- foreach ($this->multiply as $total) {
- $this->scoresArguments[':total_' . $i] = $sum;
- $i++;
- }
- }
-
- $this->scores = str_replace('i.relevance', '(' . (1.0 / $this->normalize) . ' * i.score * t.count)', $this->scores);
-
- $this->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);
- if (count($this->getOrderBy()) == 0) {
-
- $this->orderBy('calculated_score', 'DESC');
- }
-
- $this
- ->addTag('search_' . $this->type)
- ->addMetaData('normalize', $this->normalize)
- ->fields('i', array('type', 'sid'));
- return $this->query->execute();
- }
-
- public function countQuery() {
-
- $inner = clone $this->query;
-
- $inner->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
- $inner->condition($this->conditions);
-
-
- $fields =& $inner->getFields();
- $fields = array();
- $expressions =& $inner->getExpressions();
- $expressions = array();
-
- $count = db_select($inner->fields('i', array('sid')), NULL, array('target' => 'slave'));
-
- $count->addExpression('COUNT(*)');
- return $count;
- }
- }
|