callback_add_aggregation.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * @file
  4. * Contains SearchApiAlterAddAggregation.
  5. */
  6. /**
  7. * Search API data alteration callback that adds an URL field for all items.
  8. */
  9. class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
  10. /**
  11. * The type of aggregation currently performed.
  12. *
  13. * Used to temporarily store the current aggregation type for use of
  14. * SearchApiAlterAddAggregation::reduce() with array_reduce().
  15. *
  16. * @var string
  17. */
  18. protected $reductionType;
  19. public function configurationForm() {
  20. $form['#attached']['css'][] = drupal_get_path('module', 'search_api') . '/search_api.admin.css';
  21. $fields = $this->index->getFields(FALSE);
  22. $field_options = array();
  23. foreach ($fields as $name => $field) {
  24. $field_options[$name] = check_plain($field['name']);
  25. $field_properties[$name] = array(
  26. '#attributes' => array('title' => $name),
  27. '#description' => check_plain($field['description']),
  28. );
  29. }
  30. $additional = empty($this->options['fields']) ? array() : $this->options['fields'];
  31. $types = $this->getTypes();
  32. $type_descriptions = $this->getTypes('description');
  33. $tmp = array();
  34. foreach ($types as $type => $name) {
  35. $tmp[$type] = array(
  36. '#type' => 'item',
  37. '#description' => $type_descriptions[$type],
  38. );
  39. }
  40. $type_descriptions = $tmp;
  41. $form['#id'] = 'edit-callbacks-search-api-alter-add-aggregation-settings';
  42. $form['description'] = array(
  43. '#markup' => t('<p>This data alteration lets you define additional fields that will be added to this index. ' .
  44. 'Each of these new fields will be an aggregation of one or more existing fields.</p>' .
  45. '<p>To add a new aggregated field, click the "Add new field" button and then fill out the form.</p>' .
  46. '<p>To remove a previously defined field, click the "Remove field" button.</p>' .
  47. '<p>You can also change the names or contained fields of existing aggregated fields.</p>'),
  48. );
  49. $form['fields']['#prefix'] = '<div id="search-api-alter-add-aggregation-field-settings">';
  50. $form['fields']['#suffix'] = '</div>';
  51. if (isset($this->changes)) {
  52. $form['fields']['#prefix'] .= '<div class="messages warning">All changes in the form will not be saved until the <em>Save configuration</em> button at the form bottom is clicked.</div>';
  53. }
  54. foreach ($additional as $name => $field) {
  55. $form['fields'][$name] = array(
  56. '#type' => 'fieldset',
  57. '#title' => $field['name'] ? $field['name'] : t('New field'),
  58. '#collapsible' => TRUE,
  59. '#collapsed' => (boolean) $field['name'],
  60. );
  61. $form['fields'][$name]['name'] = array(
  62. '#type' => 'textfield',
  63. '#title' => t('New field name'),
  64. '#default_value' => $field['name'],
  65. '#required' => TRUE,
  66. );
  67. $form['fields'][$name]['type'] = array(
  68. '#type' => 'select',
  69. '#title' => t('Aggregation type'),
  70. '#options' => $types,
  71. '#default_value' => $field['type'],
  72. '#required' => TRUE,
  73. );
  74. $form['fields'][$name]['type_descriptions'] = $type_descriptions;
  75. foreach (array_keys($types) as $type) {
  76. $form['fields'][$name]['type_descriptions'][$type]['#states']['visible'][':input[name="callbacks[search_api_alter_add_aggregation][settings][fields][' . $name . '][type]"]']['value'] = $type;
  77. }
  78. $form['fields'][$name]['fields'] = array_merge($field_properties, array(
  79. '#type' => 'checkboxes',
  80. '#title' => t('Contained fields'),
  81. '#options' => $field_options,
  82. '#default_value' => drupal_map_assoc($field['fields']),
  83. '#attributes' => array('class' => array('search-api-alter-add-aggregation-fields')),
  84. '#required' => TRUE,
  85. ));
  86. $form['fields'][$name]['actions'] = array(
  87. '#type' => 'actions',
  88. 'remove' => array(
  89. '#type' => 'submit',
  90. '#value' => t('Remove field'),
  91. '#submit' => array('_search_api_add_aggregation_field_submit'),
  92. '#limit_validation_errors' => array(),
  93. '#name' => 'search_api_add_aggregation_remove_' . $name,
  94. '#ajax' => array(
  95. 'callback' => '_search_api_add_aggregation_field_ajax',
  96. 'wrapper' => 'search-api-alter-add-aggregation-field-settings',
  97. ),
  98. ),
  99. );
  100. }
  101. $form['actions']['#type'] = 'actions';
  102. $form['actions']['add_field'] = array(
  103. '#type' => 'submit',
  104. '#value' => t('Add new field'),
  105. '#submit' => array('_search_api_add_aggregation_field_submit'),
  106. '#limit_validation_errors' => array(),
  107. '#ajax' => array(
  108. 'callback' => '_search_api_add_aggregation_field_ajax',
  109. 'wrapper' => 'search-api-alter-add-aggregation-field-settings',
  110. ),
  111. );
  112. return $form;
  113. }
  114. public function configurationFormValidate(array $form, array &$values, array &$form_state) {
  115. unset($values['actions']);
  116. if (empty($values['fields'])) {
  117. return;
  118. }
  119. foreach ($values['fields'] as $name => $field) {
  120. $fields = $values['fields'][$name]['fields'] = array_values(array_filter($field['fields']));
  121. unset($values['fields'][$name]['actions']);
  122. if ($field['name'] && !$fields) {
  123. form_error($form['fields'][$name]['fields'], t('You have to select at least one field to aggregate. If you want to remove an aggregated field, please delete its name.'));
  124. }
  125. }
  126. }
  127. public function configurationFormSubmit(array $form, array &$values, array &$form_state) {
  128. if (empty($values['fields'])) {
  129. return array();
  130. }
  131. $index_fields = $this->index->getFields(FALSE);
  132. foreach ($values['fields'] as $name => $field) {
  133. if (!$field['name']) {
  134. unset($values['fields'][$name]);
  135. }
  136. else {
  137. $values['fields'][$name]['description'] = $this->fieldDescription($field, $index_fields);
  138. }
  139. }
  140. $this->options = $values;
  141. return $values;
  142. }
  143. public function alterItems(array &$items) {
  144. if (!$items) {
  145. return;
  146. }
  147. if (isset($this->options['fields'])) {
  148. $types = $this->getTypes('type');
  149. foreach ($items as $item) {
  150. $wrapper = $this->index->entityWrapper($item);
  151. foreach ($this->options['fields'] as $name => $field) {
  152. if ($field['name']) {
  153. $required_fields = array();
  154. foreach ($field['fields'] as $f) {
  155. if (!isset($required_fields[$f])) {
  156. $required_fields[$f]['type'] = $types[$field['type']];
  157. }
  158. }
  159. $fields = search_api_extract_fields($wrapper, $required_fields);
  160. $values = array();
  161. foreach ($fields as $f) {
  162. if (isset($f['value'])) {
  163. $values[] = $f['value'];
  164. }
  165. }
  166. $values = $this->flattenArray($values);
  167. $this->reductionType = $field['type'];
  168. $item->$name = array_reduce($values, array($this, 'reduce'), NULL);
  169. if ($field['type'] == 'count' && !$item->$name) {
  170. $item->$name = 0;
  171. }
  172. }
  173. }
  174. }
  175. }
  176. }
  177. /**
  178. * Helper method for reducing an array to a single value.
  179. */
  180. public function reduce($a, $b) {
  181. switch ($this->reductionType) {
  182. case 'fulltext':
  183. return isset($a) ? $a . "\n\n" . $b : $b;
  184. case 'sum':
  185. return $a + $b;
  186. case 'count':
  187. return $a + 1;
  188. case 'max':
  189. return isset($a) ? max($a, $b) : $b;
  190. case 'min':
  191. return isset($a) ? min($a, $b) : $b;
  192. case 'first':
  193. return isset($a) ? $a : $b;
  194. case 'first_char':
  195. $b = "$b";
  196. if (isset($a) || $b === '') {
  197. return $a;
  198. }
  199. return drupal_substr($b, 0, 1);
  200. case 'list':
  201. if (!isset($a)) {
  202. $a = array();
  203. }
  204. $a[] = $b;
  205. return $a;
  206. }
  207. return NULL;
  208. }
  209. /**
  210. * Helper method for flattening a multi-dimensional array.
  211. */
  212. protected function flattenArray(array $data) {
  213. $ret = array();
  214. foreach ($data as $item) {
  215. if (!isset($item)) {
  216. continue;
  217. }
  218. if (is_scalar($item)) {
  219. $ret[] = $item;
  220. }
  221. else {
  222. $ret = array_merge($ret, $this->flattenArray($item));
  223. }
  224. }
  225. return $ret;
  226. }
  227. public function propertyInfo() {
  228. $types = $this->getTypes('type');
  229. $ret = array();
  230. if (isset($this->options['fields'])) {
  231. foreach ($this->options['fields'] as $name => $field) {
  232. $ret[$name] = array(
  233. 'label' => $field['name'],
  234. 'description' => empty($field['description']) ? '' : $field['description'],
  235. 'type' => $types[$field['type']],
  236. );
  237. }
  238. }
  239. return $ret;
  240. }
  241. /**
  242. * Helper method for creating a field description.
  243. */
  244. protected function fieldDescription(array $field, array $index_fields) {
  245. $fields = array();
  246. foreach ($field['fields'] as $f) {
  247. $fields[] = isset($index_fields[$f]) ? $index_fields[$f]['name'] : $f;
  248. }
  249. $type = $this->getTypes();
  250. $type = $type[$field['type']];
  251. return t('A @type aggregation of the following fields: @fields.', array('@type' => $type, '@fields' => implode(', ', $fields)));
  252. }
  253. /**
  254. * Helper method for getting all available aggregation types.
  255. *
  256. * @param string $info
  257. * (optional) One of "name", "type" or "description", to indicate what
  258. * information should be returned for the types.
  259. *
  260. * @return string[]
  261. * An associative array of aggregation type identifiers mapped to their
  262. * names, data types or descriptions, as requested.
  263. */
  264. protected function getTypes($info = 'name') {
  265. switch ($info) {
  266. case 'name':
  267. return array(
  268. 'fulltext' => t('Fulltext'),
  269. 'sum' => t('Sum'),
  270. 'count' => t('Count'),
  271. 'max' => t('Maximum'),
  272. 'min' => t('Minimum'),
  273. 'first' => t('First'),
  274. 'first_char' => t('First letter'),
  275. 'list' => t('List'),
  276. );
  277. case 'type':
  278. return array(
  279. 'fulltext' => 'text',
  280. 'sum' => 'integer',
  281. 'count' => 'integer',
  282. 'max' => 'integer',
  283. 'min' => 'integer',
  284. 'first' => 'string',
  285. 'first_char' => 'string',
  286. 'list' => 'list<string>',
  287. );
  288. case 'description':
  289. return array(
  290. 'fulltext' => t('The Fulltext aggregation concatenates the text data of all contained fields.'),
  291. 'sum' => t('The Sum aggregation adds the values of all contained fields numerically.'),
  292. 'count' => t('The Count aggregation takes the total number of contained field values as the aggregated field value.'),
  293. 'max' => t('The Maximum aggregation computes the numerically largest contained field value.'),
  294. 'min' => t('The Minimum aggregation computes the numerically smallest contained field value.'),
  295. 'first' => t('The First aggregation will simply keep the first encountered field value. This is helpful foremost when you know that a list field will only have a single value.'),
  296. 'first_char' => t('The "First letter" aggregation uses just the first letter of the first encountered field value as the aggregated value. This can, for example, be used to build a Glossary view.'),
  297. 'list' => t('The List aggregation collects all field values into a multi-valued field containing all values.'),
  298. );
  299. }
  300. return array();
  301. }
  302. /**
  303. * Submit helper callback for buttons in the callback's configuration form.
  304. */
  305. public function formButtonSubmit(array $form, array &$form_state) {
  306. $button_name = $form_state['triggering_element']['#name'];
  307. if ($button_name == 'op') {
  308. // Increment $i until the corresponding field is not set, then create the
  309. // field with that number as suffix.
  310. for ($i = 1; isset($this->options['fields']['search_api_aggregation_' . $i]); ++$i) {
  311. }
  312. $this->options['fields']['search_api_aggregation_' . $i] = array(
  313. 'name' => '',
  314. 'type' => 'fulltext',
  315. 'fields' => array(),
  316. );
  317. }
  318. else {
  319. $field = substr($button_name, 34);
  320. unset($this->options['fields'][$field]);
  321. }
  322. $form_state['rebuild'] = TRUE;
  323. $this->changes = TRUE;
  324. }
  325. }
  326. /**
  327. * Submit function for buttons in the callback's configuration form.
  328. */
  329. function _search_api_add_aggregation_field_submit(array $form, array &$form_state) {
  330. $form_state['callbacks']['search_api_alter_add_aggregation']->formButtonSubmit($form, $form_state);
  331. }
  332. /**
  333. * AJAX submit function for buttons in the callback's configuration form.
  334. */
  335. function _search_api_add_aggregation_field_ajax(array $form, array &$form_state) {
  336. return $form['callbacks']['settings']['search_api_alter_add_aggregation']['fields'];
  337. }