search_api_facetapi.module 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. /**
  3. * @file
  4. * Integrates the Search API with the Facet API.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function search_api_facetapi_menu() {
  10. // We need to handle our own menu paths for facets because we need a facet
  11. // configuration page per index.
  12. $first = TRUE;
  13. foreach (facetapi_get_realm_info() as $realm_name => $realm) {
  14. if ($first) {
  15. $first = FALSE;
  16. $items['admin/config/search/search_api/index/%search_api_index/facets'] = array(
  17. 'title' => 'Facets',
  18. 'page callback' => 'search_api_facetapi_settings',
  19. 'page arguments' => array($realm_name, 5),
  20. 'weight' => -1,
  21. 'access arguments' => array('administer search_api'),
  22. 'type' => MENU_LOCAL_TASK,
  23. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  24. );
  25. $items['admin/config/search/search_api/index/%search_api_index/facets/' . $realm_name] = array(
  26. 'title' => $realm['label'],
  27. 'type' => MENU_DEFAULT_LOCAL_TASK,
  28. 'weight' => $realm['weight'],
  29. );
  30. }
  31. else {
  32. $items['admin/config/search/search_api/index/%search_api_index/facets/' . $realm_name] = array(
  33. 'title' => $realm['label'],
  34. 'page callback' => 'search_api_facetapi_settings',
  35. 'page arguments' => array($realm_name, 5),
  36. 'access arguments' => array('administer search_api'),
  37. 'type' => MENU_LOCAL_TASK,
  38. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  39. 'weight' => $realm['weight'],
  40. );
  41. }
  42. }
  43. return $items;
  44. }
  45. /**
  46. * Implements hook_facetapi_searcher_info().
  47. */
  48. function search_api_facetapi_facetapi_searcher_info() {
  49. $info = array();
  50. $indexes = search_api_index_load_multiple(FALSE);
  51. foreach ($indexes as $index) {
  52. if ($index->enabled && $index->server()->supportsFeature('search_api_facets')) {
  53. $searcher_name = 'search_api@' . $index->machine_name;
  54. $info[$searcher_name] = array(
  55. 'label' => t('Search service: @name', array('@name' => $index->name)),
  56. 'adapter' => 'search_api',
  57. 'instance' => $index->machine_name,
  58. 'types' => array($index->item_type),
  59. 'path' => '',
  60. 'supports facet missing' => TRUE,
  61. 'supports facet mincount' => TRUE,
  62. 'include default facets' => FALSE,
  63. );
  64. if (($entity_type = $index->getEntityType()) && $entity_type !== $index->item_type) {
  65. $info[$searcher_name]['types'][] = $entity_type;
  66. }
  67. }
  68. }
  69. return $info;
  70. }
  71. /**
  72. * Implements hook_facetapi_facet_info().
  73. */
  74. function search_api_facetapi_facetapi_facet_info(array $searcher_info) {
  75. $facet_info = array();
  76. if ('search_api' == $searcher_info['adapter']) {
  77. $index = search_api_index_load($searcher_info['instance']);
  78. if (!empty($index->options['fields'])) {
  79. $wrapper = $index->entityWrapper();
  80. $bundle_key = NULL;
  81. if ($index->getEntityType() && ($entity_info = entity_get_info($index->getEntityType())) && !empty($entity_info['bundle keys']['bundle'])) {
  82. $bundle_key = $entity_info['bundle keys']['bundle'];
  83. }
  84. // Some type-specific settings. Allowing to set some additional callbacks
  85. // (and other settings) in the map options allows for easier overriding by
  86. // other modules.
  87. $type_settings = array(
  88. 'taxonomy_term' => array(
  89. 'hierarchy callback' => 'search_api_facetapi_get_taxonomy_hierarchy',
  90. ),
  91. 'date' => array(
  92. 'query type' => 'date',
  93. 'map options' => array(
  94. 'map callback' => 'facetapi_map_date',
  95. ),
  96. ),
  97. );
  98. // Iterate through the indexed fields to set the facetapi settings for
  99. // each one.
  100. foreach ($index->getFields() as $key => $field) {
  101. $field['key'] = $key;
  102. // Determine which, if any, of the field type-specific options will be
  103. // used for this field.
  104. $type = isset($field['entity_type']) ? $field['entity_type'] : $field['type'];
  105. $type_settings += array($type => array());
  106. $facet_info[$key] = $type_settings[$type] + array(
  107. 'label' => $field['name'],
  108. 'description' => t('Filter by @type.', array('@type' => $field['name'])),
  109. 'allowed operators' => array(
  110. FACETAPI_OPERATOR_AND => TRUE,
  111. FACETAPI_OPERATOR_OR => $index->server()->supportsFeature('search_api_facets_operator_or'),
  112. ),
  113. 'dependency plugins' => array('role'),
  114. 'facet missing allowed' => TRUE,
  115. 'facet mincount allowed' => TRUE,
  116. 'map callback' => 'search_api_facetapi_facet_map_callback',
  117. 'map options' => array(),
  118. 'field type' => $type,
  119. );
  120. if ($type === 'date') {
  121. $facet_info[$key]['description'] .= ' ' . t('(Caution: This may perform very poorly for large result sets.)');
  122. }
  123. $facet_info[$key]['map options'] += array(
  124. 'field' => $field,
  125. 'index id' => $index->machine_name,
  126. 'value callback' => '_search_api_facetapi_facet_create_label',
  127. );
  128. // Find out whether this property is a Field API field.
  129. if (strpos($key, ':') === FALSE) {
  130. if (isset($wrapper->$key)) {
  131. $property_info = $wrapper->$key->info();
  132. if (!empty($property_info['field'])) {
  133. $facet_info[$key]['field api name'] = $key;
  134. }
  135. }
  136. }
  137. // Add bundle information, if applicable.
  138. if ($bundle_key) {
  139. if ($key === $bundle_key) {
  140. // Set entity type this field contains bundle information for.
  141. $facet_info[$key]['field api bundles'][] = $index->getEntityType();
  142. }
  143. else {
  144. // Add "bundle" as possible dependency plugin.
  145. $facet_info[$key]['dependency plugins'][] = 'bundle';
  146. }
  147. }
  148. }
  149. }
  150. }
  151. return $facet_info;
  152. }
  153. /**
  154. * Implements hook_facetapi_adapters().
  155. */
  156. function search_api_facetapi_facetapi_adapters() {
  157. return array(
  158. 'search_api' => array(
  159. 'handler' => array(
  160. 'class' => 'SearchApiFacetapiAdapter',
  161. ),
  162. ),
  163. );
  164. }
  165. /**
  166. * Implements hook_facetapi_query_types().
  167. */
  168. function search_api_facetapi_facetapi_query_types() {
  169. return array(
  170. 'search_api_term' => array(
  171. 'handler' => array(
  172. 'class' => 'SearchApiFacetapiTerm',
  173. 'adapter' => 'search_api',
  174. ),
  175. ),
  176. 'search_api_date' => array(
  177. 'handler' => array(
  178. 'class' => 'SearchApiFacetapiDate',
  179. 'adapter' => 'search_api',
  180. ),
  181. ),
  182. );
  183. }
  184. /**
  185. * Implements hook_search_api_query_alter().
  186. *
  187. * Adds Facet API support to the query.
  188. */
  189. function search_api_facetapi_search_api_query_alter($query) {
  190. $index = $query->getIndex();
  191. if ($index->server()->supportsFeature('search_api_facets')) {
  192. // This is the main point of communication between the facet system and the
  193. // search back-end - it makes the query respond to active facets.
  194. $searcher = 'search_api@' . $index->machine_name;
  195. $adapter = facetapi_adapter_load($searcher);
  196. if ($adapter) {
  197. $adapter->addActiveFilters($query);
  198. }
  199. }
  200. }
  201. /**
  202. * Menu callback for the facet settings page.
  203. */
  204. function search_api_facetapi_settings($realm_name, SearchApiIndex $index) {
  205. if (!$index->enabled) {
  206. return array('#markup' => t('Since this index is at the moment disabled, no facets can be activated.'));
  207. }
  208. if (!$index->server()->supportsFeature('search_api_facets')) {
  209. return array('#markup' => t('This index uses a server that does not support facet functionality.'));
  210. }
  211. $searcher_name = 'search_api@' . $index->machine_name;
  212. module_load_include('inc', 'facetapi', 'facetapi.admin');
  213. return drupal_get_form('facetapi_realm_settings_form', $searcher_name, $realm_name);
  214. }
  215. /**
  216. * Gets hierarchy information for taxonomy terms.
  217. *
  218. * Used as a hierarchy callback in search_api_facetapi_facetapi_facet_info().
  219. *
  220. * Internally just uses facetapi_get_taxonomy_hierarchy(), but makes sure that
  221. * our special "!" value is not passed.
  222. *
  223. * @param array $values
  224. * An array containing the term IDs.
  225. *
  226. * @return array
  227. * An associative array mapping term IDs to parent IDs (where parents could be
  228. * found).
  229. */
  230. function search_api_facetapi_get_taxonomy_hierarchy(array $values) {
  231. $values = array_filter($values, 'is_numeric');
  232. return $values ? facetapi_get_taxonomy_hierarchy($values) : array();
  233. }
  234. /**
  235. * Map callback for all search_api facet fields.
  236. *
  237. * @param array $values
  238. * The values to map.
  239. * @param array $options
  240. * An associative array containing:
  241. * - field: Field information, as stored in the index, but with an additional
  242. * "key" property set to the field's internal name.
  243. * - index id: The machine name of the index for this facet.
  244. * - map callback: (optional) A callback that will be called at the beginning,
  245. * which allows initial mapping of filters. Only values not mapped by that
  246. * callback will be processed by this method.
  247. * - value callback: A callback used to map single values and the limits of
  248. * ranges. The signature is the same as for this function, but all values
  249. * will be single values.
  250. * - missing label: (optional) The label used for the "missing" facet.
  251. *
  252. * @return array
  253. * An array mapping raw filter values to their labels.
  254. */
  255. function search_api_facetapi_facet_map_callback(array $values, array $options = array()) {
  256. $map = array();
  257. // See if we have an additional map callback.
  258. if (isset($options['map callback']) && is_callable($options['map callback'])) {
  259. $map = call_user_func($options['map callback'], $values, $options);
  260. }
  261. // Then look at all unmapped values and save information for them.
  262. $mappable_values = array();
  263. $ranges = array();
  264. foreach ($values as $value) {
  265. $value = (string) $value;
  266. if (isset($map[$value])) {
  267. continue;
  268. }
  269. if ($value == '!') {
  270. // The "missing" filter is usually always the same, but we allow an easy
  271. // override via the "missing label" map option.
  272. $map['!'] = isset($options['missing label']) ? $options['missing label'] : '(' . t('none') . ')';
  273. continue;
  274. }
  275. $length = strlen($value);
  276. if ($length > 5 && $value[0] == '[' && $value[$length - 1] == ']' && ($pos = strpos($value, ' TO '))) {
  277. // This is a range filter.
  278. $lower = trim(substr($value, 1, $pos));
  279. $upper = trim(substr($value, $pos + 4, -1));
  280. if ($lower != '*') {
  281. $mappable_values[$lower] = TRUE;
  282. }
  283. if ($upper != '*') {
  284. $mappable_values[$upper] = TRUE;
  285. }
  286. $ranges[$value] = array(
  287. 'lower' => $lower,
  288. 'upper' => $upper,
  289. );
  290. }
  291. else {
  292. // A normal, single-value filter.
  293. $mappable_values[$value] = TRUE;
  294. }
  295. }
  296. if ($mappable_values) {
  297. $map += call_user_func($options['value callback'], array_keys($mappable_values), $options);
  298. }
  299. foreach ($ranges as $value => $range) {
  300. $lower = isset($map[$range['lower']]) ? $map[$range['lower']] : $range['lower'];
  301. $upper = isset($map[$range['upper']]) ? $map[$range['upper']] : $range['upper'];
  302. if ($lower == '*' && $upper == '*') {
  303. $map[$value] = t('any');
  304. }
  305. elseif ($lower == '*') {
  306. $map[$value] = "< $upper";
  307. }
  308. elseif ($upper == '*') {
  309. $map[$value] = "> $lower";
  310. }
  311. else {
  312. $map[$value] = "$lower – $upper";
  313. }
  314. }
  315. return $map;
  316. }
  317. /**
  318. * Creates a human-readable label for single facet filter values.
  319. *
  320. * @param array $values
  321. * The values for which labels should be returned.
  322. * @param array $options
  323. * An associative array containing the following information about the facet:
  324. * - field: Field information, as stored in the index, but with an additional
  325. * "key" property set to the field's internal name.
  326. * - index id: The machine name of the index for this facet.
  327. * - map callback: (optional) A callback that will be called at the beginning,
  328. * which allows initial mapping of filters. Only values not mapped by that
  329. * callback will be processed by this method.
  330. * - value callback: A callback used to map single values and the limits of
  331. * ranges. The signature is the same as for this function, but all values
  332. * will be single values.
  333. * - missing label: (optional) The label used for the "missing" facet.
  334. *
  335. * @return array
  336. * An array mapping raw facet values to their labels.
  337. */
  338. function _search_api_facetapi_facet_create_label(array $values, array $options) {
  339. $field = $options['field'];
  340. $map = array();
  341. $n = count($values);
  342. // For entities, we can simply use the entity labels.
  343. if (isset($field['entity_type'])) {
  344. $type = $field['entity_type'];
  345. $entities = entity_load($type, $values);
  346. foreach ($entities as $id => $entity) {
  347. $label = entity_label($type, $entity);
  348. if ($label) {
  349. $map[$id] = $label;
  350. }
  351. }
  352. if (count($map) == $n) {
  353. return $map;
  354. }
  355. }
  356. // Then, we check whether there is an options list for the field.
  357. $index = search_api_index_load($options['index id']);
  358. $wrapper = $index->entityWrapper();
  359. $values = drupal_map_assoc($values);
  360. foreach (explode(':', $field['key']) as $part) {
  361. if (!isset($wrapper->$part)) {
  362. $wrapper = NULL;
  363. break;
  364. }
  365. $wrapper = $wrapper->$part;
  366. while (($info = $wrapper->info()) && search_api_is_list_type($info['type'])) {
  367. $wrapper = $wrapper[0];
  368. }
  369. }
  370. if ($wrapper && ($options_list = $wrapper->optionsList('view'))) {
  371. // We have no use for empty strings, as then the facet links would be
  372. // invisible.
  373. $map += array_intersect_key(array_filter($options_list, 'strlen'), $values);
  374. if (count($map) == $n) {
  375. return $map;
  376. }
  377. }
  378. // As a "last resort" we try to create a label based on the field type, for
  379. // all values that haven't got a mapping yet.
  380. foreach (array_diff_key($values, $map) as $value) {
  381. switch ($field['type']) {
  382. case 'boolean':
  383. $map[$value] = $value ? t('true') : t('false');
  384. break;
  385. case 'date':
  386. $v = is_numeric($value) ? $value : strtotime($value);
  387. $map[$value] = format_date($v, 'short');
  388. break;
  389. case 'duration':
  390. $map[$value] = format_interval($value);
  391. break;
  392. }
  393. }
  394. return $map;
  395. }
  396. /**
  397. * Implements hook_form_FORM_ID_alter().
  398. */
  399. function search_api_facetapi_form_search_api_admin_index_fields_alter(&$form, &$form_state) {
  400. $form['#submit'][] = 'search_api_facetapi_search_api_admin_index_fields_submit';
  401. }
  402. /**
  403. * Form submission handler for search_api_admin_index_fields().
  404. */
  405. function search_api_facetapi_search_api_admin_index_fields_submit($form, &$form_state) {
  406. // Clears this searcher's cached facet definitions.
  407. $cid = 'facetapi:facet_info:search_api@' . $form_state['index']->machine_name . ':';
  408. cache_clear_all($cid, 'cache', TRUE);
  409. }