search_api_facetapi.module 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. }
  65. }
  66. return $info;
  67. }
  68. /**
  69. * Implements hook_facetapi_facet_info().
  70. */
  71. function search_api_facetapi_facetapi_facet_info(array $searcher_info) {
  72. $facet_info = array();
  73. if ('search_api' == $searcher_info['adapter']) {
  74. $index = search_api_index_load($searcher_info['instance']);
  75. if (!empty($index->options['fields'])) {
  76. $wrapper = $index->entityWrapper();
  77. $bundle_key = NULL;
  78. if (($entity_info = entity_get_info($index->item_type)) && !empty($entity_info['bundle keys']['bundle'])) {
  79. $bundle_key = $entity_info['bundle keys']['bundle'];
  80. }
  81. // Some type-specific settings. Allowing to set some additional callbacks
  82. // (and other settings) in the map options allows for easier overriding by
  83. // other modules.
  84. $type_settings = array(
  85. 'taxonomy_term' => array(
  86. 'hierarchy callback' => 'facetapi_get_taxonomy_hierarchy',
  87. ),
  88. 'date' => array(
  89. 'query type' => 'date',
  90. 'map options' => array(
  91. 'map callback' => 'facetapi_map_date',
  92. ),
  93. ),
  94. );
  95. // Iterate through the indexed fields to set the facetapi settings for
  96. // each one.
  97. foreach ($index->getFields() as $key => $field) {
  98. $field['key'] = $key;
  99. // Determine which, if any, of the field type-specific options will be
  100. // used for this field.
  101. $type = isset($field['entity_type']) ? $field['entity_type'] : $field['type'];
  102. $type_settings += array($type => array());
  103. $facet_info[$key] = $type_settings[$type] + array(
  104. 'label' => $field['name'],
  105. 'description' => t('Filter by @type.', array('@type' => $field['name'])),
  106. 'allowed operators' => array(
  107. FACETAPI_OPERATOR_AND => TRUE,
  108. FACETAPI_OPERATOR_OR => $index->server()->supportsFeature('search_api_facets_operator_or'),
  109. ),
  110. 'dependency plugins' => array('role'),
  111. 'facet missing allowed' => TRUE,
  112. 'facet mincount allowed' => TRUE,
  113. 'map callback' => 'search_api_facetapi_facet_map_callback',
  114. 'map options' => array(),
  115. 'field type' => $type,
  116. );
  117. if ($type === 'date') {
  118. $facet_info[$key]['description'] .= ' ' . t('(Caution: This may perform very poorly for large result sets.)');
  119. }
  120. $facet_info[$key]['map options'] += array(
  121. 'field' => $field,
  122. 'index id' => $index->machine_name,
  123. 'value callback' => '_search_api_facetapi_facet_create_label',
  124. );
  125. // Find out whether this property is a Field API field.
  126. if (strpos($key, ':') === FALSE) {
  127. if (isset($wrapper->$key)) {
  128. $property_info = $wrapper->$key->info();
  129. if (!empty($property_info['field'])) {
  130. $facet_info[$key]['field api name'] = $key;
  131. }
  132. }
  133. }
  134. // Add bundle information, if applicable.
  135. if ($bundle_key) {
  136. if ($key === $bundle_key) {
  137. // Set entity type this field contains bundle information for.
  138. $facet_info[$key]['field api bundles'][] = $index->item_type;
  139. }
  140. else {
  141. // Add "bundle" as possible dependency plugin.
  142. $facet_info[$key]['dependency plugins'][] = 'bundle';
  143. }
  144. }
  145. }
  146. }
  147. }
  148. return $facet_info;
  149. }
  150. /**
  151. * Implements hook_facetapi_adapters().
  152. */
  153. function search_api_facetapi_facetapi_adapters() {
  154. return array(
  155. 'search_api' => array(
  156. 'handler' => array(
  157. 'class' => 'SearchApiFacetapiAdapter',
  158. ),
  159. ),
  160. );
  161. }
  162. /**
  163. * Implements hook_facetapi_query_types().
  164. */
  165. function search_api_facetapi_facetapi_query_types() {
  166. return array(
  167. 'search_api_term' => array(
  168. 'handler' => array(
  169. 'class' => 'SearchApiFacetapiTerm',
  170. 'adapter' => 'search_api',
  171. ),
  172. ),
  173. 'search_api_date' => array(
  174. 'handler' => array(
  175. 'class' => 'SearchApiFacetapiDate',
  176. 'adapter' => 'search_api',
  177. ),
  178. ),
  179. );
  180. }
  181. /**
  182. * Implements hook_search_api_query_alter().
  183. *
  184. * Adds Facet API support to the query.
  185. */
  186. function search_api_facetapi_search_api_query_alter($query) {
  187. $index = $query->getIndex();
  188. if ($index->server()->supportsFeature('search_api_facets')) {
  189. // This is the main point of communication between the facet system and the
  190. // search back-end - it makes the query respond to active facets.
  191. $searcher = 'search_api@' . $index->machine_name;
  192. $adapter = facetapi_adapter_load($searcher);
  193. if ($adapter) {
  194. $adapter->addActiveFilters($query);
  195. }
  196. }
  197. }
  198. /**
  199. * Menu callback for the facet settings page.
  200. */
  201. function search_api_facetapi_settings($realm_name, SearchApiIndex $index) {
  202. if (!$index->enabled) {
  203. return array('#markup' => t('Since this index is at the moment disabled, no facets can be activated.'));
  204. }
  205. if (!$index->server()->supportsFeature('search_api_facets')) {
  206. return array('#markup' => t('This index uses a server that does not support facet functionality.'));
  207. }
  208. $searcher_name = 'search_api@' . $index->machine_name;
  209. module_load_include('inc', 'facetapi', 'facetapi.admin');
  210. return drupal_get_form('facetapi_realm_settings_form', $searcher_name, $realm_name);
  211. }
  212. /**
  213. * Map callback for all search_api facet fields.
  214. *
  215. * @param array $values
  216. * The values to map.
  217. * @param array $options
  218. * An associative array containing:
  219. * - field: Field information, as stored in the index, but with an additional
  220. * "key" property set to the field's internal name.
  221. * - index id: The machine name of the index for this facet.
  222. * - map callback: (optional) A callback that will be called at the beginning,
  223. * which allows initial mapping of filters. Only values not mapped by that
  224. * callback will be processed by this method.
  225. * - value callback: A callback used to map single values and the limits of
  226. * ranges. The signature is the same as for this function, but all values
  227. * will be single values.
  228. * - missing label: (optional) The label used for the "missing" facet.
  229. *
  230. * @return array
  231. * An array mapping raw filter values to their labels.
  232. */
  233. function search_api_facetapi_facet_map_callback(array $values, array $options = array()) {
  234. $map = array();
  235. // See if we have an additional map callback.
  236. if (isset($options['map callback']) && is_callable($options['map callback'])) {
  237. $map = call_user_func($options['map callback'], $values, $options);
  238. }
  239. // Then look at all unmapped values and save information for them.
  240. $mappable_values = array();
  241. $ranges = array();
  242. foreach ($values as $value) {
  243. $value = (string) $value;
  244. if (isset($map[$value])) {
  245. continue;
  246. }
  247. if ($value == '!') {
  248. // The "missing" filter is usually always the same, but we allow an easy
  249. // override via the "missing label" map option.
  250. $map['!'] = isset($options['missing label']) ? $options['missing label'] : '(' . t('none') . ')';
  251. continue;
  252. }
  253. $length = strlen($value);
  254. if ($length > 5 && $value[0] == '[' && $value[$length - 1] == ']' && ($pos = strpos($value, ' TO '))) {
  255. // This is a range filter.
  256. $lower = trim(substr($value, 1, $pos));
  257. $upper = trim(substr($value, $pos + 4, -1));
  258. if ($lower != '*') {
  259. $mappable_values[$lower] = TRUE;
  260. }
  261. if ($upper != '*') {
  262. $mappable_values[$upper] = TRUE;
  263. }
  264. $ranges[$value] = array(
  265. 'lower' => $lower,
  266. 'upper' => $upper,
  267. );
  268. }
  269. else {
  270. // A normal, single-value filter.
  271. $mappable_values[$value] = TRUE;
  272. }
  273. }
  274. if ($mappable_values) {
  275. $map += call_user_func($options['value callback'], array_keys($mappable_values), $options);
  276. }
  277. foreach ($ranges as $value => $range) {
  278. $lower = isset($map[$range['lower']]) ? $map[$range['lower']] : $range['lower'];
  279. $upper = isset($map[$range['upper']]) ? $map[$range['upper']] : $range['upper'];
  280. if ($lower == '*' && $upper == '*') {
  281. $map[$value] = t('any');
  282. }
  283. elseif ($lower == '*') {
  284. $map[$value] = "< $upper";
  285. }
  286. elseif ($upper == '*') {
  287. $map[$value] = "> $lower";
  288. }
  289. else {
  290. $map[$value] = "$lower – $upper";
  291. }
  292. }
  293. return $map;
  294. }
  295. /**
  296. * Creates a human-readable label for single facet filter values.
  297. */
  298. function _search_api_facetapi_facet_create_label(array $values, array $options) {
  299. $field = $options['field'];
  300. // For entities, we can simply use the entity labels.
  301. if (isset($field['entity_type'])) {
  302. $type = $field['entity_type'];
  303. $entities = entity_load($type, $values);
  304. $map = array();
  305. foreach ($entities as $id => $entity) {
  306. $label = entity_label($type, $entity);
  307. if ($label) {
  308. $map[$id] = $label;
  309. }
  310. }
  311. return $map;
  312. }
  313. // Then, we check whether there is an options list for the field.
  314. $index = search_api_index_load($options['index id']);
  315. $wrapper = $index->entityWrapper();
  316. foreach (explode(':', $field['key']) as $part) {
  317. if (!isset($wrapper->$part)) {
  318. $wrapper = NULL;
  319. break;
  320. }
  321. $wrapper = $wrapper->$part;
  322. while (($info = $wrapper->info()) && search_api_is_list_type($info['type'])) {
  323. $wrapper = $wrapper[0];
  324. }
  325. }
  326. if ($wrapper && ($options = $wrapper->optionsList('view'))) {
  327. return $options;
  328. }
  329. // As a "last resort" we try to create a label based on the field type.
  330. $map = array();
  331. foreach ($values as $value) {
  332. switch ($field['type']) {
  333. case 'boolean':
  334. $map[$value] = $value ? t('true') : t('false');
  335. break;
  336. case 'date':
  337. $v = is_numeric($value) ? $value : strtotime($value);
  338. $map[$value] = format_date($v, 'short');
  339. break;
  340. case 'duration':
  341. $map[$value] = format_interval($value);
  342. break;
  343. }
  344. }
  345. return $map;
  346. }
  347. /**
  348. * Implements hook_form_FORM_ID_alter().
  349. */
  350. function search_api_facetapi_form_search_api_admin_index_fields_alter(&$form, &$form_state) {
  351. $form['#submit'][] = 'search_api_facetapi_search_api_admin_index_fields_submit';
  352. }
  353. /**
  354. * Form submission handler for search_api_admin_index_fields().
  355. */
  356. function search_api_facetapi_search_api_admin_index_fields_submit($form, &$form_state) {
  357. // Clears this searcher's cached facet definitions.
  358. $cid = 'facetapi:facet_info:search_api@' . $form_state['index']->machine_name . ':';
  359. cache_clear_all($cid, 'cache', TRUE);
  360. }