processor_highlight.inc 15 KB

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