search_api_facetapi.module 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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' => '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. * Map callback for all search_api facet fields.
  217. *
  218. * @param array $values
  219. * The values to map.
  220. * @param array $options
  221. * An associative array containing:
  222. * - field: Field information, as stored in the index, but with an additional
  223. * "key" property set to the field's internal name.
  224. * - index id: The machine name of the index for this facet.
  225. * - map callback: (optional) A callback that will be called at the beginning,
  226. * which allows initial mapping of filters. Only values not mapped by that
  227. * callback will be processed by this method.
  228. * - value callback: A callback used to map single values and the limits of
  229. * ranges. The signature is the same as for this function, but all values
  230. * will be single values.
  231. * - missing label: (optional) The label used for the "missing" facet.
  232. *
  233. * @return array
  234. * An array mapping raw filter values to their labels.
  235. */
  236. function search_api_facetapi_facet_map_callback(array $values, array $options = array()) {
  237. $map = array();
  238. // See if we have an additional map callback.
  239. if (isset($options['map callback']) && is_callable($options['map callback'])) {
  240. $map = call_user_func($options['map callback'], $values, $options);
  241. }
  242. // Then look at all unmapped values and save information for them.
  243. $mappable_values = array();
  244. $ranges = array();
  245. foreach ($values as $value) {
  246. $value = (string) $value;
  247. if (isset($map[$value])) {
  248. continue;
  249. }
  250. if ($value == '!') {
  251. // The "missing" filter is usually always the same, but we allow an easy
  252. // override via the "missing label" map option.
  253. $map['!'] = isset($options['missing label']) ? $options['missing label'] : '(' . t('none') . ')';
  254. continue;
  255. }
  256. $length = strlen($value);
  257. if ($length > 5 && $value[0] == '[' && $value[$length - 1] == ']' && ($pos = strpos($value, ' TO '))) {
  258. // This is a range filter.
  259. $lower = trim(substr($value, 1, $pos));
  260. $upper = trim(substr($value, $pos + 4, -1));
  261. if ($lower != '*') {
  262. $mappable_values[$lower] = TRUE;
  263. }
  264. if ($upper != '*') {
  265. $mappable_values[$upper] = TRUE;
  266. }
  267. $ranges[$value] = array(
  268. 'lower' => $lower,
  269. 'upper' => $upper,
  270. );
  271. }
  272. else {
  273. // A normal, single-value filter.
  274. $mappable_values[$value] = TRUE;
  275. }
  276. }
  277. if ($mappable_values) {
  278. $map += call_user_func($options['value callback'], array_keys($mappable_values), $options);
  279. }
  280. foreach ($ranges as $value => $range) {
  281. $lower = isset($map[$range['lower']]) ? $map[$range['lower']] : $range['lower'];
  282. $upper = isset($map[$range['upper']]) ? $map[$range['upper']] : $range['upper'];
  283. if ($lower == '*' && $upper == '*') {
  284. $map[$value] = t('any');
  285. }
  286. elseif ($lower == '*') {
  287. $map[$value] = "< $upper";
  288. }
  289. elseif ($upper == '*') {
  290. $map[$value] = "> $lower";
  291. }
  292. else {
  293. $map[$value] = "$lower – $upper";
  294. }
  295. }
  296. return $map;
  297. }
  298. /**
  299. * Creates a human-readable label for single facet filter values.
  300. *
  301. * @param array $values
  302. * The values for which labels should be returned.
  303. * @param array $options
  304. * An associative array containing the following information about the facet:
  305. * - field: Field information, as stored in the index, but with an additional
  306. * "key" property set to the field's internal name.
  307. * - index id: The machine name of the index for this facet.
  308. * - map callback: (optional) A callback that will be called at the beginning,
  309. * which allows initial mapping of filters. Only values not mapped by that
  310. * callback will be processed by this method.
  311. * - value callback: A callback used to map single values and the limits of
  312. * ranges. The signature is the same as for this function, but all values
  313. * will be single values.
  314. * - missing label: (optional) The label used for the "missing" facet.
  315. *
  316. * @return array
  317. * An array mapping raw facet values to their labels.
  318. */
  319. function _search_api_facetapi_facet_create_label(array $values, array $options) {
  320. $field = $options['field'];
  321. $map = array();
  322. $n = count($values);
  323. // For entities, we can simply use the entity labels.
  324. if (isset($field['entity_type'])) {
  325. $type = $field['entity_type'];
  326. $entities = entity_load($type, $values);
  327. foreach ($entities as $id => $entity) {
  328. $label = entity_label($type, $entity);
  329. if ($label) {
  330. $map[$id] = $label;
  331. }
  332. }
  333. if (count($map) == $n) {
  334. return $map;
  335. }
  336. }
  337. // Then, we check whether there is an options list for the field.
  338. $index = search_api_index_load($options['index id']);
  339. $wrapper = $index->entityWrapper();
  340. $values = drupal_map_assoc($values);
  341. foreach (explode(':', $field['key']) as $part) {
  342. if (!isset($wrapper->$part)) {
  343. $wrapper = NULL;
  344. break;
  345. }
  346. $wrapper = $wrapper->$part;
  347. while (($info = $wrapper->info()) && search_api_is_list_type($info['type'])) {
  348. $wrapper = $wrapper[0];
  349. }
  350. }
  351. if ($wrapper && ($options_list = $wrapper->optionsList('view'))) {
  352. // We have no use for empty strings, as then the facet links would be
  353. // invisible.
  354. $map += array_intersect_key(array_filter($options_list, 'strlen'), $values);
  355. if (count($map) == $n) {
  356. return $map;
  357. }
  358. }
  359. // As a "last resort" we try to create a label based on the field type, for
  360. // all values that haven't got a mapping yet.
  361. foreach (array_diff_key($values, $map) as $value) {
  362. switch ($field['type']) {
  363. case 'boolean':
  364. $map[$value] = $value ? t('true') : t('false');
  365. break;
  366. case 'date':
  367. $v = is_numeric($value) ? $value : strtotime($value);
  368. $map[$value] = format_date($v, 'short');
  369. break;
  370. case 'duration':
  371. $map[$value] = format_interval($value);
  372. break;
  373. }
  374. }
  375. return $map;
  376. }
  377. /**
  378. * Implements hook_form_FORM_ID_alter().
  379. */
  380. function search_api_facetapi_form_search_api_admin_index_fields_alter(&$form, &$form_state) {
  381. $form['#submit'][] = 'search_api_facetapi_search_api_admin_index_fields_submit';
  382. }
  383. /**
  384. * Form submission handler for search_api_admin_index_fields().
  385. */
  386. function search_api_facetapi_search_api_admin_index_fields_submit($form, &$form_state) {
  387. // Clears this searcher's cached facet definitions.
  388. $cid = 'facetapi:facet_info:search_api@' . $form_state['index']->machine_name . ':';
  389. cache_clear_all($cid, 'cache', TRUE);
  390. }