query_type_date.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. if ($filter) {
  53. $this->addFacetFilter($query, $field, $filter);
  54. }
  55. }
  56. }
  57. /**
  58. * Rewrites the handler-specific date range syntax to the normal facet syntax.
  59. *
  60. * @param string $value
  61. * The user-facing facet value.
  62. *
  63. * @return string|null
  64. * A facet to add as a filter, in the format used internally in this module.
  65. * Or NULL if the raw facet in $value is not valid.
  66. */
  67. protected function createRangeFilter($value) {
  68. // Ignore any filters passed directly from the server (range or missing).
  69. if (!$value || $value == '!' || (!ctype_digit($value[0]) && preg_match('/^[\[(][^ ]+ TO [^ ]+[\])]$/', $value))) {
  70. return $value ? $value : NULL;
  71. }
  72. // Parse into date parts.
  73. $parts = $this->parseRangeFilter($value);
  74. // Return NULL if the date parts are invalid or none were found.
  75. if (empty($parts)) {
  76. return NULL;
  77. }
  78. $date = new DateTime();
  79. switch (count($parts)) {
  80. case 1:
  81. $date->setDate($parts[0], 1, 1);
  82. $date->setTime(0, 0, 0);
  83. $lower = $date->format('U');
  84. $date->setDate($parts[0] + 1, 1, 1);
  85. $date->setTime(0, 0, -1);
  86. $upper = $date->format('U');
  87. break;
  88. case 2:
  89. // Luckily, $month = 13 is treated as January of next year. (The same
  90. // goes for all other parameters.) We use the inverse trick for the
  91. // seconds of the upper bound, since that's inclusive and we want to
  92. // stop at a second before the next segment starts.
  93. $date->setDate($parts[0], $parts[1], 1);
  94. $date->setTime(0, 0, 0);
  95. $lower = $date->format('U');
  96. $date->setDate($parts[0], $parts[1] + 1, 1);
  97. $date->setTime(0, 0, -1);
  98. $upper = $date->format('U');
  99. break;
  100. case 3:
  101. $date->setDate($parts[0], $parts[1], $parts[2]);
  102. $date->setTime(0, 0, 0);
  103. $lower = $date->format('U');
  104. $date->setDate($parts[0], $parts[1], $parts[2] + 1);
  105. $date->setTime(0, 0, -1);
  106. $upper = $date->format('U');
  107. break;
  108. case 4:
  109. $date->setDate($parts[0], $parts[1], $parts[2]);
  110. $date->setTime($parts[3], 0, 0);
  111. $lower = $date->format('U');
  112. $date->setTime($parts[3] + 1, 0, -1);
  113. $upper = $date->format('U');
  114. break;
  115. case 5:
  116. $date->setDate($parts[0], $parts[1], $parts[2]);
  117. $date->setTime($parts[3], $parts[4], 0);
  118. $lower = $date->format('U');
  119. $date->setTime($parts[3], $parts[4] + 1, -1);
  120. $upper = $date->format('U');
  121. break;
  122. case 6:
  123. $date->setDate($parts[0], $parts[1], $parts[2]);
  124. $date->setTime($parts[3], $parts[4], $parts[5]);
  125. return $date->format('U');
  126. default:
  127. return $value;
  128. }
  129. return "[$lower TO $upper]";
  130. }
  131. /**
  132. * Parses the date range filter value into parts.
  133. *
  134. * @param string $value
  135. * The user-facing facet value.
  136. *
  137. * @return int[]|null
  138. * An array of date parts, or NULL if an invalid value was provided.
  139. */
  140. protected static function parseRangeFilter($value) {
  141. $parts = explode('-', $value);
  142. foreach ($parts as $i => $part) {
  143. // Invalidate if part is not an integer.
  144. if ($part === '' || !is_numeric($part) || intval($part) != $part) {
  145. return NULL;
  146. }
  147. $parts[$i] = (int) $part;
  148. // Depending on the position, negative numbers or 0 are invalid.
  149. switch ($i) {
  150. case 0:
  151. // Years can contain anything – negative values are unlikely, but
  152. // technically possible.
  153. break;
  154. case 1:
  155. case 2:
  156. // Days and months have to be positive.
  157. if ($part <= 0) {
  158. return NULL;
  159. }
  160. break;
  161. default:
  162. // All others can be 0, but not negative.
  163. if ($part < 0) {
  164. return NULL;
  165. }
  166. }
  167. }
  168. return $parts;
  169. }
  170. /**
  171. * Replacement callback for replacing ISO dates with timestamps.
  172. *
  173. * Not used anymore, but kept for backwards compatibility with potential
  174. * subclasses.
  175. */
  176. public function replaceDateString($matches) {
  177. return strtotime($matches[0]);
  178. }
  179. /**
  180. * Initializes the facet's build array.
  181. *
  182. * @return array
  183. * The initialized render array.
  184. */
  185. public function build() {
  186. $facet = $this->adapter->getFacet($this->facet);
  187. $search_ids = drupal_static('search_api_facetapi_active_facets', array());
  188. $facet_key = $facet['name'] . '@' . $this->adapter->getSearcher();
  189. if (empty($search_ids[$facet_key]) || !search_api_current_search($search_ids[$facet_key])) {
  190. return array();
  191. }
  192. $search_id = $search_ids[$facet_key];
  193. $build = array();
  194. $search = search_api_current_search($search_id);
  195. $results = $search[1];
  196. // Gets total number of documents matched in search.
  197. $total = $results['result count'];
  198. // Executes query, iterates over results.
  199. if (isset($results['search_api_facets']) && isset($results['search_api_facets'][$this->facet['name']])) {
  200. $values = $results['search_api_facets'][$this->facet['name']];
  201. foreach ($values as $value) {
  202. if ($value['count']) {
  203. $filter = $value['filter'];
  204. // We only process single values further. The "missing" filter and
  205. // range filters will be passed on unchanged.
  206. if ($filter == '!') {
  207. $build[$filter]['#count'] = $value['count'];
  208. }
  209. elseif ($filter[0] == '"') {
  210. $filter = substr($value['filter'], 1, -1);
  211. if ($filter) {
  212. $raw_values[$filter] = $value['count'];
  213. }
  214. }
  215. else {
  216. $build[$filter]['#count'] = $value['count'];
  217. }
  218. }
  219. }
  220. }
  221. $settings = $facet->getSettings()->settings;
  222. // Get the finest level of detail we're allowed to drill down to.
  223. $max_granularity = FACETAPI_DATE_MINUTE;
  224. if (isset($settings['date_granularity'])) {
  225. $max_granularity = $settings['date_granularity'];
  226. }
  227. // Get the coarsest level of detail we're allowed to start at.
  228. $min_granularity = FACETAPI_DATE_YEAR;
  229. if (isset($settings['date_granularity_min'])) {
  230. $min_granularity = $settings['date_granularity_min'];
  231. }
  232. // Gets active facets, starts building hierarchy.
  233. $parent = $granularity = NULL;
  234. $active_items = $this->adapter->getActiveItems($this->facet);
  235. foreach ($active_items as $value => $item) {
  236. // If the item is active, the count is the result set count.
  237. $build[$value] = array('#count' => $total);
  238. // Gets next "gap" increment. Ignore any filters passed directly from the
  239. // server (range or missing). We always create filters starting with a
  240. // year.
  241. $value = "$value";
  242. if (!$value || !ctype_digit($value[0])) {
  243. continue;
  244. }
  245. $granularity = search_api_facetapi_date_get_granularity($value);
  246. if (!$granularity) {
  247. continue;
  248. }
  249. $granularity = facetapi_get_next_date_gap($granularity, $max_granularity);
  250. // If there is a previous item, there is a parent, uses a reference so the
  251. // arrays are populated when they are updated.
  252. if (NULL !== $parent) {
  253. $build[$parent]['#item_children'][$value] = &$build[$value];
  254. $build[$value]['#item_parents'][$parent] = $parent;
  255. }
  256. // Stores the last value iterated over.
  257. $parent = $value;
  258. }
  259. if (empty($raw_values)) {
  260. return $build;
  261. }
  262. ksort($raw_values);
  263. // Mind the gap! Calculates gap from min and max timestamps.
  264. $timestamps = array_keys($raw_values);
  265. if (NULL === $parent) {
  266. if (count($raw_values) > 1) {
  267. $granularity = facetapi_get_timestamp_gap(min($timestamps), max($timestamps), $max_granularity);
  268. // Array of numbers used to determine whether the next gap is smaller than
  269. // the minimum gap allowed in the drilldown.
  270. $gap_numbers = array(
  271. FACETAPI_DATE_YEAR => 6,
  272. FACETAPI_DATE_MONTH => 5,
  273. FACETAPI_DATE_DAY => 4,
  274. FACETAPI_DATE_HOUR => 3,
  275. FACETAPI_DATE_MINUTE => 2,
  276. FACETAPI_DATE_SECOND => 1,
  277. );
  278. // Gets gap numbers for both the gap, minimum and maximum gap, checks if
  279. // the gap is within the limit set by the $granularity parameters.
  280. if ($gap_numbers[$granularity] < $gap_numbers[$max_granularity]) {
  281. $granularity = $max_granularity;
  282. }
  283. if ($gap_numbers[$granularity] > $gap_numbers[$min_granularity]) {
  284. $granularity = $min_granularity;
  285. }
  286. }
  287. else {
  288. $granularity = $max_granularity;
  289. }
  290. }
  291. // Groups dates by the range they belong to, builds the $build array with
  292. // the facet counts and formatted range values.
  293. $format = search_api_facetapi_date_get_granularity_format($granularity);
  294. foreach ($raw_values as $value => $count) {
  295. $new_value = date($format, $value);
  296. if (!isset($build[$new_value])) {
  297. $build[$new_value] = array('#count' => $count);
  298. }
  299. // Active items already have their value set because it's the current
  300. // result count.
  301. elseif (!isset($active_items[$new_value])) {
  302. $build[$new_value]['#count'] += $count;
  303. }
  304. // Adds parent information if not already set.
  305. if (NULL !== $parent && $parent != $new_value) {
  306. $build[$parent]['#item_children'][$new_value] = &$build[$new_value];
  307. $build[$new_value]['#item_parents'][$parent] = $parent;
  308. }
  309. }
  310. return $build;
  311. }
  312. }