handler_filter_fulltext.inc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <?php
  2. /**
  3. * @file
  4. * Contains SearchApiViewsHandlerFilterFulltext.
  5. */
  6. /**
  7. * Views filter handler class for handling fulltext fields.
  8. */
  9. class SearchApiViewsHandlerFilterFulltext extends SearchApiViewsHandlerFilterText {
  10. /**
  11. * Displays the operator form, adding a description.
  12. */
  13. public function show_operator_form(&$form, &$form_state) {
  14. $this->operator_form($form, $form_state);
  15. $form['operator']['#description'] = t('This operator is only useful when using \'Search keys\'.');
  16. }
  17. /**
  18. * Provide a list of options for the operator form.
  19. */
  20. public function operator_options() {
  21. return array(
  22. 'AND' => t('Contains all of these words'),
  23. 'OR' => t('Contains any of these words'),
  24. 'NOT' => t('Contains none of these words'),
  25. );
  26. }
  27. /**
  28. * Specify the options this filter uses.
  29. */
  30. public function option_definition() {
  31. $options = parent::option_definition();
  32. $options['operator']['default'] = 'AND';
  33. $options['mode'] = array('default' => 'keys');
  34. $options['min_length'] = array('default' => '');
  35. $options['fields'] = array('default' => array());
  36. return $options;
  37. }
  38. /**
  39. * Extend the options form a bit.
  40. */
  41. public function options_form(&$form, &$form_state) {
  42. parent::options_form($form, $form_state);
  43. $form['mode'] = array(
  44. '#title' => t('Use as'),
  45. '#type' => 'radios',
  46. '#options' => array(
  47. 'keys' => t('Search keys – multiple words will be split and the filter will influence relevance. You can change how search keys are parsed under "Advanced" > "Query settings".'),
  48. 'filter' => t("Search filter – use as a single phrase that restricts the result set but doesn't influence relevance."),
  49. ),
  50. '#default_value' => $this->options['mode'],
  51. );
  52. $fields = $this->getFulltextFields();
  53. if (!empty($fields)) {
  54. $form['fields'] = array(
  55. '#type' => 'select',
  56. '#title' => t('Searched fields'),
  57. '#description' => t('Select the fields that will be searched. If no fields are selected, all available fulltext fields will be searched.'),
  58. '#options' => $fields,
  59. '#size' => min(4, count($fields)),
  60. '#multiple' => TRUE,
  61. '#default_value' => $this->options['fields'],
  62. );
  63. }
  64. else {
  65. $form['fields'] = array(
  66. '#type' => 'value',
  67. '#value' => array(),
  68. );
  69. }
  70. if (isset($form['expose'])) {
  71. $form['expose']['#weight'] = -5;
  72. }
  73. $form['min_length'] = array(
  74. '#title' => t('Minimum keyword length'),
  75. '#description' => t('Minimum length of each word in the search keys. Leave empty to allow all words.'),
  76. '#type' => 'textfield',
  77. '#element_validate' => array('element_validate_integer_positive'),
  78. '#default_value' => $this->options['min_length'],
  79. );
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function exposed_validate(&$form, &$form_state) {
  85. // Only validate exposed input.
  86. if (empty($this->options['exposed']) || empty($this->options['expose']['identifier'])) {
  87. return;
  88. }
  89. // We only need to validate if there is a minimum word length set.
  90. if ($this->options['min_length'] < 2) {
  91. return;
  92. }
  93. $identifier = $this->options['expose']['identifier'];
  94. $input = &$form_state['values'][$identifier];
  95. if ($this->options['is_grouped'] && isset($this->options['group_info']['group_items'][$input])) {
  96. $this->operator = $this->options['group_info']['group_items'][$input]['operator'];
  97. $input = &$this->options['group_info']['group_items'][$input]['value'];
  98. }
  99. // If there is no input, we're fine.
  100. if (!trim($input)) {
  101. return;
  102. }
  103. $words = preg_split('/\s+/', $input);
  104. $quoted = FALSE;
  105. foreach ($words as $i => $word) {
  106. $word_length = drupal_strlen($word);
  107. if (!$word_length) {
  108. unset($words[$i]);
  109. continue;
  110. }
  111. // Protect quoted strings.
  112. if ($quoted && $word[strlen($word) - 1] === '"') {
  113. $quoted = FALSE;
  114. continue;
  115. }
  116. if ($quoted || $word[0] === '"') {
  117. $quoted = TRUE;
  118. continue;
  119. }
  120. if ($word_length < $this->options['min_length']) {
  121. unset($words[$i]);
  122. }
  123. }
  124. if (!$words) {
  125. $vars['@count'] = $this->options['min_length'];
  126. $msg = t('You must include at least one positive keyword with @count characters or more.', $vars);
  127. form_error($form[$identifier], $msg);
  128. }
  129. $input = implode(' ', $words);
  130. }
  131. /**
  132. * Add this filter to the query.
  133. */
  134. public function query() {
  135. while (is_array($this->value)) {
  136. $this->value = $this->value ? reset($this->value) : '';
  137. }
  138. // Catch empty strings entered by the user, but not "0".
  139. if ($this->value === '') {
  140. return;
  141. }
  142. $fields = $this->options['fields'];
  143. $available_fields = array_keys($this->getFulltextFields());
  144. $fields = $fields ? array_intersect($fields, $available_fields) : $available_fields;
  145. // If something already specifically set different fields, we silently fall
  146. // back to mere filtering.
  147. $filter = $this->options['mode'] == 'filter';
  148. if (!$filter) {
  149. $old = $this->query->getFields();
  150. $filter = $old && (array_diff($old, $fields) || array_diff($fields, $old));
  151. }
  152. if ($filter) {
  153. $filter = $this->query->createFilter('OR');
  154. $op = $this->operator === 'NOT' ? '<>' : '=';
  155. foreach ($fields as $field) {
  156. $filter->condition($field, $this->value, $op);
  157. }
  158. $this->query->filter($filter);
  159. return;
  160. }
  161. // If the operator was set to OR or NOT, set OR as the conjunction. (It is
  162. // also set for NOT since otherwise it would be "not all of these words".)
  163. if ($this->operator != 'AND') {
  164. $this->query->setOption('conjunction', 'OR');
  165. }
  166. try {
  167. $this->query->fields($fields);
  168. }
  169. catch (SearchApiException $e) {
  170. $this->query->abort($e->getMessage());
  171. return;
  172. }
  173. $old = $this->query->getKeys();
  174. $old_original = $this->query->getOriginalKeys();
  175. $this->query->keys($this->value);
  176. if ($this->operator == 'NOT') {
  177. $keys = &$this->query->getKeys();
  178. if (is_array($keys)) {
  179. $keys['#negation'] = TRUE;
  180. }
  181. else {
  182. // We can't know how negation is expressed in the server's syntax.
  183. }
  184. }
  185. // If there were fulltext keys set, we take care to combine them in a
  186. // meaningful way (especially with negated keys).
  187. if ($old) {
  188. $keys = &$this->query->getKeys();
  189. // Array-valued keys are combined.
  190. if (is_array($keys)) {
  191. // If the old keys weren't parsed into an array, we instead have to
  192. // combine the original keys.
  193. if (is_scalar($old)) {
  194. $keys = "($old) ({$this->value})";
  195. }
  196. else {
  197. // If the conjunction or negation settings aren't the same, we have to
  198. // nest both old and new keys array.
  199. if (!empty($keys['#negation']) != !empty($old['#negation']) || $keys['#conjunction'] != $old['#conjunction']) {
  200. $keys = array(
  201. '#conjunction' => 'AND',
  202. $old,
  203. $keys,
  204. );
  205. }
  206. // Otherwise, just add all individual words from the old keys to the
  207. // new ones.
  208. else {
  209. foreach (element_children($old) as $i) {
  210. $keys[] = $old[$i];
  211. }
  212. }
  213. }
  214. }
  215. // If the parse mode was "direct" for both old and new keys, we
  216. // concatenate them and set them both via method and reference (to also
  217. // update the originalKeys property.
  218. elseif (is_scalar($old_original)) {
  219. $combined_keys = "($old_original) ($keys)";
  220. $this->query->keys($combined_keys);
  221. $keys = $combined_keys;
  222. }
  223. }
  224. }
  225. /**
  226. * Helper method to get an option list of all available fulltext fields.
  227. */
  228. protected function getFulltextFields() {
  229. $fields = array();
  230. $index = search_api_index_load(substr($this->table, 17));
  231. if (!empty($index->options['fields'])) {
  232. $f = $index->getFields();
  233. foreach ($index->getFulltextFields() as $name) {
  234. $fields[$name] = $f[$name]['name'];
  235. }
  236. }
  237. return $fields;
  238. }
  239. }