processor_highlight.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * @file
  4. * Contains the SearchApiHighlight class.
  5. */
  6. /**
  7. * Processor for highlighting search results.
  8. */
  9. class SearchApiHighlight extends SearchApiAbstractProcessor {
  10. /**
  11. * PREG regular expression for a word boundary.
  12. *
  13. * We highlight around non-indexable or CJK characters.
  14. *
  15. * @var string
  16. */
  17. protected static $boundary;
  18. /**
  19. * PREG regular expression for splitting words.
  20. *
  21. * We highlight around non-indexable or CJK characters.
  22. *
  23. * @var string
  24. */
  25. protected static $split;
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function __construct(SearchApiIndex $index, array $options = array()) {
  30. parent::__construct($index, $options);
  31. $cjk = '\x{1100}-\x{11FF}\x{3040}-\x{309F}\x{30A1}-\x{318E}' .
  32. '\x{31A0}-\x{31B7}\x{31F0}-\x{31FF}\x{3400}-\x{4DBF}\x{4E00}-\x{9FCF}' .
  33. '\x{A000}-\x{A48F}\x{A4D0}-\x{A4FD}\x{A960}-\x{A97F}\x{AC00}-\x{D7FF}' .
  34. '\x{F900}-\x{FAFF}\x{FF21}-\x{FF3A}\x{FF41}-\x{FF5A}\x{FF66}-\x{FFDC}' .
  35. '\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}';
  36. self::$boundary = '(?:(?<=[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . $cjk . '])|(?=[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . $cjk . ']))';
  37. self::$split = '/[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . $cjk . ']+/iu';
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function configurationForm() {
  43. $this->options += array(
  44. 'prefix' => '<strong>',
  45. 'suffix' => '</strong>',
  46. 'excerpt' => TRUE,
  47. 'excerpt_length' => 256,
  48. 'highlight' => 'always',
  49. );
  50. $form['prefix'] = array(
  51. '#type' => 'textfield',
  52. '#title' => t('Highlighting prefix'),
  53. '#description' => t('Text/HTML that will be prepended to all occurrences of search keywords in highlighted text.'),
  54. '#default_value' => $this->options['prefix'],
  55. );
  56. $form['suffix'] = array(
  57. '#type' => 'textfield',
  58. '#title' => t('Highlighting suffix'),
  59. '#description' => t('Text/HTML that will be appended to all occurrences of search keywords in highlighted text.'),
  60. '#default_value' => $this->options['suffix'],
  61. );
  62. $form['excerpt'] = array(
  63. '#type' => 'checkbox',
  64. '#title' => t('Create excerpt'),
  65. '#description' => t('When enabled, an excerpt will be created for searches with keywords, containing all occurrences of keywords in a fulltext field.'),
  66. '#default_value' => $this->options['excerpt'],
  67. );
  68. $form['excerpt_length'] = array(
  69. '#type' => 'textfield',
  70. '#title' => t('Excerpt length'),
  71. '#description' => t('The requested length of the excerpt, in characters.'),
  72. '#default_value' => $this->options['excerpt_length'],
  73. '#element_validate' => array('element_validate_integer_positive'),
  74. '#states' => array(
  75. 'visible' => array(
  76. '#edit-processors-search-api-highlighting-settings-excerpt' => array(
  77. 'checked' => TRUE,
  78. ),
  79. ),
  80. ),
  81. );
  82. $form['highlight'] = array(
  83. '#type' => 'select',
  84. '#title' => t('Highlight returned field data'),
  85. '#description' => t('Select whether returned fields should be highlighted.'),
  86. '#options' => array(
  87. 'always' => t('Always'),
  88. 'server' => t('If the server returns fields'),
  89. 'never' => t('Never'),
  90. ),
  91. '#default_value' => $this->options['highlight'],
  92. );
  93. return $form;
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function configurationFormValidate(array $form, array &$values, array &$form_state) {
  99. // Overridden so $form['fields'] is not checked.
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function postprocessSearchResults(array &$response, SearchApiQuery $query) {
  105. if (!$response['result count'] || !($keys = $this->getKeywords($query))) {
  106. return;
  107. }
  108. foreach ($response['results'] as $id => &$result) {
  109. if ($this->options['excerpt']) {
  110. $text = array();
  111. $fields = $this->getFulltextFields($response['results'], $id);
  112. foreach ($fields as $data) {
  113. if (is_array($data)) {
  114. $text = array_merge($text, $data);
  115. }
  116. else {
  117. $text[] = $data;
  118. }
  119. }
  120. $result['excerpt'] = $this->createExcerpt(implode("\n\n", $text), $keys);
  121. }
  122. if ($this->options['highlight'] != 'never') {
  123. $fields = $this->getFulltextFields($response['results'], $id, $this->options['highlight'] == 'always');
  124. foreach ($fields as $field => $data) {
  125. if (is_array($data)) {
  126. foreach ($data as $i => $text) {
  127. $result['fields'][$field][$i] = $this->highlightField($text, $keys);
  128. }
  129. }
  130. else {
  131. $result['fields'][$field] = $this->highlightField($data, $keys);
  132. }
  133. }
  134. }
  135. }
  136. }
  137. /**
  138. * Retrieves the fulltext data of a result.
  139. *
  140. * @param array $result
  141. * All results returned in the search.
  142. * @param int|string $i
  143. * The index in the results array of the result whose data should be
  144. * returned.
  145. * @param bool $load
  146. * TRUE if the item should be loaded if necessary, FALSE if only fields
  147. * already returned in the results should be used.
  148. *
  149. * @return array
  150. * An array containing fulltext field names mapped to the text data
  151. * contained in them for the given result.
  152. */
  153. protected function getFulltextFields(array &$results, $i, $load = TRUE) {
  154. $data = array();
  155. // Act as if $load is TRUE if we have a loaded item.
  156. $load |= !empty($result['entity']);
  157. $result = &$results[$i];
  158. $result += array('fields' => array());
  159. $fulltext_fields = $this->index->getFulltextFields();
  160. // We only need detailed fields data if $load is TRUE.
  161. $fields = $load ? $this->index->getFields() : array();
  162. $needs_extraction = array();
  163. foreach ($fulltext_fields as $field) {
  164. if (array_key_exists($field, $result['fields'])) {
  165. $data[$field] = $result['fields'][$field];
  166. }
  167. elseif ($load) {
  168. $needs_extraction[$field] = $fields[$field];
  169. }
  170. }
  171. if (!$needs_extraction) {
  172. return $data;
  173. }
  174. if (empty($result['entity'])) {
  175. $items = $this->index->loadItems(array_keys($results));
  176. foreach ($items as $id => $item) {
  177. $results[$id]['entity'] = $item;
  178. }
  179. }
  180. // If we still don't have a loaded item, we should stop trying.
  181. if (empty($result['entity'])) {
  182. return $data;
  183. }
  184. $wrapper = $this->index->entityWrapper($result['entity'], FALSE);
  185. $extracted = search_api_extract_fields($wrapper, $needs_extraction);
  186. foreach ($extracted as $field => $info) {
  187. if (isset($info['value'])) {
  188. $data[$field] = $info['value'];
  189. }
  190. }
  191. return $data;
  192. }
  193. /**
  194. * Extracts the positive keywords used in a search query.
  195. *
  196. * @param SearchApiQuery $query
  197. * The query from which to extract the keywords.
  198. *
  199. * @return array
  200. * An array of all unique positive keywords used in the query.
  201. */
  202. protected function getKeywords(SearchApiQuery $query) {
  203. $keys = $query->getKeys();
  204. if (!$keys) {
  205. return array();
  206. }
  207. if (is_array($keys)) {
  208. return $this->flattenKeysArray($keys);
  209. }
  210. $keywords = preg_split(self::$split, $keys);
  211. // Assure there are no duplicates. (This is actually faster than
  212. // array_unique() by a factor of 3 to 4.)
  213. $keywords = drupal_map_assoc(array_filter($keywords));
  214. // Remove quotes from keywords.
  215. foreach ($keywords as $key) {
  216. $keywords[$key] = trim($key, "'\"");
  217. }
  218. return drupal_map_assoc(array_filter($keywords));
  219. }
  220. /**
  221. * Extracts the positive keywords from a keys array.
  222. *
  223. * @param array $keys
  224. * A search keys array, as specified by SearchApiQueryInterface::getKeys().
  225. *
  226. * @return array
  227. * An array of all unique positive keywords contained in the keys.
  228. */
  229. protected function flattenKeysArray(array $keys) {
  230. if (!empty($keys['#negation'])) {
  231. return array();
  232. }
  233. $keywords = array();
  234. foreach ($keys as $i => $key) {
  235. if (!element_child($i)) {
  236. continue;
  237. }
  238. if (is_array($key)) {
  239. $keywords += $this->flattenKeysArray($key);
  240. }
  241. else {
  242. $keywords[$key] = $key;
  243. }
  244. }
  245. return $keywords;
  246. }
  247. /**
  248. * Returns snippets from a piece of text, with certain keywords highlighted.
  249. *
  250. * Largely copied from search_excerpt().
  251. *
  252. * @param string $text
  253. * The text to extract fragments from.
  254. * @param array $keys
  255. * Search keywords entered by the user.
  256. *
  257. * @return string
  258. * A string containing HTML for the excerpt.
  259. */
  260. protected function createExcerpt($text, array $keys) {
  261. // Prepare text by stripping HTML tags and decoding HTML entities.
  262. $text = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text));
  263. $text = ' ' . decode_entities($text);
  264. // Extract fragments around keywords.
  265. // First we collect ranges of text around each keyword, starting/ending
  266. // at spaces, trying to get to the requested length.
  267. // If the sum of all fragments is too short, we look for second occurrences.
  268. $ranges = array();
  269. $included = array();
  270. $foundkeys = array();
  271. $length = 0;
  272. $workkeys = $keys;
  273. while ($length < $this->options['excerpt_length'] && count($workkeys)) {
  274. foreach ($workkeys as $k => $key) {
  275. if ($length >= $this->options['excerpt_length']) {
  276. break;
  277. }
  278. // Remember occurrence of key so we can skip over it if more occurrences
  279. // are desired.
  280. if (!isset($included[$key])) {
  281. $included[$key] = 0;
  282. }
  283. // Locate a keyword (position $p, always >0 because $text starts with a
  284. // space).
  285. $p = 0;
  286. if (preg_match('/' . self::$boundary . $key . self::$boundary . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
  287. $p = $match[0][1];
  288. }
  289. // Now locate a space in front (position $q) and behind it (position $s),
  290. // leaving about 60 characters extra before and after for context.
  291. // Note that a space was added to the front and end of $text above.
  292. if ($p) {
  293. if (($q = strpos(' ' . $text, ' ', max(0, $p - 61))) !== FALSE) {
  294. $end = substr($text . ' ', $p, 80);
  295. if (($s = strrpos($end, ' ')) !== FALSE) {
  296. // Account for the added spaces.
  297. $q = max($q - 1, 0);
  298. $s = min($s, strlen($end) - 1);
  299. $ranges[$q] = $p + $s;
  300. $length += $p + $s - $q;
  301. $included[$key] = $p + 1;
  302. }
  303. else {
  304. unset($workkeys[$k]);
  305. }
  306. }
  307. else {
  308. unset($workkeys[$k]);
  309. }
  310. }
  311. else {
  312. unset($workkeys[$k]);
  313. }
  314. }
  315. }
  316. if (count($ranges) == 0) {
  317. // We didn't find any keyword matches, so just return NULL.
  318. return NULL;
  319. }
  320. // Sort the text ranges by starting position.
  321. ksort($ranges);
  322. // Now we collapse overlapping text ranges into one. The sorting makes it O(n).
  323. $newranges = array();
  324. foreach ($ranges as $from2 => $to2) {
  325. if (!isset($from1)) {
  326. $from1 = $from2;
  327. $to1 = $to2;
  328. continue;
  329. }
  330. if ($from2 <= $to1) {
  331. $to1 = max($to1, $to2);
  332. }
  333. else {
  334. $newranges[$from1] = $to1;
  335. $from1 = $from2;
  336. $to1 = $to2;
  337. }
  338. }
  339. $newranges[$from1] = $to1;
  340. // Fetch text
  341. $out = array();
  342. foreach ($newranges as $from => $to) {
  343. $out[] = substr($text, $from, $to - $from);
  344. }
  345. // Let translators have the ... separator text as one chunk.
  346. $dots = explode('!excerpt', t('... !excerpt ... !excerpt ...'));
  347. $text = (isset($newranges[0]) ? '' : $dots[0]) . implode($dots[1], $out) . $dots[2];
  348. $text = check_plain($text);
  349. return $this->highlightField($text, $keys);
  350. }
  351. /**
  352. * Marks occurrences of the search keywords in a text field.
  353. *
  354. * @param string $text
  355. * The text of the field.
  356. * @param array $keys
  357. * Search keywords entered by the user.
  358. *
  359. * @return string
  360. * The field's text with all occurrences of search keywords highlighted.
  361. */
  362. protected function highlightField($text, array $keys) {
  363. $replace = $this->options['prefix'] . '\0' . $this->options['suffix'];
  364. $text = preg_replace('/' . self::$boundary . '(' . implode('|', $keys) . ')' . self::$boundary . '/iu', $replace, ' ' . $text);
  365. return substr($text, 1);
  366. }
  367. }