callback_role_filter.inc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * @file
  4. * Contains the SearchApiAlterRoleFilter class.
  5. */
  6. /**
  7. * Data alteration that filters out users based on their role.
  8. */
  9. class SearchApiAlterRoleFilter extends SearchApiAbstractAlterCallback {
  10. /**
  11. * Overrides SearchApiAbstractAlterCallback::supportsIndex().
  12. *
  13. * This plugin only supports indexes containing users.
  14. */
  15. public function supportsIndex(SearchApiIndex $index) {
  16. if ($this->isMultiEntityIndex($index)) {
  17. return in_array('user', $index->options['datasource']['types']);
  18. }
  19. return $index->getEntityType() == 'user';
  20. }
  21. /**
  22. * Implements SearchApiAlterCallbackInterface::alterItems().
  23. */
  24. public function alterItems(array &$items) {
  25. $selected_roles = $this->options['roles'];
  26. $default = (bool) $this->options['default'];
  27. $multi_types = $this->isMultiEntityIndex($this->index);
  28. foreach ($items as $id => $item) {
  29. if ($multi_types) {
  30. if ($item->item_type !== 'user') {
  31. continue;
  32. }
  33. $item_roles = $item->user->roles;
  34. }
  35. else {
  36. $item_roles = $item->roles;
  37. }
  38. $role_match = (count(array_diff_key($item_roles, $selected_roles)) !== count($item_roles));
  39. if ($role_match === $default) {
  40. unset($items[$id]);
  41. }
  42. }
  43. }
  44. /**
  45. * Overrides SearchApiAbstractAlterCallback::configurationForm().
  46. *
  47. * Add option for the roles to include/exclude.
  48. */
  49. public function configurationForm() {
  50. $options = array_map('check_plain', user_roles());
  51. $form = array(
  52. 'default' => array(
  53. '#type' => 'radios',
  54. '#title' => t('Which users should be indexed?'),
  55. '#default_value' => isset($this->options['default']) ? $this->options['default'] : 1,
  56. '#options' => array(
  57. 1 => t('All but those from one of the selected roles'),
  58. 0 => t('Only those from the selected roles'),
  59. ),
  60. ),
  61. 'roles' => array(
  62. '#type' => 'select',
  63. '#title' => t('Roles'),
  64. '#default_value' => isset($this->options['roles']) ? $this->options['roles'] : array(),
  65. '#options' => $options,
  66. '#size' => min(4, count($options)),
  67. '#multiple' => TRUE,
  68. ),
  69. );
  70. return $form;
  71. }
  72. }