search_api_facetapi.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 (_search_api_facetapi_index_support_feature($index)) {
  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' => 'search_api_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 => _search_api_facetapi_index_support_feature($index, '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 (!_search_api_facetapi_index_support_feature($index)) {
  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. * Checks whether a certain feature is supported for an index.
  217. *
  218. * @param SearchApiIndex $index
  219. * The search index which should be checked.
  220. * @param string $feature
  221. * (optional) The feature to check for. Defaults to "search_api_facets".
  222. *
  223. * @return bool
  224. * TRUE if the feature is supported by the index's server (and the index is
  225. * currently enabled), FALSE otherwise.
  226. */
  227. function _search_api_facetapi_index_support_feature(SearchApiIndex $index, $feature = 'search_api_facets') {
  228. try {
  229. $server = $index->server();
  230. return $server && $server->supportsFeature($feature);
  231. }
  232. catch (SearchApiException $e) {
  233. return FALSE;
  234. }
  235. }
  236. /**
  237. * Gets hierarchy information for taxonomy terms.
  238. *
  239. * Used as a hierarchy callback in search_api_facetapi_facetapi_facet_info().
  240. *
  241. * Internally just uses facetapi_get_taxonomy_hierarchy(), but makes sure that
  242. * our special "!" value is not passed.
  243. *
  244. * @param array $values
  245. * An array containing the term IDs.
  246. *
  247. * @return array
  248. * An associative array mapping term IDs to parent IDs (where parents could be
  249. * found).
  250. */
  251. function search_api_facetapi_get_taxonomy_hierarchy(array $values) {
  252. $values = array_filter($values, 'is_numeric');
  253. return $values ? facetapi_get_taxonomy_hierarchy($values) : array();
  254. }
  255. /**
  256. * Map callback for all search_api facet fields.
  257. *
  258. * @param array $values
  259. * The values to map.
  260. * @param array $options
  261. * An associative array containing:
  262. * - field: Field information, as stored in the index, but with an additional
  263. * "key" property set to the field's internal name.
  264. * - index id: The machine name of the index for this facet.
  265. * - map callback: (optional) A callback that will be called at the beginning,
  266. * which allows initial mapping of filters. Only values not mapped by that
  267. * callback will be processed by this method.
  268. * - value callback: A callback used to map single values and the limits of
  269. * ranges. The signature is the same as for this function, but all values
  270. * will be single values.
  271. * - missing label: (optional) The label used for the "missing" facet.
  272. *
  273. * @return array
  274. * An array mapping raw filter values to their labels.
  275. */
  276. function search_api_facetapi_facet_map_callback(array $values, array $options = array()) {
  277. $map = array();
  278. // See if we have an additional map callback.
  279. if (isset($options['map callback']) && is_callable($options['map callback'])) {
  280. $map = call_user_func($options['map callback'], $values, $options);
  281. }
  282. // Then look at all unmapped values and save information for them.
  283. $mappable_values = array();
  284. $ranges = array();
  285. foreach ($values as $value) {
  286. $value = (string) $value;
  287. if (isset($map[$value])) {
  288. continue;
  289. }
  290. if ($value == '!') {
  291. // The "missing" filter is usually always the same, but we allow an easy
  292. // override via the "missing label" map option.
  293. $map['!'] = isset($options['missing label']) ? $options['missing label'] : '(' . t('none') . ')';
  294. continue;
  295. }
  296. $length = strlen($value);
  297. if ($length > 5 && $value[0] == '[' && $value[$length - 1] == ']' && ($pos = strpos($value, ' TO '))) {
  298. // This is a range filter.
  299. $lower = trim(substr($value, 1, $pos));
  300. $upper = trim(substr($value, $pos + 4, -1));
  301. if ($lower != '*') {
  302. $mappable_values[$lower] = TRUE;
  303. }
  304. if ($upper != '*') {
  305. $mappable_values[$upper] = TRUE;
  306. }
  307. $ranges[$value] = array(
  308. 'lower' => $lower,
  309. 'upper' => $upper,
  310. );
  311. }
  312. else {
  313. // A normal, single-value filter.
  314. $mappable_values[$value] = TRUE;
  315. }
  316. }
  317. if ($mappable_values) {
  318. $map += call_user_func($options['value callback'], array_keys($mappable_values), $options);
  319. }
  320. foreach ($ranges as $value => $range) {
  321. $lower = isset($map[$range['lower']]) ? $map[$range['lower']] : $range['lower'];
  322. $upper = isset($map[$range['upper']]) ? $map[$range['upper']] : $range['upper'];
  323. if ($lower == '*' && $upper == '*') {
  324. $map[$value] = t('any');
  325. }
  326. elseif ($lower == '*') {
  327. $map[$value] = "< $upper";
  328. }
  329. elseif ($upper == '*') {
  330. $map[$value] = "> $lower";
  331. }
  332. else {
  333. $map[$value] = "$lower – $upper";
  334. }
  335. }
  336. return $map;
  337. }
  338. /**
  339. * Creates a human-readable label for single facet filter values.
  340. *
  341. * @param array $values
  342. * The values for which labels should be returned.
  343. * @param array $options
  344. * An associative array containing the following information about the facet:
  345. * - field: Field information, as stored in the index, but with an additional
  346. * "key" property set to the field's internal name.
  347. * - index id: The machine name of the index for this facet.
  348. * - map callback: (optional) A callback that will be called at the beginning,
  349. * which allows initial mapping of filters. Only values not mapped by that
  350. * callback will be processed by this method.
  351. * - value callback: A callback used to map single values and the limits of
  352. * ranges. The signature is the same as for this function, but all values
  353. * will be single values.
  354. * - missing label: (optional) The label used for the "missing" facet.
  355. *
  356. * @return array
  357. * An array mapping raw facet values to their labels.
  358. */
  359. function _search_api_facetapi_facet_create_label(array $values, array $options) {
  360. $field = $options['field'];
  361. $map = array();
  362. $n = count($values);
  363. // For entities, we can simply use the entity labels.
  364. if (isset($field['entity_type'])) {
  365. $type = $field['entity_type'];
  366. $entities = entity_load($type, $values);
  367. foreach ($entities as $id => $entity) {
  368. $label = entity_label($type, $entity);
  369. if ($label !== FALSE) {
  370. $map[$id] = $label;
  371. }
  372. }
  373. if (count($map) == $n) {
  374. return $map;
  375. }
  376. }
  377. // Then, we check whether there is an options list for the field.
  378. $index = search_api_index_load($options['index id']);
  379. $wrapper = $index->entityWrapper();
  380. $values = drupal_map_assoc($values);
  381. foreach (explode(':', $field['key']) as $part) {
  382. if (!isset($wrapper->$part)) {
  383. $wrapper = NULL;
  384. break;
  385. }
  386. $wrapper = $wrapper->$part;
  387. while (($info = $wrapper->info()) && search_api_is_list_type($info['type'])) {
  388. $wrapper = $wrapper[0];
  389. }
  390. }
  391. if ($wrapper && ($options_list = $wrapper->optionsList('view'))) {
  392. // We have no use for empty strings, as then the facet links would be
  393. // invisible.
  394. $map += array_intersect_key(array_filter($options_list, 'strlen'), $values);
  395. if (count($map) == $n) {
  396. return $map;
  397. }
  398. }
  399. // As a "last resort" we try to create a label based on the field type, for
  400. // all values that haven't got a mapping yet.
  401. foreach (array_diff_key($values, $map) as $value) {
  402. switch ($field['type']) {
  403. case 'boolean':
  404. $map[$value] = $value ? t('true') : t('false');
  405. break;
  406. case 'date':
  407. $v = is_numeric($value) ? $value : strtotime($value);
  408. $map[$value] = format_date($v, 'short');
  409. break;
  410. case 'duration':
  411. $map[$value] = format_interval($value);
  412. break;
  413. }
  414. }
  415. return $map;
  416. }
  417. /**
  418. * Implements hook_form_FORM_ID_alter().
  419. */
  420. function search_api_facetapi_form_search_api_admin_index_fields_alter(&$form, &$form_state) {
  421. $form['#submit'][] = 'search_api_facetapi_search_api_admin_index_fields_submit';
  422. }
  423. /**
  424. * Form submission handler for search_api_admin_index_fields().
  425. */
  426. function search_api_facetapi_search_api_admin_index_fields_submit($form, &$form_state) {
  427. // Clears this searcher's cached facet definitions.
  428. $cid = 'facetapi:facet_info:search_api@' . $form_state['index']->machine_name . ':';
  429. cache_clear_all($cid, 'cache', TRUE);
  430. }
  431. /**
  432. * Computes the granularity of a date facet filter.
  433. *
  434. * @param $filter
  435. * The filter value to examine.
  436. *
  437. * @return string|null
  438. * Either one of the FACETAPI_DATE_* constants corresponding to the
  439. * granularity of the filter, or NULL if it couldn't be computed.
  440. */
  441. function search_api_facetapi_date_get_granularity($filter) {
  442. // Granularity corresponds to number of dashes in filter value.
  443. $units = array(
  444. FACETAPI_DATE_YEAR,
  445. FACETAPI_DATE_MONTH,
  446. FACETAPI_DATE_DAY,
  447. FACETAPI_DATE_HOUR,
  448. FACETAPI_DATE_MINUTE,
  449. FACETAPI_DATE_SECOND,
  450. );
  451. $count = substr_count($filter, '-');
  452. return isset($units[$count]) ? $units[$count] : NULL;
  453. }
  454. /**
  455. * Returns the date format used for a given granularity.
  456. *
  457. * @param $granularity
  458. * One of the FACETAPI_DATE_* constants.
  459. *
  460. * @return string
  461. * The date format used for the given granularity.
  462. */
  463. function search_api_facetapi_date_get_granularity_format($granularity) {
  464. $formats = array(
  465. FACETAPI_DATE_YEAR => 'Y',
  466. FACETAPI_DATE_MONTH => 'Y-m',
  467. FACETAPI_DATE_DAY => 'Y-m-d',
  468. FACETAPI_DATE_HOUR => 'Y-m-d-H',
  469. FACETAPI_DATE_MINUTE => 'Y-m-d-H-i',
  470. FACETAPI_DATE_SECOND => 'Y-m-d-H-i-s',
  471. );
  472. return $formats[$granularity];
  473. }
  474. /**
  475. * Constructs labels for date facet filter values.
  476. *
  477. * @param array $values
  478. * The date facet filter values, as used in URL parameters.
  479. * @param array $options
  480. * (optional) Options for creating the mapping. The following options are
  481. * recognized:
  482. * - format callback: A callback for creating a label for a timestamp. The
  483. * function signature is like search_api_facetapi_format_timestamp(),
  484. * receiving a timestamp and one of the FACETAPI_DATE_* constants as the
  485. * parameters and returning a human-readable label.
  486. *
  487. * @return array
  488. * An array of labels for the given facet filters.
  489. */
  490. function search_api_facetapi_map_date(array $values, array $options = array()) {
  491. $map = array();
  492. foreach ($values as $value) {
  493. // Ignore any filters passed directly from the server (range or missing). We
  494. // always create filters starting with a year.
  495. $value = "$value";
  496. if (!$value || !ctype_digit($value[0])) {
  497. continue;
  498. }
  499. // Get the granularity of the filter.
  500. $granularity = search_api_facetapi_date_get_granularity($value);
  501. if (!$granularity) {
  502. continue;
  503. }
  504. // For years, the URL value is already the label.
  505. if ($granularity == FACETAPI_DATE_YEAR) {
  506. $map[$value] = $value;
  507. continue;
  508. }
  509. // Otherwise, parse the timestamp from the known format and format it as a
  510. // label.
  511. $format = search_api_facetapi_date_get_granularity_format($granularity);
  512. $date = DateTime::createFromFormat($format, $value);
  513. if (!$date) {
  514. continue;
  515. }
  516. $format_callback = 'search_api_facetapi_format_timestamp';
  517. if (!empty($options['format callback']) && is_callable($options['format callback'])) {
  518. $format_callback = $options['format callback'];
  519. }
  520. $map[$value] = call_user_func($format_callback, $date->format('U'), $granularity);
  521. }
  522. return $map;
  523. }
  524. /**
  525. * Format a date according to the default timezone and the given precision.
  526. *
  527. * @param int $timestamp
  528. * An integer containing the Unix timestamp being formated.
  529. * @param string $precision
  530. * A string containing the formatting precision. See the FACETAPI_DATE_*
  531. * constants for valid values.
  532. *
  533. * @return string
  534. * A human-readable representation of the timestamp.
  535. */
  536. function search_api_facetapi_format_timestamp($timestamp, $precision = FACETAPI_DATE_YEAR) {
  537. $formats = array(
  538. FACETAPI_DATE_YEAR => 'Y',
  539. FACETAPI_DATE_MONTH => 'F Y',
  540. FACETAPI_DATE_DAY => 'F j, Y',
  541. FACETAPI_DATE_HOUR => 'H:__',
  542. FACETAPI_DATE_MINUTE => 'H:i',
  543. FACETAPI_DATE_SECOND => 'H:i:s',
  544. );
  545. if (!isset($formats[$precision])) {
  546. $precision = FACETAPI_DATE_YEAR;
  547. }
  548. return format_date($timestamp, 'custom', $formats[$precision]);
  549. }