You are here

function apachesolr_autocomplete_suggest_additional_term in Apache Solr Autocomplete 7.2

Same name and namespace in other branches
  1. 6 apachesolr_autocomplete.module \apachesolr_autocomplete_suggest_additional_term()
  2. 7 apachesolr_autocomplete.module \apachesolr_autocomplete_suggest_additional_term()

Helper function that suggests additional terms to search for.

For example, if $keys = "learn", this might return suggestions like: learn student, learn school, learn mathematics. The suggested terms are returned in order of frequency (most frequent first).

File

./apachesolr_autocomplete.module, line 334
Alters search forms to suggest terms using Apache Solr using AJAX.

Code

function apachesolr_autocomplete_suggest_additional_term($keys, $context) {
  $keys = trim($keys);
  $keys = check_plain($keys);
  if ($keys == '') {
    return array();
  }

  // Return no suggestions when $keys consists of only word delimiters
  if (drupal_strlen(preg_replace('/[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . ']+/u', '', $keys)) < 1) {
    return array();
  }

  // Initialize arrays
  $suggestions = array();

  // Get array of suggestions.
  $result = apachesolr_autocomplete_suggest($context['solr'], $keys, $context['apachesolr_params'], $context['suggestions_to_return']);
  if ($result && $context['engines']['additional_term']['suggest_keywords']) {
    if (isset($result['suggestions']) && sizeof($result['suggestions'])) {

      // Concatenate the original terms with the returned suggestion.
      $tmp = array();
      foreach ($result['suggestions'] as $key => $value) {
        $key = substr($key, 1);
        $value['value'] = $keys . ' ' . $value['value'];
        $tmp["*{$keys} {$key}"] = $value;
      }
      $suggestions = array_merge($suggestions, $tmp);
    }
  }

  // Suggest using the spellchecker.
  if ($context['engines']['additional_term']['spellcheck_suggest']) {
    if (isset($result['response']->spellcheck) && isset($result['response']->spellcheck->suggestions)) {
      $spellcheck_suggestions = get_object_vars($result['response']->spellcheck->suggestions);
      $replacements = array();
      foreach ($spellcheck_suggestions as $word => $value) {
        $replacements[$word] = $value->suggestion[0];
      }
      if (count($replacements)) {
        $new_keywords = strtr($keys, $replacements);
        if ($new_keywords != $keys) {

          // Place spellchecker suggestion before others
          $suggestion = array(
            'value' => $new_keywords,
            'theme' => 'spellchecker',
          );
          $suggestions = array_merge(array(
            '*' . $new_keywords => $suggestion,
          ), $suggestions);
        }
      }
    }
  }
  return $suggestions;
}