query_type_date.inc 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  2. /**
  3. * @file
  4. * Date query type plugin for the Search API adapter.
  5. */
  6. /**
  7. * Plugin for "date" query types.
  8. */
  9. class SearchApiFacetapiDate extends SearchApiFacetapiTerm implements FacetapiQueryTypeInterface {
  10. /**
  11. * Loads the include file containing the date API functions.
  12. */
  13. public function __construct(FacetapiAdapter $adapter, array $facet) {
  14. module_load_include('date.inc', 'facetapi');
  15. parent::__construct($adapter, $facet);
  16. }
  17. /**
  18. * Returns the query type associated with the plugin.
  19. *
  20. * @return string
  21. * The query type.
  22. */
  23. static public function getType() {
  24. return 'date';
  25. }
  26. /**
  27. * Adds the filter to the query object.
  28. *
  29. * @param $query
  30. * An object containing the query in the backend's native API.
  31. */
  32. public function execute($query) {
  33. // Return terms for this facet.
  34. $this->adapter->addFacet($this->facet, $query);
  35. $settings = $this->adapter->getFacet($this->facet)->getSettings()->settings;
  36. // First check if the facet is enabled for this search.
  37. $default_true = isset($settings['default_true']) ? $settings['default_true'] : TRUE;
  38. $facet_search_ids = isset($settings['facet_search_ids']) ? $settings['facet_search_ids'] : array();
  39. if ($default_true != empty($facet_search_ids[$query->getOption('search id')])) {
  40. // Facet is not enabled for this search ID.
  41. return;
  42. }
  43. // Change limit to "unlimited" (-1).
  44. $options = &$query->getOptions();
  45. if (!empty($options['search_api_facets'][$this->facet['name']])) {
  46. $options['search_api_facets'][$this->facet['name']]['limit'] = -1;
  47. }
  48. if ($active = $this->adapter->getActiveItems($this->facet)) {
  49. $item = end($active);
  50. $field = $this->facet['field'];
  51. $filter = $this->createRangeFilter($item['value']);
  52. $this->addFacetFilter($query, $field, $filter);
  53. }
  54. }
  55. /**
  56. * Rewrites the handler-specific date range syntax to the normal facet syntax.
  57. *
  58. * @param $value
  59. * The user-facing facet value.
  60. *
  61. * @return string
  62. * A facet to add as a filter, in the format used internally in this module.
  63. */
  64. protected function createRangeFilter($value) {
  65. // Gets the granularity. Ignore any filters passed directly from the server
  66. // (range or missing). We always create filters starting with a year.
  67. if (!$value || !ctype_digit($value[0])) {
  68. return $value;
  69. }
  70. $parts = explode('-', $value);
  71. $date = new DateTime();
  72. switch (count($parts)) {
  73. case 1:
  74. $date->setDate($parts[0], 1, 1);
  75. $date->setTime(0, 0, 0);
  76. $lower = $date->format('U');
  77. $date->setDate($parts[0] + 1, 1, 1);
  78. $date->setTime(0, 0, -1);
  79. $upper = $date->format('U');
  80. break;
  81. case 2:
  82. // Luckily, $month = 13 is treated as January of next year. (The same
  83. // goes for all other parameters.) We use the inverse trick for the
  84. // seconds of the upper bound, since that's inclusive and we want to
  85. // stop at a second before the next segment starts.
  86. $date->setDate($parts[0], $parts[1], 1);
  87. $date->setTime(0, 0, 0);
  88. $lower = $date->format('U');
  89. $date->setDate($parts[0], $parts[1] + 1, 1);
  90. $date->setTime(0, 0, -1);
  91. $upper = $date->format('U');
  92. break;
  93. case 3:
  94. $date->setDate($parts[0], $parts[1], $parts[2]);
  95. $date->setTime(0, 0, 0);
  96. $lower = $date->format('U');
  97. $date->setDate($parts[0], $parts[1], $parts[2] + 1);
  98. $date->setTime(0, 0, -1);
  99. $upper = $date->format('U');
  100. break;
  101. case 4:
  102. $date->setDate($parts[0], $parts[1], $parts[2]);
  103. $date->setTime($parts[3], 0, 0);
  104. $lower = $date->format('U');
  105. $date->setTime($parts[3] + 1, 0, -1);
  106. $upper = $date->format('U');
  107. break;
  108. case 5:
  109. $date->setDate($parts[0], $parts[1], $parts[2]);
  110. $date->setTime($parts[3], $parts[4], 0);
  111. $lower = $date->format('U');
  112. $date->setTime($parts[3], $parts[4] + 1, -1);
  113. $upper = $date->format('U');
  114. break;
  115. case 6:
  116. $date->setDate($parts[0], $parts[1], $parts[2]);
  117. $date->setTime($parts[3], $parts[4], $parts[5]);
  118. return $date->format('U');
  119. default:
  120. return $value;
  121. }
  122. return "[$lower TO $upper]";
  123. }
  124. /**
  125. * Replacement callback for replacing ISO dates with timestamps.
  126. *
  127. * Not used anymore, but kept for backwards compatibility with potential
  128. * subclasses.
  129. */
  130. public function replaceDateString($matches) {
  131. return strtotime($matches[0]);
  132. }
  133. /**
  134. * Initializes the facet's build array.
  135. *
  136. * @return array
  137. * The initialized render array.
  138. */
  139. public function build() {
  140. $facet = $this->adapter->getFacet($this->facet);
  141. $search_ids = drupal_static('search_api_facetapi_active_facets', array());
  142. if (empty($search_ids[$facet['name']]) || !search_api_current_search($search_ids[$facet['name']])) {
  143. return array();
  144. }
  145. $search_id = $search_ids[$facet['name']];
  146. $build = array();
  147. $search = search_api_current_search($search_id);
  148. $results = $search[1];
  149. // Gets total number of documents matched in search.
  150. $total = $results['result count'];
  151. // Executes query, iterates over results.
  152. if (isset($results['search_api_facets']) && isset($results['search_api_facets'][$this->facet['name']])) {
  153. $values = $results['search_api_facets'][$this->facet['name']];
  154. foreach ($values as $value) {
  155. if ($value['count']) {
  156. $filter = $value['filter'];
  157. // We only process single values further. The "missing" filter and
  158. // range filters will be passed on unchanged.
  159. if ($filter == '!') {
  160. $build[$filter]['#count'] = $value['count'];
  161. }
  162. elseif ($filter[0] == '"') {
  163. $filter = substr($value['filter'], 1, -1);
  164. if ($filter) {
  165. $raw_values[$filter] = $value['count'];
  166. }
  167. }
  168. else {
  169. $build[$filter]['#count'] = $value['count'];
  170. }
  171. }
  172. }
  173. }
  174. // Get the finest level of detail we're allowed to drill down to.
  175. $settings = $facet->getSettings()->settings;
  176. $max_granularity = isset($settings['date_granularity']) ? $settings['date_granularity'] : FACETAPI_DATE_MINUTE;
  177. // Gets active facets, starts building hierarchy.
  178. $parent = $granularity = NULL;
  179. $active_items = $this->adapter->getActiveItems($this->facet);
  180. foreach ($active_items as $value => $item) {
  181. // If the item is active, the count is the result set count.
  182. $build[$value] = array('#count' => $total);
  183. // Gets next "gap" increment. Ignore any filters passed directly from the
  184. // server (range or missing). We always create filters starting with a
  185. // year.
  186. $value = "$value";
  187. if (!$value || !ctype_digit($value[0])) {
  188. continue;
  189. }
  190. $granularity = search_api_facetapi_date_get_granularity($value);
  191. if (!$granularity) {
  192. continue;
  193. }
  194. $granularity = facetapi_get_next_date_gap($granularity, $max_granularity);
  195. // If there is a previous item, there is a parent, uses a reference so the
  196. // arrays are populated when they are updated.
  197. if (NULL !== $parent) {
  198. $build[$parent]['#item_children'][$value] = &$build[$value];
  199. $build[$value]['#item_parents'][$parent] = $parent;
  200. }
  201. // Stores the last value iterated over.
  202. $parent = $value;
  203. }
  204. if (empty($raw_values)) {
  205. return $build;
  206. }
  207. ksort($raw_values);
  208. // Mind the gap! Calculates gap from min and max timestamps.
  209. $timestamps = array_keys($raw_values);
  210. if (NULL === $parent) {
  211. if (count($raw_values) > 1) {
  212. $granularity = facetapi_get_timestamp_gap(min($timestamps), max($timestamps), $max_granularity);
  213. // Array of numbers used to determine whether the next gap is smaller than
  214. // the minimum gap allowed in the drilldown.
  215. $gap_numbers = array(
  216. FACETAPI_DATE_YEAR => 6,
  217. FACETAPI_DATE_MONTH => 5,
  218. FACETAPI_DATE_DAY => 4,
  219. FACETAPI_DATE_HOUR => 3,
  220. FACETAPI_DATE_MINUTE => 2,
  221. FACETAPI_DATE_SECOND => 1,
  222. );
  223. // Gets gap numbers for both the gap and minimum gap, checks if the gap
  224. // is within the limit set by the $granularity parameter.
  225. if ($gap_numbers[$granularity] < $gap_numbers[$max_granularity]) {
  226. $granularity = $max_granularity;
  227. }
  228. }
  229. else {
  230. $granularity = $max_granularity;
  231. }
  232. }
  233. // Groups dates by the range they belong to, builds the $build array with
  234. // the facet counts and formatted range values.
  235. $format = search_api_facetapi_date_get_granularity_format($granularity);
  236. foreach ($raw_values as $value => $count) {
  237. $new_value = date($format, $value);
  238. if (!isset($build[$new_value])) {
  239. $build[$new_value] = array('#count' => $count);
  240. }
  241. // Active items already have their value set because it's the current
  242. // result count.
  243. elseif (!isset($active_items[$new_value])) {
  244. $build[$new_value]['#count'] += $count;
  245. }
  246. // Adds parent information if not already set.
  247. if (NULL !== $parent && $parent != $new_value) {
  248. $build[$parent]['#item_children'][$new_value] = &$build[$new_value];
  249. $build[$new_value]['#item_parents'][$parent] = $parent;
  250. }
  251. }
  252. return $build;
  253. }
  254. }