UserGroupMembership.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\WorkflowEngine\Check;
  7. use OCP\IGroupManager;
  8. use OCP\IL10N;
  9. use OCP\IUser;
  10. use OCP\IUserSession;
  11. use OCP\WorkflowEngine\ICheck;
  12. use OCP\WorkflowEngine\IManager;
  13. class UserGroupMembership implements ICheck {
  14. /** @var string */
  15. protected $cachedUser;
  16. /** @var string[] */
  17. protected $cachedGroupMemberships;
  18. /** @var IUserSession */
  19. protected $userSession;
  20. /** @var IGroupManager */
  21. protected $groupManager;
  22. /** @var IL10N */
  23. protected $l;
  24. /**
  25. * @param IUserSession $userSession
  26. * @param IGroupManager $groupManager
  27. * @param IL10N $l
  28. */
  29. public function __construct(IUserSession $userSession, IGroupManager $groupManager, IL10N $l) {
  30. $this->userSession = $userSession;
  31. $this->groupManager = $groupManager;
  32. $this->l = $l;
  33. }
  34. /**
  35. * @param string $operator
  36. * @param string $value
  37. * @return bool
  38. */
  39. public function executeCheck($operator, $value) {
  40. $user = $this->userSession->getUser();
  41. if ($user instanceof IUser) {
  42. $groupIds = $this->getUserGroups($user);
  43. return ($operator === 'is') === in_array($value, $groupIds);
  44. } else {
  45. return $operator !== 'is';
  46. }
  47. }
  48. /**
  49. * @param string $operator
  50. * @param string $value
  51. * @throws \UnexpectedValueException
  52. */
  53. public function validateCheck($operator, $value) {
  54. if (!in_array($operator, ['is', '!is'])) {
  55. throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
  56. }
  57. if (!$this->groupManager->groupExists($value)) {
  58. throw new \UnexpectedValueException($this->l->t('The given group does not exist'), 2);
  59. }
  60. }
  61. /**
  62. * @param IUser $user
  63. * @return string[]
  64. */
  65. protected function getUserGroups(IUser $user) {
  66. $uid = $user->getUID();
  67. if ($this->cachedUser !== $uid) {
  68. $this->cachedUser = $uid;
  69. $this->cachedGroupMemberships = $this->groupManager->getUserGroupIds($user);
  70. }
  71. return $this->cachedGroupMemberships;
  72. }
  73. public function supportedEntities(): array {
  74. // universal by default
  75. return [];
  76. }
  77. public function isAvailableForScope(int $scope): bool {
  78. // admin only by default
  79. return $scope === IManager::SCOPE_ADMIN;
  80. }
  81. }