processor_highlight.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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 fulltextfields
  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] = $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. if (is_array($data)) {
  148. foreach ($data as $i => $text) {
  149. $result['fields'][$field][$i] = $this->highlightField($text, $keys);
  150. }
  151. }
  152. else {
  153. $result['fields'][$field] = $this->highlightField($data, $keys);
  154. }
  155. }
  156. }
  157. }
  158. }
  159. /**
  160. * Retrieves the fulltext data of a result.
  161. *
  162. * @param array $results
  163. * All results returned in the search, by reference.
  164. * @param int|string $i
  165. * The index in the results array of the result whose data should be
  166. * returned.
  167. * @param array $fulltext_fields
  168. * The fulltext fields from which the excerpt should be created.
  169. * @param bool $load
  170. * TRUE if the item should be loaded if necessary, FALSE if only fields
  171. * already returned in the results should be used.
  172. *
  173. * @return array
  174. * An array containing fulltext field names mapped to the text data
  175. * contained in them for the given result.
  176. */
  177. protected function getFulltextFields(array &$results, $i, array $fulltext_fields, $load = TRUE) {
  178. global $language;
  179. $data = array();
  180. $result = &$results[$i];
  181. // Act as if $load is TRUE if we have a loaded item.
  182. $load |= !empty($result['entity']);
  183. $result += array('fields' => array());
  184. // We only need detailed fields data if $load is TRUE.
  185. $fields = $load ? $this->index->getFields() : array();
  186. $needs_extraction = array();
  187. foreach ($fulltext_fields as $field) {
  188. if (array_key_exists($field, $result['fields'])) {
  189. $data[$field] = $result['fields'][$field];
  190. }
  191. elseif ($load) {
  192. $needs_extraction[$field] = $fields[$field];
  193. }
  194. }
  195. if (!$needs_extraction) {
  196. return $data;
  197. }
  198. if (empty($result['entity'])) {
  199. $items = $this->index->loadItems(array_keys($results));
  200. foreach ($items as $id => $item) {
  201. $results[$id]['entity'] = $item;
  202. }
  203. }
  204. // If we still don't have a loaded item, we should stop trying.
  205. if (empty($result['entity'])) {
  206. return $data;
  207. }
  208. $wrapper = $this->index->entityWrapper($result['entity'], FALSE);
  209. $wrapper->language($language->language);
  210. $extracted = search_api_extract_fields($wrapper, $needs_extraction);
  211. foreach ($extracted as $field => $info) {
  212. if (isset($info['value'])) {
  213. $data[$field] = $info['value'];
  214. }
  215. }
  216. return $data;
  217. }
  218. /**
  219. * Extracts the positive keywords used in a search query.
  220. *
  221. * @param SearchApiQuery $query
  222. * The query from which to extract the keywords.
  223. *
  224. * @return array
  225. * An array of all unique positive keywords used in the query.
  226. */
  227. protected function getKeywords(SearchApiQuery $query) {
  228. $keys = $query->getKeys();
  229. if (!$keys) {
  230. return array();
  231. }
  232. if (is_array($keys)) {
  233. return $this->flattenKeysArray($keys);
  234. }
  235. $keywords = preg_split(self::$split, $keys);
  236. // Assure there are no duplicates. (This is actually faster than
  237. // array_unique() by a factor of 3 to 4.)
  238. $keywords = drupal_map_assoc(array_filter($keywords));
  239. // Remove quotes from keywords.
  240. foreach ($keywords as $key) {
  241. $keywords[$key] = trim($key, "'\"");
  242. }
  243. return drupal_map_assoc(array_filter($keywords));
  244. }
  245. /**
  246. * Extracts the positive keywords from a keys array.
  247. *
  248. * @param array $keys
  249. * A search keys array, as specified by SearchApiQueryInterface::getKeys().
  250. *
  251. * @return array
  252. * An array of all unique positive keywords contained in the keys.
  253. */
  254. protected function flattenKeysArray(array $keys) {
  255. if (!empty($keys['#negation'])) {
  256. return array();
  257. }
  258. $keywords = array();
  259. foreach ($keys as $i => $key) {
  260. if (!element_child($i)) {
  261. continue;
  262. }
  263. if (is_array($key)) {
  264. $keywords += $this->flattenKeysArray($key);
  265. }
  266. else {
  267. $keywords[$key] = $key;
  268. }
  269. }
  270. return $keywords;
  271. }
  272. /**
  273. * Returns snippets from a piece of text, with certain keywords highlighted.
  274. *
  275. * Largely copied from search_excerpt().
  276. *
  277. * @param string $text
  278. * The text to extract fragments from.
  279. * @param array $keys
  280. * Search keywords entered by the user.
  281. *
  282. * @return string
  283. * A string containing HTML for the excerpt.
  284. */
  285. protected function createExcerpt($text, array $keys) {
  286. // Prepare text by stripping HTML tags and decoding HTML entities.
  287. $text = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text));
  288. $text = ' ' . decode_entities($text);
  289. // Extract fragments around keywords.
  290. // First we collect ranges of text around each keyword, starting/ending
  291. // at spaces, trying to get to the requested length.
  292. // If the sum of all fragments is too short, we look for second occurrences.
  293. $ranges = array();
  294. $included = array();
  295. $length = 0;
  296. $workkeys = $keys;
  297. while ($length < $this->options['excerpt_length'] && count($workkeys)) {
  298. foreach ($workkeys as $k => $key) {
  299. if ($length >= $this->options['excerpt_length']) {
  300. break;
  301. }
  302. // Remember occurrence of key so we can skip over it if more occurrences
  303. // are desired.
  304. if (!isset($included[$key])) {
  305. $included[$key] = 0;
  306. }
  307. // Locate a keyword (position $p, always >0 because $text starts with a
  308. // space).
  309. $p = 0;
  310. if (preg_match('/' . self::$boundary . preg_quote($key, '/') . self::$boundary . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
  311. $p = $match[0][1];
  312. }
  313. // Now locate a space in front (position $q) and behind it (position $s),
  314. // leaving about 60 characters extra before and after for context.
  315. // Note that a space was added to the front and end of $text above.
  316. if ($p) {
  317. if (($q = strpos(' ' . $text, ' ', max(0, $p - 61))) !== FALSE) {
  318. $end = substr($text . ' ', $p, 80);
  319. if (($s = strrpos($end, ' ')) !== FALSE) {
  320. // Account for the added spaces.
  321. $q = max($q - 1, 0);
  322. $s = min($s, strlen($end) - 1);
  323. $ranges[$q] = $p + $s;
  324. $length += $p + $s - $q;
  325. $included[$key] = $p + 1;
  326. }
  327. else {
  328. unset($workkeys[$k]);
  329. }
  330. }
  331. else {
  332. unset($workkeys[$k]);
  333. }
  334. }
  335. else {
  336. unset($workkeys[$k]);
  337. }
  338. }
  339. }
  340. if (count($ranges) == 0) {
  341. // We didn't find any keyword matches, so just return NULL.
  342. return NULL;
  343. }
  344. // Sort the text ranges by starting position.
  345. ksort($ranges);
  346. // Now we collapse overlapping text ranges into one. The sorting makes it O(n).
  347. $newranges = array();
  348. foreach ($ranges as $from2 => $to2) {
  349. if (!isset($from1)) {
  350. $from1 = $from2;
  351. $to1 = $to2;
  352. continue;
  353. }
  354. if ($from2 <= $to1) {
  355. $to1 = max($to1, $to2);
  356. }
  357. else {
  358. $newranges[$from1] = $to1;
  359. $from1 = $from2;
  360. $to1 = $to2;
  361. }
  362. }
  363. $newranges[$from1] = $to1;
  364. // Fetch text
  365. $out = array();
  366. foreach ($newranges as $from => $to) {
  367. $out[] = substr($text, $from, $to - $from);
  368. }
  369. // Let translators have the ... separator text as one chunk.
  370. $dots = explode('!excerpt', t('... !excerpt ... !excerpt ...'));
  371. $text = (isset($newranges[0]) ? '' : $dots[0]) . implode($dots[1], $out) . $dots[2];
  372. $text = check_plain($text);
  373. // Since we stripped the tags at the beginning, highlighting doesn't need to
  374. // handle HTML anymore.
  375. return $this->highlightField($text, $keys, FALSE);
  376. }
  377. /**
  378. * Marks occurrences of the search keywords in a text field.
  379. *
  380. * @param string $text
  381. * The text of the field.
  382. * @param array $keys
  383. * Search keywords entered by the user.
  384. * @param bool $html
  385. * Whether the text can contain HTML tags or not. In the former case, text
  386. * inside tags (i.e., tag names and attributes) won't be highlighted.
  387. *
  388. * @return string
  389. * The field's text with all occurrences of search keywords highlighted.
  390. */
  391. protected function highlightField($text, array $keys, $html = TRUE) {
  392. if (is_array($text)) {
  393. $text = $this->flattenArrayValues($text);
  394. }
  395. if ($html) {
  396. $texts = preg_split('#((?:</?[[:alpha:]](?:[^>"\']*|"[^"]*"|\'[^\']\')*>)+)#i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  397. for ($i = 0; $i < count($texts); $i += 2) {
  398. $texts[$i] = $this->highlightField($texts[$i], $keys, FALSE);
  399. }
  400. return implode('', $texts);
  401. }
  402. $replace = $this->options['prefix'] . '\0' . $this->options['suffix'];
  403. $keys = implode('|', array_map('preg_quote', $keys, array_fill(0, count($keys), '/')));
  404. $text = preg_replace('/' . self::$boundary . '(' . $keys . ')' . self::$boundary . '/iu', $replace, ' ' . $text . ' ');
  405. return substr($text, 1, -1);
  406. }
  407. /**
  408. * Flattens a (possibly multidimensional) array into a string.
  409. *
  410. * @param array $array
  411. * The array to flatten.
  412. * @param string $glue
  413. * The separator to insert between individual array items.
  414. *
  415. * @return string
  416. * The glued string.
  417. */
  418. protected function flattenArrayValues(array $array, $glue = "\n\n") {
  419. $ret = array();
  420. foreach ($array as $item) {
  421. if (is_array($item)) {
  422. $ret[] = $this->flattenArrayValues($item, $glue);
  423. }
  424. else {
  425. $ret[] = $item;
  426. }
  427. }
  428. return implode($glue, $ret);
  429. }
  430. }