| @@ -28,9 +28,9 @@ | ||
| 28 | 28 | * @since 17.0.0 | 
| 29 | 29 | */ | 
| 30 | 30 |  interface IGetDisplayNameBackend { | 
| 31 | - /** | |
| 32 | - * @since 17.0.0 | |
| 33 | - */ | |
| 34 | - public function getDisplayName(string $gid): string; | |
| 31 | + /** | |
| 32 | + * @since 17.0.0 | |
| 33 | + */ | |
| 34 | + public function getDisplayName(string $gid): string; | |
| 35 | 35 | |
| 36 | 36 | } | 
| @@ -42,347 +42,347 @@ | ||
| 42 | 42 | use Symfony\Component\EventDispatcher\GenericEvent; | 
| 43 | 43 | |
| 44 | 44 |  class Group implements IGroup { | 
| 45 | - /** @var null|string */ | |
| 46 | - protected $displayName; | |
| 45 | + /** @var null|string */ | |
| 46 | + protected $displayName; | |
| 47 | 47 | |
| 48 | - /** @var string */ | |
| 49 | - private $gid; | |
| 48 | + /** @var string */ | |
| 49 | + private $gid; | |
| 50 | 50 | |
| 51 | - /** @var \OC\User\User[] */ | |
| 52 | - private $users = array(); | |
| 51 | + /** @var \OC\User\User[] */ | |
| 52 | + private $users = array(); | |
| 53 | 53 | |
| 54 | - /** @var bool */ | |
| 55 | - private $usersLoaded; | |
| 54 | + /** @var bool */ | |
| 55 | + private $usersLoaded; | |
| 56 | 56 | |
| 57 | - /** @var Backend[] */ | |
| 58 | - private $backends; | |
| 59 | - /** @var EventDispatcherInterface */ | |
| 60 | - private $dispatcher; | |
| 61 | - /** @var \OC\User\Manager|IUserManager */ | |
| 62 | - private $userManager; | |
| 63 | - /** @var PublicEmitter */ | |
| 64 | - private $emitter; | |
| 57 | + /** @var Backend[] */ | |
| 58 | + private $backends; | |
| 59 | + /** @var EventDispatcherInterface */ | |
| 60 | + private $dispatcher; | |
| 61 | + /** @var \OC\User\Manager|IUserManager */ | |
| 62 | + private $userManager; | |
| 63 | + /** @var PublicEmitter */ | |
| 64 | + private $emitter; | |
| 65 | 65 | |
| 66 | 66 | |
| 67 | - /** | |
| 68 | - * @param string $gid | |
| 69 | - * @param Backend[] $backends | |
| 70 | - * @param EventDispatcherInterface $dispatcher | |
| 71 | - * @param IUserManager $userManager | |
| 72 | - * @param PublicEmitter $emitter | |
| 73 | - * @param string $displayName | |
| 74 | - */ | |
| 75 | -	public function __construct(string $gid, array $backends, EventDispatcherInterface $dispatcher, IUserManager $userManager, PublicEmitter $emitter = null, ?string $displayName = null) { | |
| 76 | - $this->gid = $gid; | |
| 77 | - $this->backends = $backends; | |
| 78 | - $this->dispatcher = $dispatcher; | |
| 79 | - $this->userManager = $userManager; | |
| 80 | - $this->emitter = $emitter; | |
| 81 | - $this->displayName = $displayName; | |
| 82 | - } | |
| 67 | + /** | |
| 68 | + * @param string $gid | |
| 69 | + * @param Backend[] $backends | |
| 70 | + * @param EventDispatcherInterface $dispatcher | |
| 71 | + * @param IUserManager $userManager | |
| 72 | + * @param PublicEmitter $emitter | |
| 73 | + * @param string $displayName | |
| 74 | + */ | |
| 75 | +    public function __construct(string $gid, array $backends, EventDispatcherInterface $dispatcher, IUserManager $userManager, PublicEmitter $emitter = null, ?string $displayName = null) { | |
| 76 | + $this->gid = $gid; | |
| 77 | + $this->backends = $backends; | |
| 78 | + $this->dispatcher = $dispatcher; | |
| 79 | + $this->userManager = $userManager; | |
| 80 | + $this->emitter = $emitter; | |
| 81 | + $this->displayName = $displayName; | |
| 82 | + } | |
| 83 | 83 | |
| 84 | -	public function getGID() { | |
| 85 | - return $this->gid; | |
| 86 | - } | |
| 84 | +    public function getGID() { | |
| 85 | + return $this->gid; | |
| 86 | + } | |
| 87 | 87 | |
| 88 | -	public function getDisplayName() { | |
| 89 | -		if (is_null($this->displayName)) { | |
| 90 | -			foreach ($this->backends as $backend) { | |
| 91 | -				if ($backend instanceof IGetDisplayNameBackend) { | |
| 92 | - $displayName = $backend->getDisplayName($this->gid); | |
| 93 | -					if (trim($displayName) !== '') { | |
| 94 | - $this->displayName = $displayName; | |
| 95 | - return $this->displayName; | |
| 96 | - } | |
| 97 | - } | |
| 98 | - } | |
| 99 | - return $this->gid; | |
| 100 | - } | |
| 101 | - return $this->displayName; | |
| 102 | - } | |
| 88 | +    public function getDisplayName() { | |
| 89 | +        if (is_null($this->displayName)) { | |
| 90 | +            foreach ($this->backends as $backend) { | |
| 91 | +                if ($backend instanceof IGetDisplayNameBackend) { | |
| 92 | + $displayName = $backend->getDisplayName($this->gid); | |
| 93 | +                    if (trim($displayName) !== '') { | |
| 94 | + $this->displayName = $displayName; | |
| 95 | + return $this->displayName; | |
| 96 | + } | |
| 97 | + } | |
| 98 | + } | |
| 99 | + return $this->gid; | |
| 100 | + } | |
| 101 | + return $this->displayName; | |
| 102 | + } | |
| 103 | 103 | |
| 104 | - /** | |
| 105 | - * get all users in the group | |
| 106 | - * | |
| 107 | - * @return \OC\User\User[] | |
| 108 | - */ | |
| 109 | -	public function getUsers() { | |
| 110 | -		if ($this->usersLoaded) { | |
| 111 | - return $this->users; | |
| 112 | - } | |
| 104 | + /** | |
| 105 | + * get all users in the group | |
| 106 | + * | |
| 107 | + * @return \OC\User\User[] | |
| 108 | + */ | |
| 109 | +    public function getUsers() { | |
| 110 | +        if ($this->usersLoaded) { | |
| 111 | + return $this->users; | |
| 112 | + } | |
| 113 | 113 | |
| 114 | - $userIds = array(); | |
| 115 | -		foreach ($this->backends as $backend) { | |
| 116 | - $diff = array_diff( | |
| 117 | - $backend->usersInGroup($this->gid), | |
| 118 | - $userIds | |
| 119 | - ); | |
| 120 | -			if ($diff) { | |
| 121 | - $userIds = array_merge($userIds, $diff); | |
| 122 | - } | |
| 123 | - } | |
| 114 | + $userIds = array(); | |
| 115 | +        foreach ($this->backends as $backend) { | |
| 116 | + $diff = array_diff( | |
| 117 | + $backend->usersInGroup($this->gid), | |
| 118 | + $userIds | |
| 119 | + ); | |
| 120 | +            if ($diff) { | |
| 121 | + $userIds = array_merge($userIds, $diff); | |
| 122 | + } | |
| 123 | + } | |
| 124 | 124 | |
| 125 | - $this->users = $this->getVerifiedUsers($userIds); | |
| 126 | - $this->usersLoaded = true; | |
| 127 | - return $this->users; | |
| 128 | - } | |
| 125 | + $this->users = $this->getVerifiedUsers($userIds); | |
| 126 | + $this->usersLoaded = true; | |
| 127 | + return $this->users; | |
| 128 | + } | |
| 129 | 129 | |
| 130 | - /** | |
| 131 | - * check if a user is in the group | |
| 132 | - * | |
| 133 | - * @param IUser $user | |
| 134 | - * @return bool | |
| 135 | - */ | |
| 136 | -	public function inGroup(IUser $user) { | |
| 137 | -		if (isset($this->users[$user->getUID()])) { | |
| 138 | - return true; | |
| 139 | - } | |
| 140 | -		foreach ($this->backends as $backend) { | |
| 141 | -			if ($backend->inGroup($user->getUID(), $this->gid)) { | |
| 142 | - $this->users[$user->getUID()] = $user; | |
| 143 | - return true; | |
| 144 | - } | |
| 145 | - } | |
| 146 | - return false; | |
| 147 | - } | |
| 130 | + /** | |
| 131 | + * check if a user is in the group | |
| 132 | + * | |
| 133 | + * @param IUser $user | |
| 134 | + * @return bool | |
| 135 | + */ | |
| 136 | +    public function inGroup(IUser $user) { | |
| 137 | +        if (isset($this->users[$user->getUID()])) { | |
| 138 | + return true; | |
| 139 | + } | |
| 140 | +        foreach ($this->backends as $backend) { | |
| 141 | +            if ($backend->inGroup($user->getUID(), $this->gid)) { | |
| 142 | + $this->users[$user->getUID()] = $user; | |
| 143 | + return true; | |
| 144 | + } | |
| 145 | + } | |
| 146 | + return false; | |
| 147 | + } | |
| 148 | 148 | |
| 149 | - /** | |
| 150 | - * add a user to the group | |
| 151 | - * | |
| 152 | - * @param IUser $user | |
| 153 | - */ | |
| 154 | -	public function addUser(IUser $user) { | |
| 155 | -		if ($this->inGroup($user)) { | |
| 156 | - return; | |
| 157 | - } | |
| 149 | + /** | |
| 150 | + * add a user to the group | |
| 151 | + * | |
| 152 | + * @param IUser $user | |
| 153 | + */ | |
| 154 | +    public function addUser(IUser $user) { | |
| 155 | +        if ($this->inGroup($user)) { | |
| 156 | + return; | |
| 157 | + } | |
| 158 | 158 | |
| 159 | - $this->dispatcher->dispatch(IGroup::class . '::preAddUser', new GenericEvent($this, [ | |
| 160 | - 'user' => $user, | |
| 161 | - ])); | |
| 159 | + $this->dispatcher->dispatch(IGroup::class . '::preAddUser', new GenericEvent($this, [ | |
| 160 | + 'user' => $user, | |
| 161 | + ])); | |
| 162 | 162 | |
| 163 | -		if ($this->emitter) { | |
| 164 | -			$this->emitter->emit('\OC\Group', 'preAddUser', array($this, $user)); | |
| 165 | - } | |
| 166 | -		foreach ($this->backends as $backend) { | |
| 167 | -			if ($backend->implementsActions(\OC\Group\Backend::ADD_TO_GROUP)) { | |
| 168 | - $backend->addToGroup($user->getUID(), $this->gid); | |
| 169 | -				if ($this->users) { | |
| 170 | - $this->users[$user->getUID()] = $user; | |
| 171 | - } | |
| 163 | +        if ($this->emitter) { | |
| 164 | +            $this->emitter->emit('\OC\Group', 'preAddUser', array($this, $user)); | |
| 165 | + } | |
| 166 | +        foreach ($this->backends as $backend) { | |
| 167 | +            if ($backend->implementsActions(\OC\Group\Backend::ADD_TO_GROUP)) { | |
| 168 | + $backend->addToGroup($user->getUID(), $this->gid); | |
| 169 | +                if ($this->users) { | |
| 170 | + $this->users[$user->getUID()] = $user; | |
| 171 | + } | |
| 172 | 172 | |
| 173 | - $this->dispatcher->dispatch(IGroup::class . '::postAddUser', new GenericEvent($this, [ | |
| 174 | - 'user' => $user, | |
| 175 | - ])); | |
| 173 | + $this->dispatcher->dispatch(IGroup::class . '::postAddUser', new GenericEvent($this, [ | |
| 174 | + 'user' => $user, | |
| 175 | + ])); | |
| 176 | 176 | |
| 177 | -				if ($this->emitter) { | |
| 178 | -					$this->emitter->emit('\OC\Group', 'postAddUser', array($this, $user)); | |
| 179 | - } | |
| 180 | - return; | |
| 181 | - } | |
| 182 | - } | |
| 183 | - } | |
| 177 | +                if ($this->emitter) { | |
| 178 | +                    $this->emitter->emit('\OC\Group', 'postAddUser', array($this, $user)); | |
| 179 | + } | |
| 180 | + return; | |
| 181 | + } | |
| 182 | + } | |
| 183 | + } | |
| 184 | 184 | |
| 185 | - /** | |
| 186 | - * remove a user from the group | |
| 187 | - * | |
| 188 | - * @param \OC\User\User $user | |
| 189 | - */ | |
| 190 | -	public function removeUser($user) { | |
| 191 | - $result = false; | |
| 192 | - $this->dispatcher->dispatch(IGroup::class . '::preRemoveUser', new GenericEvent($this, [ | |
| 193 | - 'user' => $user, | |
| 194 | - ])); | |
| 195 | -		if ($this->emitter) { | |
| 196 | -			$this->emitter->emit('\OC\Group', 'preRemoveUser', array($this, $user)); | |
| 197 | - } | |
| 198 | -		foreach ($this->backends as $backend) { | |
| 199 | -			if ($backend->implementsActions(\OC\Group\Backend::REMOVE_FROM_GOUP) and $backend->inGroup($user->getUID(), $this->gid)) { | |
| 200 | - $backend->removeFromGroup($user->getUID(), $this->gid); | |
| 201 | - $result = true; | |
| 202 | - } | |
| 203 | - } | |
| 204 | -		if ($result) { | |
| 205 | - $this->dispatcher->dispatch(IGroup::class . '::postRemoveUser', new GenericEvent($this, [ | |
| 206 | - 'user' => $user, | |
| 207 | - ])); | |
| 208 | -			if ($this->emitter) { | |
| 209 | -				$this->emitter->emit('\OC\Group', 'postRemoveUser', array($this, $user)); | |
| 210 | - } | |
| 211 | -			if ($this->users) { | |
| 212 | -				foreach ($this->users as $index => $groupUser) { | |
| 213 | -					if ($groupUser->getUID() === $user->getUID()) { | |
| 214 | - unset($this->users[$index]); | |
| 215 | - return; | |
| 216 | - } | |
| 217 | - } | |
| 218 | - } | |
| 219 | - } | |
| 220 | - } | |
| 185 | + /** | |
| 186 | + * remove a user from the group | |
| 187 | + * | |
| 188 | + * @param \OC\User\User $user | |
| 189 | + */ | |
| 190 | +    public function removeUser($user) { | |
| 191 | + $result = false; | |
| 192 | + $this->dispatcher->dispatch(IGroup::class . '::preRemoveUser', new GenericEvent($this, [ | |
| 193 | + 'user' => $user, | |
| 194 | + ])); | |
| 195 | +        if ($this->emitter) { | |
| 196 | +            $this->emitter->emit('\OC\Group', 'preRemoveUser', array($this, $user)); | |
| 197 | + } | |
| 198 | +        foreach ($this->backends as $backend) { | |
| 199 | +            if ($backend->implementsActions(\OC\Group\Backend::REMOVE_FROM_GOUP) and $backend->inGroup($user->getUID(), $this->gid)) { | |
| 200 | + $backend->removeFromGroup($user->getUID(), $this->gid); | |
| 201 | + $result = true; | |
| 202 | + } | |
| 203 | + } | |
| 204 | +        if ($result) { | |
| 205 | + $this->dispatcher->dispatch(IGroup::class . '::postRemoveUser', new GenericEvent($this, [ | |
| 206 | + 'user' => $user, | |
| 207 | + ])); | |
| 208 | +            if ($this->emitter) { | |
| 209 | +                $this->emitter->emit('\OC\Group', 'postRemoveUser', array($this, $user)); | |
| 210 | + } | |
| 211 | +            if ($this->users) { | |
| 212 | +                foreach ($this->users as $index => $groupUser) { | |
| 213 | +                    if ($groupUser->getUID() === $user->getUID()) { | |
| 214 | + unset($this->users[$index]); | |
| 215 | + return; | |
| 216 | + } | |
| 217 | + } | |
| 218 | + } | |
| 219 | + } | |
| 220 | + } | |
| 221 | 221 | |
| 222 | - /** | |
| 223 | - * search for users in the group by userid | |
| 224 | - * | |
| 225 | - * @param string $search | |
| 226 | - * @param int $limit | |
| 227 | - * @param int $offset | |
| 228 | - * @return \OC\User\User[] | |
| 229 | - */ | |
| 230 | -	public function searchUsers($search, $limit = null, $offset = null) { | |
| 231 | - $users = array(); | |
| 232 | -		foreach ($this->backends as $backend) { | |
| 233 | - $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset); | |
| 234 | - $users += $this->getVerifiedUsers($userIds); | |
| 235 | -			if (!is_null($limit) and $limit <= 0) { | |
| 236 | - return $users; | |
| 237 | - } | |
| 238 | - } | |
| 239 | - return $users; | |
| 240 | - } | |
| 222 | + /** | |
| 223 | + * search for users in the group by userid | |
| 224 | + * | |
| 225 | + * @param string $search | |
| 226 | + * @param int $limit | |
| 227 | + * @param int $offset | |
| 228 | + * @return \OC\User\User[] | |
| 229 | + */ | |
| 230 | +    public function searchUsers($search, $limit = null, $offset = null) { | |
| 231 | + $users = array(); | |
| 232 | +        foreach ($this->backends as $backend) { | |
| 233 | + $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset); | |
| 234 | + $users += $this->getVerifiedUsers($userIds); | |
| 235 | +            if (!is_null($limit) and $limit <= 0) { | |
| 236 | + return $users; | |
| 237 | + } | |
| 238 | + } | |
| 239 | + return $users; | |
| 240 | + } | |
| 241 | 241 | |
| 242 | - /** | |
| 243 | - * returns the number of users matching the search string | |
| 244 | - * | |
| 245 | - * @param string $search | |
| 246 | - * @return int|bool | |
| 247 | - */ | |
| 248 | -	public function count($search = '') { | |
| 249 | - $users = false; | |
| 250 | -		foreach ($this->backends as $backend) { | |
| 251 | -			if($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { | |
| 252 | -				if($users === false) { | |
| 253 | - //we could directly add to a bool variable, but this would | |
| 254 | - //be ugly | |
| 255 | - $users = 0; | |
| 256 | - } | |
| 257 | - $users += $backend->countUsersInGroup($this->gid, $search); | |
| 258 | - } | |
| 259 | - } | |
| 260 | - return $users; | |
| 261 | - } | |
| 242 | + /** | |
| 243 | + * returns the number of users matching the search string | |
| 244 | + * | |
| 245 | + * @param string $search | |
| 246 | + * @return int|bool | |
| 247 | + */ | |
| 248 | +    public function count($search = '') { | |
| 249 | + $users = false; | |
| 250 | +        foreach ($this->backends as $backend) { | |
| 251 | +            if($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) { | |
| 252 | +                if($users === false) { | |
| 253 | + //we could directly add to a bool variable, but this would | |
| 254 | + //be ugly | |
| 255 | + $users = 0; | |
| 256 | + } | |
| 257 | + $users += $backend->countUsersInGroup($this->gid, $search); | |
| 258 | + } | |
| 259 | + } | |
| 260 | + return $users; | |
| 261 | + } | |
| 262 | 262 | |
| 263 | - /** | |
| 264 | - * returns the number of disabled users | |
| 265 | - * | |
| 266 | - * @return int|bool | |
| 267 | - */ | |
| 268 | -	public function countDisabled() { | |
| 269 | - $users = false; | |
| 270 | -		foreach ($this->backends as $backend) { | |
| 271 | -			if($backend instanceOf ICountDisabledInGroup) { | |
| 272 | -				if($users === false) { | |
| 273 | - //we could directly add to a bool variable, but this would | |
| 274 | - //be ugly | |
| 275 | - $users = 0; | |
| 276 | - } | |
| 277 | - $users += $backend->countDisabledInGroup($this->gid); | |
| 278 | - } | |
| 279 | - } | |
| 280 | - return $users; | |
| 281 | - } | |
| 263 | + /** | |
| 264 | + * returns the number of disabled users | |
| 265 | + * | |
| 266 | + * @return int|bool | |
| 267 | + */ | |
| 268 | +    public function countDisabled() { | |
| 269 | + $users = false; | |
| 270 | +        foreach ($this->backends as $backend) { | |
| 271 | +            if($backend instanceOf ICountDisabledInGroup) { | |
| 272 | +                if($users === false) { | |
| 273 | + //we could directly add to a bool variable, but this would | |
| 274 | + //be ugly | |
| 275 | + $users = 0; | |
| 276 | + } | |
| 277 | + $users += $backend->countDisabledInGroup($this->gid); | |
| 278 | + } | |
| 279 | + } | |
| 280 | + return $users; | |
| 281 | + } | |
| 282 | 282 | |
| 283 | - /** | |
| 284 | - * search for users in the group by displayname | |
| 285 | - * | |
| 286 | - * @param string $search | |
| 287 | - * @param int $limit | |
| 288 | - * @param int $offset | |
| 289 | - * @return \OC\User\User[] | |
| 290 | - */ | |
| 291 | -	public function searchDisplayName($search, $limit = null, $offset = null) { | |
| 292 | - $users = array(); | |
| 293 | -		foreach ($this->backends as $backend) { | |
| 294 | - $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset); | |
| 295 | - $users = $this->getVerifiedUsers($userIds); | |
| 296 | -			if (!is_null($limit) and $limit <= 0) { | |
| 297 | - return array_values($users); | |
| 298 | - } | |
| 299 | - } | |
| 300 | - return array_values($users); | |
| 301 | - } | |
| 283 | + /** | |
| 284 | + * search for users in the group by displayname | |
| 285 | + * | |
| 286 | + * @param string $search | |
| 287 | + * @param int $limit | |
| 288 | + * @param int $offset | |
| 289 | + * @return \OC\User\User[] | |
| 290 | + */ | |
| 291 | +    public function searchDisplayName($search, $limit = null, $offset = null) { | |
| 292 | + $users = array(); | |
| 293 | +        foreach ($this->backends as $backend) { | |
| 294 | + $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset); | |
| 295 | + $users = $this->getVerifiedUsers($userIds); | |
| 296 | +            if (!is_null($limit) and $limit <= 0) { | |
| 297 | + return array_values($users); | |
| 298 | + } | |
| 299 | + } | |
| 300 | + return array_values($users); | |
| 301 | + } | |
| 302 | 302 | |
| 303 | - /** | |
| 304 | - * delete the group | |
| 305 | - * | |
| 306 | - * @return bool | |
| 307 | - */ | |
| 308 | -	public function delete() { | |
| 309 | - // Prevent users from deleting group admin | |
| 310 | -		if ($this->getGID() === 'admin') { | |
| 311 | - return false; | |
| 312 | - } | |
| 303 | + /** | |
| 304 | + * delete the group | |
| 305 | + * | |
| 306 | + * @return bool | |
| 307 | + */ | |
| 308 | +    public function delete() { | |
| 309 | + // Prevent users from deleting group admin | |
| 310 | +        if ($this->getGID() === 'admin') { | |
| 311 | + return false; | |
| 312 | + } | |
| 313 | 313 | |
| 314 | - $result = false; | |
| 315 | - $this->dispatcher->dispatch(IGroup::class . '::preDelete', new GenericEvent($this)); | |
| 316 | -		if ($this->emitter) { | |
| 317 | -			$this->emitter->emit('\OC\Group', 'preDelete', array($this)); | |
| 318 | - } | |
| 319 | -		foreach ($this->backends as $backend) { | |
| 320 | -			if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) { | |
| 321 | - $result = true; | |
| 322 | - $backend->deleteGroup($this->gid); | |
| 323 | - } | |
| 324 | - } | |
| 325 | -		if ($result) { | |
| 326 | - $this->dispatcher->dispatch(IGroup::class . '::postDelete', new GenericEvent($this)); | |
| 327 | -			if ($this->emitter) { | |
| 328 | -				$this->emitter->emit('\OC\Group', 'postDelete', array($this)); | |
| 329 | - } | |
| 330 | - } | |
| 331 | - return $result; | |
| 332 | - } | |
| 314 | + $result = false; | |
| 315 | + $this->dispatcher->dispatch(IGroup::class . '::preDelete', new GenericEvent($this)); | |
| 316 | +        if ($this->emitter) { | |
| 317 | +            $this->emitter->emit('\OC\Group', 'preDelete', array($this)); | |
| 318 | + } | |
| 319 | +        foreach ($this->backends as $backend) { | |
| 320 | +            if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) { | |
| 321 | + $result = true; | |
| 322 | + $backend->deleteGroup($this->gid); | |
| 323 | + } | |
| 324 | + } | |
| 325 | +        if ($result) { | |
| 326 | + $this->dispatcher->dispatch(IGroup::class . '::postDelete', new GenericEvent($this)); | |
| 327 | +            if ($this->emitter) { | |
| 328 | +                $this->emitter->emit('\OC\Group', 'postDelete', array($this)); | |
| 329 | + } | |
| 330 | + } | |
| 331 | + return $result; | |
| 332 | + } | |
| 333 | 333 | |
| 334 | - /** | |
| 335 | - * returns all the Users from an array that really exists | |
| 336 | - * @param string[] $userIds an array containing user IDs | |
| 337 | - * @return \OC\User\User[] an Array with the userId as Key and \OC\User\User as value | |
| 338 | - */ | |
| 339 | -	private function getVerifiedUsers($userIds) { | |
| 340 | -		if (!is_array($userIds)) { | |
| 341 | - return array(); | |
| 342 | - } | |
| 343 | - $users = array(); | |
| 344 | -		foreach ($userIds as $userId) { | |
| 345 | - $user = $this->userManager->get($userId); | |
| 346 | -			if (!is_null($user)) { | |
| 347 | - $users[$userId] = $user; | |
| 348 | - } | |
| 349 | - } | |
| 350 | - return $users; | |
| 351 | - } | |
| 334 | + /** | |
| 335 | + * returns all the Users from an array that really exists | |
| 336 | + * @param string[] $userIds an array containing user IDs | |
| 337 | + * @return \OC\User\User[] an Array with the userId as Key and \OC\User\User as value | |
| 338 | + */ | |
| 339 | +    private function getVerifiedUsers($userIds) { | |
| 340 | +        if (!is_array($userIds)) { | |
| 341 | + return array(); | |
| 342 | + } | |
| 343 | + $users = array(); | |
| 344 | +        foreach ($userIds as $userId) { | |
| 345 | + $user = $this->userManager->get($userId); | |
| 346 | +            if (!is_null($user)) { | |
| 347 | + $users[$userId] = $user; | |
| 348 | + } | |
| 349 | + } | |
| 350 | + return $users; | |
| 351 | + } | |
| 352 | 352 | |
| 353 | - /** | |
| 354 | - * @return bool | |
| 355 | - * @since 14.0.0 | |
| 356 | - */ | |
| 357 | -	public function canRemoveUser() { | |
| 358 | -		foreach ($this->backends as $backend) { | |
| 359 | -			if ($backend->implementsActions(GroupInterface::REMOVE_FROM_GOUP)) { | |
| 360 | - return true; | |
| 361 | - } | |
| 362 | - } | |
| 363 | - return false; | |
| 364 | - } | |
| 353 | + /** | |
| 354 | + * @return bool | |
| 355 | + * @since 14.0.0 | |
| 356 | + */ | |
| 357 | +    public function canRemoveUser() { | |
| 358 | +        foreach ($this->backends as $backend) { | |
| 359 | +            if ($backend->implementsActions(GroupInterface::REMOVE_FROM_GOUP)) { | |
| 360 | + return true; | |
| 361 | + } | |
| 362 | + } | |
| 363 | + return false; | |
| 364 | + } | |
| 365 | 365 | |
| 366 | - /** | |
| 367 | - * @return bool | |
| 368 | - * @since 14.0.0 | |
| 369 | - */ | |
| 370 | -	public function canAddUser() { | |
| 371 | -		foreach ($this->backends as $backend) { | |
| 372 | -			if ($backend->implementsActions(GroupInterface::ADD_TO_GROUP)) { | |
| 373 | - return true; | |
| 374 | - } | |
| 375 | - } | |
| 376 | - return false; | |
| 377 | - } | |
| 366 | + /** | |
| 367 | + * @return bool | |
| 368 | + * @since 14.0.0 | |
| 369 | + */ | |
| 370 | +    public function canAddUser() { | |
| 371 | +        foreach ($this->backends as $backend) { | |
| 372 | +            if ($backend->implementsActions(GroupInterface::ADD_TO_GROUP)) { | |
| 373 | + return true; | |
| 374 | + } | |
| 375 | + } | |
| 376 | + return false; | |
| 377 | + } | |
| 378 | 378 | |
| 379 | - /** | |
| 380 | - * @return bool | |
| 381 | - * @since 16.0.0 | |
| 382 | - */ | |
| 383 | -	public function hideFromCollaboration(): bool { | |
| 384 | -		return array_reduce($this->backends, function(bool $hide, GroupInterface $backend) { | |
| 385 | - return $hide | ($backend instanceof IHideFromCollaborationBackend && $backend->hideGroup($this->gid)); | |
| 386 | - }, false); | |
| 387 | - } | |
| 379 | + /** | |
| 380 | + * @return bool | |
| 381 | + * @since 16.0.0 | |
| 382 | + */ | |
| 383 | +    public function hideFromCollaboration(): bool { | |
| 384 | +        return array_reduce($this->backends, function(bool $hide, GroupInterface $backend) { | |
| 385 | + return $hide | ($backend instanceof IHideFromCollaborationBackend && $backend->hideGroup($this->gid)); | |
| 386 | + }, false); | |
| 387 | + } | |
| 388 | 388 | } | 
| @@ -30,251 +30,251 @@ | ||
| 30 | 30 | use OCP\Group\Backend\IGetDisplayNameBackend; | 
| 31 | 31 | |
| 32 | 32 |  class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend { | 
| 33 | - private $backends = array(); | |
| 34 | - private $refBackend = null; | |
| 33 | + private $backends = array(); | |
| 34 | + private $refBackend = null; | |
| 35 | 35 | |
| 36 | - /** | |
| 37 | - * Constructor | |
| 38 | - * @param string[] $serverConfigPrefixes array containing the config Prefixes | |
| 39 | - */ | |
| 40 | -	public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) { | |
| 41 | - parent::__construct($ldap); | |
| 42 | -		foreach($serverConfigPrefixes as $configPrefix) { | |
| 43 | - $this->backends[$configPrefix] = | |
| 44 | - new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager); | |
| 45 | -			if(is_null($this->refBackend)) { | |
| 46 | - $this->refBackend = &$this->backends[$configPrefix]; | |
| 47 | - } | |
| 48 | - } | |
| 49 | - } | |
| 36 | + /** | |
| 37 | + * Constructor | |
| 38 | + * @param string[] $serverConfigPrefixes array containing the config Prefixes | |
| 39 | + */ | |
| 40 | +    public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) { | |
| 41 | + parent::__construct($ldap); | |
| 42 | +        foreach($serverConfigPrefixes as $configPrefix) { | |
| 43 | + $this->backends[$configPrefix] = | |
| 44 | + new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager); | |
| 45 | +            if(is_null($this->refBackend)) { | |
| 46 | + $this->refBackend = &$this->backends[$configPrefix]; | |
| 47 | + } | |
| 48 | + } | |
| 49 | + } | |
| 50 | 50 | |
| 51 | - /** | |
| 52 | - * Tries the backends one after the other until a positive result is returned from the specified method | |
| 53 | - * @param string $gid the gid connected to the request | |
| 54 | - * @param string $method the method of the group backend that shall be called | |
| 55 | - * @param array $parameters an array of parameters to be passed | |
| 56 | - * @return mixed, the result of the method or false | |
| 57 | - */ | |
| 58 | -	protected function walkBackends($gid, $method, $parameters) { | |
| 59 | - $cacheKey = $this->getGroupCacheKey($gid); | |
| 60 | -		foreach($this->backends as $configPrefix => $backend) { | |
| 61 | -			if($result = call_user_func_array(array($backend, $method), $parameters)) { | |
| 62 | - $this->writeToCache($cacheKey, $configPrefix); | |
| 63 | - return $result; | |
| 64 | - } | |
| 65 | - } | |
| 66 | - return false; | |
| 67 | - } | |
| 51 | + /** | |
| 52 | + * Tries the backends one after the other until a positive result is returned from the specified method | |
| 53 | + * @param string $gid the gid connected to the request | |
| 54 | + * @param string $method the method of the group backend that shall be called | |
| 55 | + * @param array $parameters an array of parameters to be passed | |
| 56 | + * @return mixed, the result of the method or false | |
| 57 | + */ | |
| 58 | +    protected function walkBackends($gid, $method, $parameters) { | |
| 59 | + $cacheKey = $this->getGroupCacheKey($gid); | |
| 60 | +        foreach($this->backends as $configPrefix => $backend) { | |
| 61 | +            if($result = call_user_func_array(array($backend, $method), $parameters)) { | |
| 62 | + $this->writeToCache($cacheKey, $configPrefix); | |
| 63 | + return $result; | |
| 64 | + } | |
| 65 | + } | |
| 66 | + return false; | |
| 67 | + } | |
| 68 | 68 | |
| 69 | - /** | |
| 70 | - * Asks the backend connected to the server that supposely takes care of the gid from the request. | |
| 71 | - * @param string $gid the gid connected to the request | |
| 72 | - * @param string $method the method of the group backend that shall be called | |
| 73 | - * @param array $parameters an array of parameters to be passed | |
| 74 | - * @param mixed $passOnWhen the result matches this variable | |
| 75 | - * @return mixed, the result of the method or false | |
| 76 | - */ | |
| 77 | -	protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) { | |
| 78 | - $cacheKey = $this->getGroupCacheKey($gid); | |
| 79 | - $prefix = $this->getFromCache($cacheKey); | |
| 80 | - //in case the uid has been found in the past, try this stored connection first | |
| 81 | -		if(!is_null($prefix)) { | |
| 82 | -			if(isset($this->backends[$prefix])) { | |
| 83 | - $result = call_user_func_array(array($this->backends[$prefix], $method), $parameters); | |
| 84 | -				if($result === $passOnWhen) { | |
| 85 | - //not found here, reset cache to null if group vanished | |
| 86 | - //because sometimes methods return false with a reason | |
| 87 | - $groupExists = call_user_func_array( | |
| 88 | - array($this->backends[$prefix], 'groupExists'), | |
| 89 | - array($gid) | |
| 90 | - ); | |
| 91 | -					if(!$groupExists) { | |
| 92 | - $this->writeToCache($cacheKey, null); | |
| 93 | - } | |
| 94 | - } | |
| 95 | - return $result; | |
| 96 | - } | |
| 97 | - } | |
| 98 | - return false; | |
| 99 | - } | |
| 69 | + /** | |
| 70 | + * Asks the backend connected to the server that supposely takes care of the gid from the request. | |
| 71 | + * @param string $gid the gid connected to the request | |
| 72 | + * @param string $method the method of the group backend that shall be called | |
| 73 | + * @param array $parameters an array of parameters to be passed | |
| 74 | + * @param mixed $passOnWhen the result matches this variable | |
| 75 | + * @return mixed, the result of the method or false | |
| 76 | + */ | |
| 77 | +    protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) { | |
| 78 | + $cacheKey = $this->getGroupCacheKey($gid); | |
| 79 | + $prefix = $this->getFromCache($cacheKey); | |
| 80 | + //in case the uid has been found in the past, try this stored connection first | |
| 81 | +        if(!is_null($prefix)) { | |
| 82 | +            if(isset($this->backends[$prefix])) { | |
| 83 | + $result = call_user_func_array(array($this->backends[$prefix], $method), $parameters); | |
| 84 | +                if($result === $passOnWhen) { | |
| 85 | + //not found here, reset cache to null if group vanished | |
| 86 | + //because sometimes methods return false with a reason | |
| 87 | + $groupExists = call_user_func_array( | |
| 88 | + array($this->backends[$prefix], 'groupExists'), | |
| 89 | + array($gid) | |
| 90 | + ); | |
| 91 | +                    if(!$groupExists) { | |
| 92 | + $this->writeToCache($cacheKey, null); | |
| 93 | + } | |
| 94 | + } | |
| 95 | + return $result; | |
| 96 | + } | |
| 97 | + } | |
| 98 | + return false; | |
| 99 | + } | |
| 100 | 100 | |
| 101 | - /** | |
| 102 | - * is user in group? | |
| 103 | - * @param string $uid uid of the user | |
| 104 | - * @param string $gid gid of the group | |
| 105 | - * @return bool | |
| 106 | - * | |
| 107 | - * Checks whether the user is member of a group or not. | |
| 108 | - */ | |
| 109 | -	public function inGroup($uid, $gid) { | |
| 110 | - return $this->handleRequest($gid, 'inGroup', array($uid, $gid)); | |
| 111 | - } | |
| 101 | + /** | |
| 102 | + * is user in group? | |
| 103 | + * @param string $uid uid of the user | |
| 104 | + * @param string $gid gid of the group | |
| 105 | + * @return bool | |
| 106 | + * | |
| 107 | + * Checks whether the user is member of a group or not. | |
| 108 | + */ | |
| 109 | +    public function inGroup($uid, $gid) { | |
| 110 | + return $this->handleRequest($gid, 'inGroup', array($uid, $gid)); | |
| 111 | + } | |
| 112 | 112 | |
| 113 | - /** | |
| 114 | - * Get all groups a user belongs to | |
| 115 | - * @param string $uid Name of the user | |
| 116 | - * @return string[] with group names | |
| 117 | - * | |
| 118 | - * This function fetches all groups a user belongs to. It does not check | |
| 119 | - * if the user exists at all. | |
| 120 | - */ | |
| 121 | -	public function getUserGroups($uid) { | |
| 122 | - $groups = array(); | |
| 113 | + /** | |
| 114 | + * Get all groups a user belongs to | |
| 115 | + * @param string $uid Name of the user | |
| 116 | + * @return string[] with group names | |
| 117 | + * | |
| 118 | + * This function fetches all groups a user belongs to. It does not check | |
| 119 | + * if the user exists at all. | |
| 120 | + */ | |
| 121 | +    public function getUserGroups($uid) { | |
| 122 | + $groups = array(); | |
| 123 | 123 | |
| 124 | -		foreach($this->backends as $backend) { | |
| 125 | - $backendGroups = $backend->getUserGroups($uid); | |
| 126 | -			if (is_array($backendGroups)) { | |
| 127 | - $groups = array_merge($groups, $backendGroups); | |
| 128 | - } | |
| 129 | - } | |
| 124 | +        foreach($this->backends as $backend) { | |
| 125 | + $backendGroups = $backend->getUserGroups($uid); | |
| 126 | +            if (is_array($backendGroups)) { | |
| 127 | + $groups = array_merge($groups, $backendGroups); | |
| 128 | + } | |
| 129 | + } | |
| 130 | 130 | |
| 131 | - return $groups; | |
| 132 | - } | |
| 131 | + return $groups; | |
| 132 | + } | |
| 133 | 133 | |
| 134 | - /** | |
| 135 | - * get a list of all users in a group | |
| 136 | - * @return string[] with user ids | |
| 137 | - */ | |
| 138 | -	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { | |
| 139 | - $users = array(); | |
| 134 | + /** | |
| 135 | + * get a list of all users in a group | |
| 136 | + * @return string[] with user ids | |
| 137 | + */ | |
| 138 | +    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { | |
| 139 | + $users = array(); | |
| 140 | 140 | |
| 141 | -		foreach($this->backends as $backend) { | |
| 142 | - $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset); | |
| 143 | -			if (is_array($backendUsers)) { | |
| 144 | - $users = array_merge($users, $backendUsers); | |
| 145 | - } | |
| 146 | - } | |
| 141 | +        foreach($this->backends as $backend) { | |
| 142 | + $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset); | |
| 143 | +            if (is_array($backendUsers)) { | |
| 144 | + $users = array_merge($users, $backendUsers); | |
| 145 | + } | |
| 146 | + } | |
| 147 | 147 | |
| 148 | - return $users; | |
| 149 | - } | |
| 148 | + return $users; | |
| 149 | + } | |
| 150 | 150 | |
| 151 | - /** | |
| 152 | - * @param string $gid | |
| 153 | - * @return bool | |
| 154 | - */ | |
| 155 | -	public function createGroup($gid) { | |
| 156 | - return $this->handleRequest( | |
| 157 | - $gid, 'createGroup', array($gid)); | |
| 158 | - } | |
| 151 | + /** | |
| 152 | + * @param string $gid | |
| 153 | + * @return bool | |
| 154 | + */ | |
| 155 | +    public function createGroup($gid) { | |
| 156 | + return $this->handleRequest( | |
| 157 | + $gid, 'createGroup', array($gid)); | |
| 158 | + } | |
| 159 | 159 | |
| 160 | - /** | |
| 161 | - * delete a group | |
| 162 | - * @param string $gid gid of the group to delete | |
| 163 | - * @return bool | |
| 164 | - */ | |
| 165 | -	public function deleteGroup($gid) { | |
| 166 | - return $this->handleRequest( | |
| 167 | - $gid, 'deleteGroup', array($gid)); | |
| 168 | - } | |
| 160 | + /** | |
| 161 | + * delete a group | |
| 162 | + * @param string $gid gid of the group to delete | |
| 163 | + * @return bool | |
| 164 | + */ | |
| 165 | +    public function deleteGroup($gid) { | |
| 166 | + return $this->handleRequest( | |
| 167 | + $gid, 'deleteGroup', array($gid)); | |
| 168 | + } | |
| 169 | 169 | |
| 170 | - /** | |
| 171 | - * Add a user to a group | |
| 172 | - * @param string $uid Name of the user to add to group | |
| 173 | - * @param string $gid Name of the group in which add the user | |
| 174 | - * @return bool | |
| 175 | - * | |
| 176 | - * Adds a user to a group. | |
| 177 | - */ | |
| 178 | -	public function addToGroup($uid, $gid) { | |
| 179 | - return $this->handleRequest( | |
| 180 | - $gid, 'addToGroup', array($uid, $gid)); | |
| 181 | - } | |
| 170 | + /** | |
| 171 | + * Add a user to a group | |
| 172 | + * @param string $uid Name of the user to add to group | |
| 173 | + * @param string $gid Name of the group in which add the user | |
| 174 | + * @return bool | |
| 175 | + * | |
| 176 | + * Adds a user to a group. | |
| 177 | + */ | |
| 178 | +    public function addToGroup($uid, $gid) { | |
| 179 | + return $this->handleRequest( | |
| 180 | + $gid, 'addToGroup', array($uid, $gid)); | |
| 181 | + } | |
| 182 | 182 | |
| 183 | - /** | |
| 184 | - * Removes a user from a group | |
| 185 | - * @param string $uid Name of the user to remove from group | |
| 186 | - * @param string $gid Name of the group from which remove the user | |
| 187 | - * @return bool | |
| 188 | - * | |
| 189 | - * removes the user from a group. | |
| 190 | - */ | |
| 191 | -	public function removeFromGroup($uid, $gid) { | |
| 192 | - return $this->handleRequest( | |
| 193 | - $gid, 'removeFromGroup', array($uid, $gid)); | |
| 194 | - } | |
| 183 | + /** | |
| 184 | + * Removes a user from a group | |
| 185 | + * @param string $uid Name of the user to remove from group | |
| 186 | + * @param string $gid Name of the group from which remove the user | |
| 187 | + * @return bool | |
| 188 | + * | |
| 189 | + * removes the user from a group. | |
| 190 | + */ | |
| 191 | +    public function removeFromGroup($uid, $gid) { | |
| 192 | + return $this->handleRequest( | |
| 193 | + $gid, 'removeFromGroup', array($uid, $gid)); | |
| 194 | + } | |
| 195 | 195 | |
| 196 | - /** | |
| 197 | - * returns the number of users in a group, who match the search term | |
| 198 | - * @param string $gid the internal group name | |
| 199 | - * @param string $search optional, a search string | |
| 200 | - * @return int|bool | |
| 201 | - */ | |
| 202 | -	public function countUsersInGroup($gid, $search = '') { | |
| 203 | - return $this->handleRequest( | |
| 204 | - $gid, 'countUsersInGroup', array($gid, $search)); | |
| 205 | - } | |
| 196 | + /** | |
| 197 | + * returns the number of users in a group, who match the search term | |
| 198 | + * @param string $gid the internal group name | |
| 199 | + * @param string $search optional, a search string | |
| 200 | + * @return int|bool | |
| 201 | + */ | |
| 202 | +    public function countUsersInGroup($gid, $search = '') { | |
| 203 | + return $this->handleRequest( | |
| 204 | + $gid, 'countUsersInGroup', array($gid, $search)); | |
| 205 | + } | |
| 206 | 206 | |
| 207 | - /** | |
| 208 | - * get an array with group details | |
| 209 | - * @param string $gid | |
| 210 | - * @return array|false | |
| 211 | - */ | |
| 212 | -	public function getGroupDetails($gid) { | |
| 213 | - return $this->handleRequest( | |
| 214 | - $gid, 'getGroupDetails', array($gid)); | |
| 215 | - } | |
| 207 | + /** | |
| 208 | + * get an array with group details | |
| 209 | + * @param string $gid | |
| 210 | + * @return array|false | |
| 211 | + */ | |
| 212 | +    public function getGroupDetails($gid) { | |
| 213 | + return $this->handleRequest( | |
| 214 | + $gid, 'getGroupDetails', array($gid)); | |
| 215 | + } | |
| 216 | 216 | |
| 217 | - /** | |
| 218 | - * get a list of all groups | |
| 219 | - * @return string[] with group names | |
| 220 | - * | |
| 221 | - * Returns a list with all groups | |
| 222 | - */ | |
| 223 | -	public function getGroups($search = '', $limit = -1, $offset = 0) { | |
| 224 | - $groups = array(); | |
| 217 | + /** | |
| 218 | + * get a list of all groups | |
| 219 | + * @return string[] with group names | |
| 220 | + * | |
| 221 | + * Returns a list with all groups | |
| 222 | + */ | |
| 223 | +    public function getGroups($search = '', $limit = -1, $offset = 0) { | |
| 224 | + $groups = array(); | |
| 225 | 225 | |
| 226 | -		foreach($this->backends as $backend) { | |
| 227 | - $backendGroups = $backend->getGroups($search, $limit, $offset); | |
| 228 | -			if (is_array($backendGroups)) { | |
| 229 | - $groups = array_merge($groups, $backendGroups); | |
| 230 | - } | |
| 231 | - } | |
| 226 | +        foreach($this->backends as $backend) { | |
| 227 | + $backendGroups = $backend->getGroups($search, $limit, $offset); | |
| 228 | +            if (is_array($backendGroups)) { | |
| 229 | + $groups = array_merge($groups, $backendGroups); | |
| 230 | + } | |
| 231 | + } | |
| 232 | 232 | |
| 233 | - return $groups; | |
| 234 | - } | |
| 233 | + return $groups; | |
| 234 | + } | |
| 235 | 235 | |
| 236 | - /** | |
| 237 | - * check if a group exists | |
| 238 | - * @param string $gid | |
| 239 | - * @return bool | |
| 240 | - */ | |
| 241 | -	public function groupExists($gid) { | |
| 242 | - return $this->handleRequest($gid, 'groupExists', array($gid)); | |
| 243 | - } | |
| 236 | + /** | |
| 237 | + * check if a group exists | |
| 238 | + * @param string $gid | |
| 239 | + * @return bool | |
| 240 | + */ | |
| 241 | +    public function groupExists($gid) { | |
| 242 | + return $this->handleRequest($gid, 'groupExists', array($gid)); | |
| 243 | + } | |
| 244 | 244 | |
| 245 | - /** | |
| 246 | - * Check if backend implements actions | |
| 247 | - * @param int $actions bitwise-or'ed actions | |
| 248 | - * @return boolean | |
| 249 | - * | |
| 250 | - * Returns the supported actions as int to be | |
| 251 | - * compared with \OCP\GroupInterface::CREATE_GROUP etc. | |
| 252 | - */ | |
| 253 | -	public function implementsActions($actions) { | |
| 254 | - //it's the same across all our user backends obviously | |
| 255 | - return $this->refBackend->implementsActions($actions); | |
| 256 | - } | |
| 245 | + /** | |
| 246 | + * Check if backend implements actions | |
| 247 | + * @param int $actions bitwise-or'ed actions | |
| 248 | + * @return boolean | |
| 249 | + * | |
| 250 | + * Returns the supported actions as int to be | |
| 251 | + * compared with \OCP\GroupInterface::CREATE_GROUP etc. | |
| 252 | + */ | |
| 253 | +    public function implementsActions($actions) { | |
| 254 | + //it's the same across all our user backends obviously | |
| 255 | + return $this->refBackend->implementsActions($actions); | |
| 256 | + } | |
| 257 | 257 | |
| 258 | - /** | |
| 259 | - * Return access for LDAP interaction. | |
| 260 | - * @param string $gid | |
| 261 | - * @return Access instance of Access for LDAP interaction | |
| 262 | - */ | |
| 263 | -	public function getLDAPAccess($gid) { | |
| 264 | - return $this->handleRequest($gid, 'getLDAPAccess', [$gid]); | |
| 265 | - } | |
| 258 | + /** | |
| 259 | + * Return access for LDAP interaction. | |
| 260 | + * @param string $gid | |
| 261 | + * @return Access instance of Access for LDAP interaction | |
| 262 | + */ | |
| 263 | +    public function getLDAPAccess($gid) { | |
| 264 | + return $this->handleRequest($gid, 'getLDAPAccess', [$gid]); | |
| 265 | + } | |
| 266 | 266 | |
| 267 | - /** | |
| 268 | - * Return a new LDAP connection for the specified group. | |
| 269 | - * The connection needs to be closed manually. | |
| 270 | - * @param string $gid | |
| 271 | - * @return resource of the LDAP connection | |
| 272 | - */ | |
| 273 | -	public function getNewLDAPConnection($gid) { | |
| 274 | - return $this->handleRequest($gid, 'getNewLDAPConnection', array($gid)); | |
| 275 | - } | |
| 267 | + /** | |
| 268 | + * Return a new LDAP connection for the specified group. | |
| 269 | + * The connection needs to be closed manually. | |
| 270 | + * @param string $gid | |
| 271 | + * @return resource of the LDAP connection | |
| 272 | + */ | |
| 273 | +    public function getNewLDAPConnection($gid) { | |
| 274 | + return $this->handleRequest($gid, 'getNewLDAPConnection', array($gid)); | |
| 275 | + } | |
| 276 | 276 | |
| 277 | -	public function getDisplayName(string $gid): string { | |
| 278 | - return $this->handleRequest($gid, 'getDisplayName', [$gid]); | |
| 279 | - } | |
| 277 | +    public function getDisplayName(string $gid): string { | |
| 278 | + return $this->handleRequest($gid, 'getDisplayName', [$gid]); | |
| 279 | + } | |
| 280 | 280 | } | 
| @@ -68,620 +68,620 @@ | ||
| 68 | 68 | * @property string ldapGroupDisplayName | 
| 69 | 69 | */ | 
| 70 | 70 |  class Connection extends LDAPUtility { | 
| 71 | - private $ldapConnectionRes = null; | |
| 72 | - private $configPrefix; | |
| 73 | - private $configID; | |
| 74 | - private $configured = false; | |
| 75 | - //whether connection should be kept on __destruct | |
| 76 | - private $dontDestruct = false; | |
| 77 | - | |
| 78 | - /** | |
| 79 | - * @var bool runtime flag that indicates whether supported primary groups are available | |
| 80 | - */ | |
| 81 | - public $hasPrimaryGroups = true; | |
| 82 | - | |
| 83 | - /** | |
| 84 | - * @var bool runtime flag that indicates whether supported POSIX gidNumber are available | |
| 85 | - */ | |
| 86 | - public $hasGidNumber = true; | |
| 87 | - | |
| 88 | - //cache handler | |
| 89 | - protected $cache; | |
| 90 | - | |
| 91 | - /** @var Configuration settings handler **/ | |
| 92 | - protected $configuration; | |
| 93 | - | |
| 94 | - protected $doNotValidate = false; | |
| 95 | - | |
| 96 | - protected $ignoreValidation = false; | |
| 97 | - | |
| 98 | - protected $bindResult = []; | |
| 99 | - | |
| 100 | - /** | |
| 101 | - * Constructor | |
| 102 | - * @param ILDAPWrapper $ldap | |
| 103 | - * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) | |
| 104 | - * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections | |
| 105 | - */ | |
| 106 | -	public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { | |
| 107 | - parent::__construct($ldap); | |
| 108 | - $this->configPrefix = $configPrefix; | |
| 109 | - $this->configID = $configID; | |
| 110 | - $this->configuration = new Configuration($configPrefix, | |
| 111 | - !is_null($configID)); | |
| 112 | - $memcache = \OC::$server->getMemCacheFactory(); | |
| 113 | -		if($memcache->isAvailable()) { | |
| 114 | - $this->cache = $memcache->createDistributed(); | |
| 115 | - } | |
| 116 | - $helper = new Helper(\OC::$server->getConfig()); | |
| 117 | - $this->doNotValidate = !in_array($this->configPrefix, | |
| 118 | - $helper->getServerConfigurationPrefixes()); | |
| 119 | - } | |
| 120 | - | |
| 121 | -	public function __destruct() { | |
| 122 | -		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { | |
| 123 | - @$this->ldap->unbind($this->ldapConnectionRes); | |
| 124 | - $this->bindResult = []; | |
| 125 | - } | |
| 126 | - } | |
| 127 | - | |
| 128 | - /** | |
| 129 | - * defines behaviour when the instance is cloned | |
| 130 | - */ | |
| 131 | -	public function __clone() { | |
| 132 | - $this->configuration = new Configuration($this->configPrefix, | |
| 133 | - !is_null($this->configID)); | |
| 134 | -		if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { | |
| 135 | - $this->bindResult = []; | |
| 136 | - } | |
| 137 | - $this->ldapConnectionRes = null; | |
| 138 | - $this->dontDestruct = true; | |
| 139 | - } | |
| 140 | - | |
| 141 | - /** | |
| 142 | - * @param string $name | |
| 143 | - * @return bool|mixed | |
| 144 | - */ | |
| 145 | -	public function __get($name) { | |
| 146 | -		if(!$this->configured) { | |
| 147 | - $this->readConfiguration(); | |
| 148 | - } | |
| 149 | - | |
| 150 | - return $this->configuration->$name; | |
| 151 | - } | |
| 152 | - | |
| 153 | - /** | |
| 154 | - * @param string $name | |
| 155 | - * @param mixed $value | |
| 156 | - */ | |
| 157 | -	public function __set($name, $value) { | |
| 158 | - $this->doNotValidate = false; | |
| 159 | - $before = $this->configuration->$name; | |
| 160 | - $this->configuration->$name = $value; | |
| 161 | - $after = $this->configuration->$name; | |
| 162 | -		if($before !== $after) { | |
| 163 | -			if ($this->configID !== '' && $this->configID !== null) { | |
| 164 | - $this->configuration->saveConfiguration(); | |
| 165 | - } | |
| 166 | - $this->validateConfiguration(); | |
| 167 | - } | |
| 168 | - } | |
| 169 | - | |
| 170 | - /** | |
| 171 | - * @param string $rule | |
| 172 | - * @return array | |
| 173 | - * @throws \RuntimeException | |
| 174 | - */ | |
| 175 | -	public function resolveRule($rule) { | |
| 176 | - return $this->configuration->resolveRule($rule); | |
| 177 | - } | |
| 178 | - | |
| 179 | - /** | |
| 180 | - * sets whether the result of the configuration validation shall | |
| 181 | - * be ignored when establishing the connection. Used by the Wizard | |
| 182 | - * in early configuration state. | |
| 183 | - * @param bool $state | |
| 184 | - */ | |
| 185 | -	public function setIgnoreValidation($state) { | |
| 186 | - $this->ignoreValidation = (bool)$state; | |
| 187 | - } | |
| 188 | - | |
| 189 | - /** | |
| 190 | - * initializes the LDAP backend | |
| 191 | - * @param bool $force read the config settings no matter what | |
| 192 | - */ | |
| 193 | -	public function init($force = false) { | |
| 194 | - $this->readConfiguration($force); | |
| 195 | - $this->establishConnection(); | |
| 196 | - } | |
| 197 | - | |
| 198 | - /** | |
| 199 | - * Returns the LDAP handler | |
| 200 | - */ | |
| 201 | -	public function getConnectionResource() { | |
| 202 | -		if(!$this->ldapConnectionRes) { | |
| 203 | - $this->init(); | |
| 204 | -		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) { | |
| 205 | - $this->ldapConnectionRes = null; | |
| 206 | - $this->establishConnection(); | |
| 207 | - } | |
| 208 | -		if(is_null($this->ldapConnectionRes)) { | |
| 209 | -			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); | |
| 210 | -			throw new ServerNotAvailableException('Connection to LDAP server could not be established'); | |
| 211 | - } | |
| 212 | - return $this->ldapConnectionRes; | |
| 213 | - } | |
| 214 | - | |
| 215 | - /** | |
| 216 | - * resets the connection resource | |
| 217 | - */ | |
| 218 | -	public function resetConnectionResource() { | |
| 219 | -		if(!is_null($this->ldapConnectionRes)) { | |
| 220 | - @$this->ldap->unbind($this->ldapConnectionRes); | |
| 221 | - $this->ldapConnectionRes = null; | |
| 222 | - $this->bindResult = []; | |
| 223 | - } | |
| 224 | - } | |
| 225 | - | |
| 226 | - /** | |
| 227 | - * @param string|null $key | |
| 228 | - * @return string | |
| 229 | - */ | |
| 230 | -	private function getCacheKey($key) { | |
| 231 | - $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; | |
| 232 | -		if(is_null($key)) { | |
| 233 | - return $prefix; | |
| 234 | - } | |
| 235 | -		return $prefix.hash('sha256', $key); | |
| 236 | - } | |
| 237 | - | |
| 238 | - /** | |
| 239 | - * @param string $key | |
| 240 | - * @return mixed|null | |
| 241 | - */ | |
| 242 | -	public function getFromCache($key) { | |
| 243 | -		if(!$this->configured) { | |
| 244 | - $this->readConfiguration(); | |
| 245 | - } | |
| 246 | -		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { | |
| 247 | - return null; | |
| 248 | - } | |
| 249 | - $key = $this->getCacheKey($key); | |
| 250 | - | |
| 251 | - return json_decode(base64_decode($this->cache->get($key)), true); | |
| 252 | - } | |
| 253 | - | |
| 254 | - /** | |
| 255 | - * @param string $key | |
| 256 | - * @param mixed $value | |
| 257 | - * | |
| 258 | - * @return string | |
| 259 | - */ | |
| 260 | -	public function writeToCache($key, $value) { | |
| 261 | -		if(!$this->configured) { | |
| 262 | - $this->readConfiguration(); | |
| 263 | - } | |
| 264 | - if(is_null($this->cache) | |
| 265 | - || !$this->configuration->ldapCacheTTL | |
| 266 | -			|| !$this->configuration->ldapConfigurationActive) { | |
| 267 | - return null; | |
| 268 | - } | |
| 269 | - $key = $this->getCacheKey($key); | |
| 270 | - $value = base64_encode(json_encode($value)); | |
| 271 | - $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); | |
| 272 | - } | |
| 273 | - | |
| 274 | -	public function clearCache() { | |
| 275 | -		if(!is_null($this->cache)) { | |
| 276 | - $this->cache->clear($this->getCacheKey(null)); | |
| 277 | - } | |
| 278 | - } | |
| 279 | - | |
| 280 | - /** | |
| 281 | - * Caches the general LDAP configuration. | |
| 282 | - * @param bool $force optional. true, if the re-read should be forced. defaults | |
| 283 | - * to false. | |
| 284 | - * @return null | |
| 285 | - */ | |
| 286 | -	private function readConfiguration($force = false) { | |
| 287 | -		if((!$this->configured || $force) && !is_null($this->configID)) { | |
| 288 | - $this->configuration->readConfiguration(); | |
| 289 | - $this->configured = $this->validateConfiguration(); | |
| 290 | - } | |
| 291 | - } | |
| 292 | - | |
| 293 | - /** | |
| 294 | - * set LDAP configuration with values delivered by an array, not read from configuration | |
| 295 | - * @param array $config array that holds the config parameters in an associated array | |
| 296 | - * @param array &$setParameters optional; array where the set fields will be given to | |
| 297 | - * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters | |
| 298 | - */ | |
| 299 | -	public function setConfiguration($config, &$setParameters = null) { | |
| 300 | -		if(is_null($setParameters)) { | |
| 301 | - $setParameters = array(); | |
| 302 | - } | |
| 303 | - $this->doNotValidate = false; | |
| 304 | - $this->configuration->setConfiguration($config, $setParameters); | |
| 305 | -		if(count($setParameters) > 0) { | |
| 306 | - $this->configured = $this->validateConfiguration(); | |
| 307 | - } | |
| 308 | - | |
| 309 | - | |
| 310 | - return $this->configured; | |
| 311 | - } | |
| 312 | - | |
| 313 | - /** | |
| 314 | - * saves the current Configuration in the database and empties the | |
| 315 | - * cache | |
| 316 | - * @return null | |
| 317 | - */ | |
| 318 | -	public function saveConfiguration() { | |
| 319 | - $this->configuration->saveConfiguration(); | |
| 320 | - $this->clearCache(); | |
| 321 | - } | |
| 322 | - | |
| 323 | - /** | |
| 324 | - * get the current LDAP configuration | |
| 325 | - * @return array | |
| 326 | - */ | |
| 327 | -	public function getConfiguration() { | |
| 328 | - $this->readConfiguration(); | |
| 329 | - $config = $this->configuration->getConfiguration(); | |
| 330 | - $cta = $this->configuration->getConfigTranslationArray(); | |
| 331 | - $result = array(); | |
| 332 | -		foreach($cta as $dbkey => $configkey) { | |
| 333 | -			switch($configkey) { | |
| 334 | - case 'homeFolderNamingRule': | |
| 335 | -					if(strpos($config[$configkey], 'attr:') === 0) { | |
| 336 | - $result[$dbkey] = substr($config[$configkey], 5); | |
| 337 | -					} else { | |
| 338 | - $result[$dbkey] = ''; | |
| 339 | - } | |
| 340 | - break; | |
| 341 | - case 'ldapBase': | |
| 342 | - case 'ldapBaseUsers': | |
| 343 | - case 'ldapBaseGroups': | |
| 344 | - case 'ldapAttributesForUserSearch': | |
| 345 | - case 'ldapAttributesForGroupSearch': | |
| 346 | -					if(is_array($config[$configkey])) { | |
| 347 | -						$result[$dbkey] = implode("\n", $config[$configkey]); | |
| 348 | - break; | |
| 349 | - } //else follows default | |
| 350 | - default: | |
| 351 | - $result[$dbkey] = $config[$configkey]; | |
| 352 | - } | |
| 353 | - } | |
| 354 | - return $result; | |
| 355 | - } | |
| 356 | - | |
| 357 | -	private function doSoftValidation() { | |
| 358 | - //if User or Group Base are not set, take over Base DN setting | |
| 359 | -		foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) { | |
| 360 | - $val = $this->configuration->$keyBase; | |
| 361 | -			if(empty($val)) { | |
| 362 | - $this->configuration->$keyBase = $this->configuration->ldapBase; | |
| 363 | - } | |
| 364 | - } | |
| 365 | - | |
| 366 | -		foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute', | |
| 367 | - 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute') | |
| 368 | -				as $expertSetting => $effectiveSetting) { | |
| 369 | - $uuidOverride = $this->configuration->$expertSetting; | |
| 370 | -			if(!empty($uuidOverride)) { | |
| 371 | - $this->configuration->$effectiveSetting = $uuidOverride; | |
| 372 | -			} else { | |
| 373 | - $uuidAttributes = Access::UUID_ATTRIBUTES; | |
| 374 | - array_unshift($uuidAttributes, 'auto'); | |
| 375 | - if(!in_array($this->configuration->$effectiveSetting, | |
| 376 | - $uuidAttributes) | |
| 377 | -					&& (!is_null($this->configID))) { | |
| 378 | - $this->configuration->$effectiveSetting = 'auto'; | |
| 379 | - $this->configuration->saveConfiguration(); | |
| 380 | -					\OCP\Util::writeLog('user_ldap', | |
| 381 | - 'Illegal value for the '. | |
| 382 | - $effectiveSetting.', '.'reset to '. | |
| 383 | - 'autodetect.', ILogger::INFO); | |
| 384 | - } | |
| 385 | - | |
| 386 | - } | |
| 387 | - } | |
| 388 | - | |
| 389 | - $backupPort = (int)$this->configuration->ldapBackupPort; | |
| 390 | -		if ($backupPort <= 0) { | |
| 391 | - $this->configuration->backupPort = $this->configuration->ldapPort; | |
| 392 | - } | |
| 393 | - | |
| 394 | - //make sure empty search attributes are saved as simple, empty array | |
| 395 | -		$saKeys = array('ldapAttributesForUserSearch', | |
| 396 | - 'ldapAttributesForGroupSearch'); | |
| 397 | -		foreach($saKeys as $key) { | |
| 398 | - $val = $this->configuration->$key; | |
| 399 | -			if(is_array($val) && count($val) === 1 && empty($val[0])) { | |
| 400 | - $this->configuration->$key = array(); | |
| 401 | - } | |
| 402 | - } | |
| 403 | - | |
| 404 | - if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) | |
| 405 | -			&& $this->configuration->ldapTLS) { | |
| 406 | - $this->configuration->ldapTLS = false; | |
| 407 | - \OCP\Util::writeLog( | |
| 408 | - 'user_ldap', | |
| 409 | - 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.', | |
| 410 | - ILogger::INFO | |
| 411 | - ); | |
| 412 | - } | |
| 413 | - } | |
| 414 | - | |
| 415 | - /** | |
| 416 | - * @return bool | |
| 417 | - */ | |
| 418 | -	private function doCriticalValidation() { | |
| 419 | - $configurationOK = true; | |
| 420 | - $errorStr = 'Configuration Error (prefix '. | |
| 421 | - (string)$this->configPrefix .'): '; | |
| 422 | - | |
| 423 | - //options that shall not be empty | |
| 424 | -		$options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName', | |
| 425 | - 'ldapGroupDisplayName', 'ldapLoginFilter'); | |
| 426 | -		foreach($options as $key) { | |
| 427 | - $val = $this->configuration->$key; | |
| 428 | -			if(empty($val)) { | |
| 429 | -				switch($key) { | |
| 430 | - case 'ldapHost': | |
| 431 | - $subj = 'LDAP Host'; | |
| 432 | - break; | |
| 433 | - case 'ldapPort': | |
| 434 | - $subj = 'LDAP Port'; | |
| 435 | - break; | |
| 436 | - case 'ldapUserDisplayName': | |
| 437 | - $subj = 'LDAP User Display Name'; | |
| 438 | - break; | |
| 439 | - case 'ldapGroupDisplayName': | |
| 440 | - $subj = 'LDAP Group Display Name'; | |
| 441 | - break; | |
| 442 | - case 'ldapLoginFilter': | |
| 443 | - $subj = 'LDAP Login Filter'; | |
| 444 | - break; | |
| 445 | - default: | |
| 446 | - $subj = $key; | |
| 447 | - break; | |
| 448 | - } | |
| 449 | - $configurationOK = false; | |
| 450 | - \OCP\Util::writeLog( | |
| 451 | - 'user_ldap', | |
| 452 | - $errorStr.'No '.$subj.' given!', | |
| 453 | - ILogger::WARN | |
| 454 | - ); | |
| 455 | - } | |
| 456 | - } | |
| 457 | - | |
| 458 | - //combinations | |
| 459 | - $agent = $this->configuration->ldapAgentName; | |
| 460 | - $pwd = $this->configuration->ldapAgentPassword; | |
| 461 | - if ( | |
| 462 | - ($agent === '' && $pwd !== '') | |
| 463 | - || ($agent !== '' && $pwd === '') | |
| 464 | -		) { | |
| 465 | - \OCP\Util::writeLog( | |
| 466 | - 'user_ldap', | |
| 467 | - $errorStr.'either no password is given for the user ' . | |
| 468 | - 'agent or a password is given, but not an LDAP agent.', | |
| 469 | - ILogger::WARN); | |
| 470 | - $configurationOK = false; | |
| 471 | - } | |
| 472 | - | |
| 473 | - $base = $this->configuration->ldapBase; | |
| 474 | - $baseUsers = $this->configuration->ldapBaseUsers; | |
| 475 | - $baseGroups = $this->configuration->ldapBaseGroups; | |
| 476 | - | |
| 477 | -		if(empty($base) && empty($baseUsers) && empty($baseGroups)) { | |
| 478 | - \OCP\Util::writeLog( | |
| 479 | - 'user_ldap', | |
| 480 | - $errorStr.'Not a single Base DN given.', | |
| 481 | - ILogger::WARN | |
| 482 | - ); | |
| 483 | - $configurationOK = false; | |
| 484 | - } | |
| 485 | - | |
| 486 | - if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') | |
| 487 | -		   === false) { | |
| 488 | - \OCP\Util::writeLog( | |
| 489 | - 'user_ldap', | |
| 490 | - $errorStr.'login filter does not contain %uid place holder.', | |
| 491 | - ILogger::WARN | |
| 492 | - ); | |
| 493 | - $configurationOK = false; | |
| 494 | - } | |
| 495 | - | |
| 496 | - return $configurationOK; | |
| 497 | - } | |
| 498 | - | |
| 499 | - /** | |
| 500 | - * Validates the user specified configuration | |
| 501 | - * @return bool true if configuration seems OK, false otherwise | |
| 502 | - */ | |
| 503 | -	private function validateConfiguration() { | |
| 504 | - | |
| 505 | -		if($this->doNotValidate) { | |
| 506 | - //don't do a validation if it is a new configuration with pure | |
| 507 | - //default values. Will be allowed on changes via __set or | |
| 508 | - //setConfiguration | |
| 509 | - return false; | |
| 510 | - } | |
| 511 | - | |
| 512 | - // first step: "soft" checks: settings that are not really | |
| 513 | - // necessary, but advisable. If left empty, give an info message | |
| 514 | - $this->doSoftValidation(); | |
| 515 | - | |
| 516 | - //second step: critical checks. If left empty or filled wrong, mark as | |
| 517 | - //not configured and give a warning. | |
| 518 | - return $this->doCriticalValidation(); | |
| 519 | - } | |
| 520 | - | |
| 521 | - | |
| 522 | - /** | |
| 523 | - * Connects and Binds to LDAP | |
| 524 | - * | |
| 525 | - * @throws ServerNotAvailableException | |
| 526 | - */ | |
| 527 | -	private function establishConnection() { | |
| 528 | -		if(!$this->configuration->ldapConfigurationActive) { | |
| 529 | - return null; | |
| 530 | - } | |
| 531 | - static $phpLDAPinstalled = true; | |
| 532 | -		if(!$phpLDAPinstalled) { | |
| 533 | - return false; | |
| 534 | - } | |
| 535 | -		if(!$this->ignoreValidation && !$this->configured) { | |
| 536 | - \OCP\Util::writeLog( | |
| 537 | - 'user_ldap', | |
| 538 | - 'Configuration is invalid, cannot connect', | |
| 539 | - ILogger::WARN | |
| 540 | - ); | |
| 541 | - return false; | |
| 542 | - } | |
| 543 | -		if(!$this->ldapConnectionRes) { | |
| 544 | -			if(!$this->ldap->areLDAPFunctionsAvailable()) { | |
| 545 | - $phpLDAPinstalled = false; | |
| 546 | - \OCP\Util::writeLog( | |
| 547 | - 'user_ldap', | |
| 548 | - 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', | |
| 549 | - ILogger::ERROR | |
| 550 | - ); | |
| 551 | - | |
| 552 | - return false; | |
| 553 | - } | |
| 554 | -			if($this->configuration->turnOffCertCheck) { | |
| 555 | -				if(putenv('LDAPTLS_REQCERT=never')) { | |
| 556 | -					\OCP\Util::writeLog('user_ldap', | |
| 557 | - 'Turned off SSL certificate validation successfully.', | |
| 558 | - ILogger::DEBUG); | |
| 559 | -				} else { | |
| 560 | - \OCP\Util::writeLog( | |
| 561 | - 'user_ldap', | |
| 562 | - 'Could not turn off SSL certificate validation.', | |
| 563 | - ILogger::WARN | |
| 564 | - ); | |
| 565 | - } | |
| 566 | - } | |
| 567 | - | |
| 568 | - $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer | |
| 569 | -				|| $this->getFromCache('overrideMainServer')); | |
| 570 | - $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); | |
| 571 | - $bindStatus = false; | |
| 572 | -			try { | |
| 573 | -				if (!$isOverrideMainServer) { | |
| 574 | - $this->doConnect($this->configuration->ldapHost, | |
| 575 | - $this->configuration->ldapPort); | |
| 576 | - return $this->bind(); | |
| 577 | - } | |
| 578 | -			} catch (ServerNotAvailableException $e) { | |
| 579 | -				if(!$isBackupHost) { | |
| 580 | - throw $e; | |
| 581 | - } | |
| 582 | - } | |
| 583 | - | |
| 584 | - //if LDAP server is not reachable, try the Backup (Replica!) Server | |
| 585 | -			if($isBackupHost || $isOverrideMainServer) { | |
| 586 | - $this->doConnect($this->configuration->ldapBackupHost, | |
| 587 | - $this->configuration->ldapBackupPort); | |
| 588 | - $this->bindResult = []; | |
| 589 | - $bindStatus = $this->bind(); | |
| 590 | - $error = $this->ldap->isResource($this->ldapConnectionRes) ? | |
| 591 | - $this->ldap->errno($this->ldapConnectionRes) : -1; | |
| 592 | -				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { | |
| 593 | - //when bind to backup server succeeded and failed to main server, | |
| 594 | - //skip contacting him until next cache refresh | |
| 595 | -					$this->writeToCache('overrideMainServer', true); | |
| 596 | - } | |
| 597 | - } | |
| 598 | - | |
| 599 | - return $bindStatus; | |
| 600 | - } | |
| 601 | - return null; | |
| 602 | - } | |
| 603 | - | |
| 604 | - /** | |
| 605 | - * @param string $host | |
| 606 | - * @param string $port | |
| 607 | - * @return bool | |
| 608 | - * @throws \OC\ServerNotAvailableException | |
| 609 | - */ | |
| 610 | -	private function doConnect($host, $port) { | |
| 611 | -		if ($host === '') { | |
| 612 | - return false; | |
| 613 | - } | |
| 614 | - | |
| 615 | - $this->ldapConnectionRes = $this->ldap->connect($host, $port); | |
| 616 | - | |
| 617 | -		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { | |
| 618 | -			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); | |
| 619 | - } | |
| 620 | - | |
| 621 | -		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { | |
| 622 | -			throw new ServerNotAvailableException('Could not disable LDAP referrals.'); | |
| 623 | - } | |
| 624 | - | |
| 625 | -		if($this->configuration->ldapTLS) { | |
| 626 | -			if(!$this->ldap->startTls($this->ldapConnectionRes)) { | |
| 627 | -				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); | |
| 628 | - } | |
| 629 | - } | |
| 630 | - | |
| 631 | - return true; | |
| 632 | - } | |
| 633 | - | |
| 634 | - /** | |
| 635 | - * Binds to LDAP | |
| 636 | - */ | |
| 637 | -	public function bind() { | |
| 638 | -		if(!$this->configuration->ldapConfigurationActive) { | |
| 639 | - return false; | |
| 640 | - } | |
| 641 | - $cr = $this->ldapConnectionRes; | |
| 642 | -		if(!$this->ldap->isResource($cr)) { | |
| 643 | - $cr = $this->getConnectionResource(); | |
| 644 | - } | |
| 645 | - | |
| 646 | - if( | |
| 647 | - count($this->bindResult) !== 0 | |
| 648 | - && $this->bindResult['dn'] === $this->configuration->ldapAgentName | |
| 649 | - && \OC::$server->getHasher()->verify( | |
| 650 | - $this->configPrefix . $this->configuration->ldapAgentPassword, | |
| 651 | - $this->bindResult['hash'] | |
| 652 | - ) | |
| 653 | -		) { | |
| 654 | - // don't attempt to bind again with the same data as before | |
| 655 | - // bind might have been invoked via getConnectionResource(), | |
| 656 | - // but we need results specifically for e.g. user login | |
| 657 | - return $this->bindResult['result']; | |
| 658 | - } | |
| 659 | - | |
| 660 | - $ldapLogin = @$this->ldap->bind($cr, | |
| 661 | - $this->configuration->ldapAgentName, | |
| 662 | - $this->configuration->ldapAgentPassword); | |
| 663 | - | |
| 664 | - $this->bindResult = [ | |
| 665 | - 'dn' => $this->configuration->ldapAgentName, | |
| 666 | - 'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword), | |
| 667 | - 'result' => $ldapLogin, | |
| 668 | - ]; | |
| 669 | - | |
| 670 | -		if(!$ldapLogin) { | |
| 671 | - $errno = $this->ldap->errno($cr); | |
| 672 | - | |
| 673 | -			\OCP\Util::writeLog('user_ldap', | |
| 674 | - 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), | |
| 675 | - ILogger::WARN); | |
| 676 | - | |
| 677 | - // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS | |
| 678 | -			if($errno !== 0x00 && $errno !== 0x31) { | |
| 679 | - $this->ldapConnectionRes = null; | |
| 680 | - } | |
| 681 | - | |
| 682 | - return false; | |
| 683 | - } | |
| 684 | - return true; | |
| 685 | - } | |
| 71 | + private $ldapConnectionRes = null; | |
| 72 | + private $configPrefix; | |
| 73 | + private $configID; | |
| 74 | + private $configured = false; | |
| 75 | + //whether connection should be kept on __destruct | |
| 76 | + private $dontDestruct = false; | |
| 77 | + | |
| 78 | + /** | |
| 79 | + * @var bool runtime flag that indicates whether supported primary groups are available | |
| 80 | + */ | |
| 81 | + public $hasPrimaryGroups = true; | |
| 82 | + | |
| 83 | + /** | |
| 84 | + * @var bool runtime flag that indicates whether supported POSIX gidNumber are available | |
| 85 | + */ | |
| 86 | + public $hasGidNumber = true; | |
| 87 | + | |
| 88 | + //cache handler | |
| 89 | + protected $cache; | |
| 90 | + | |
| 91 | + /** @var Configuration settings handler **/ | |
| 92 | + protected $configuration; | |
| 93 | + | |
| 94 | + protected $doNotValidate = false; | |
| 95 | + | |
| 96 | + protected $ignoreValidation = false; | |
| 97 | + | |
| 98 | + protected $bindResult = []; | |
| 99 | + | |
| 100 | + /** | |
| 101 | + * Constructor | |
| 102 | + * @param ILDAPWrapper $ldap | |
| 103 | + * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) | |
| 104 | + * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections | |
| 105 | + */ | |
| 106 | +    public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { | |
| 107 | + parent::__construct($ldap); | |
| 108 | + $this->configPrefix = $configPrefix; | |
| 109 | + $this->configID = $configID; | |
| 110 | + $this->configuration = new Configuration($configPrefix, | |
| 111 | + !is_null($configID)); | |
| 112 | + $memcache = \OC::$server->getMemCacheFactory(); | |
| 113 | +        if($memcache->isAvailable()) { | |
| 114 | + $this->cache = $memcache->createDistributed(); | |
| 115 | + } | |
| 116 | + $helper = new Helper(\OC::$server->getConfig()); | |
| 117 | + $this->doNotValidate = !in_array($this->configPrefix, | |
| 118 | + $helper->getServerConfigurationPrefixes()); | |
| 119 | + } | |
| 120 | + | |
| 121 | +    public function __destruct() { | |
| 122 | +        if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { | |
| 123 | + @$this->ldap->unbind($this->ldapConnectionRes); | |
| 124 | + $this->bindResult = []; | |
| 125 | + } | |
| 126 | + } | |
| 127 | + | |
| 128 | + /** | |
| 129 | + * defines behaviour when the instance is cloned | |
| 130 | + */ | |
| 131 | +    public function __clone() { | |
| 132 | + $this->configuration = new Configuration($this->configPrefix, | |
| 133 | + !is_null($this->configID)); | |
| 134 | +        if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) { | |
| 135 | + $this->bindResult = []; | |
| 136 | + } | |
| 137 | + $this->ldapConnectionRes = null; | |
| 138 | + $this->dontDestruct = true; | |
| 139 | + } | |
| 140 | + | |
| 141 | + /** | |
| 142 | + * @param string $name | |
| 143 | + * @return bool|mixed | |
| 144 | + */ | |
| 145 | +    public function __get($name) { | |
| 146 | +        if(!$this->configured) { | |
| 147 | + $this->readConfiguration(); | |
| 148 | + } | |
| 149 | + | |
| 150 | + return $this->configuration->$name; | |
| 151 | + } | |
| 152 | + | |
| 153 | + /** | |
| 154 | + * @param string $name | |
| 155 | + * @param mixed $value | |
| 156 | + */ | |
| 157 | +    public function __set($name, $value) { | |
| 158 | + $this->doNotValidate = false; | |
| 159 | + $before = $this->configuration->$name; | |
| 160 | + $this->configuration->$name = $value; | |
| 161 | + $after = $this->configuration->$name; | |
| 162 | +        if($before !== $after) { | |
| 163 | +            if ($this->configID !== '' && $this->configID !== null) { | |
| 164 | + $this->configuration->saveConfiguration(); | |
| 165 | + } | |
| 166 | + $this->validateConfiguration(); | |
| 167 | + } | |
| 168 | + } | |
| 169 | + | |
| 170 | + /** | |
| 171 | + * @param string $rule | |
| 172 | + * @return array | |
| 173 | + * @throws \RuntimeException | |
| 174 | + */ | |
| 175 | +    public function resolveRule($rule) { | |
| 176 | + return $this->configuration->resolveRule($rule); | |
| 177 | + } | |
| 178 | + | |
| 179 | + /** | |
| 180 | + * sets whether the result of the configuration validation shall | |
| 181 | + * be ignored when establishing the connection. Used by the Wizard | |
| 182 | + * in early configuration state. | |
| 183 | + * @param bool $state | |
| 184 | + */ | |
| 185 | +    public function setIgnoreValidation($state) { | |
| 186 | + $this->ignoreValidation = (bool)$state; | |
| 187 | + } | |
| 188 | + | |
| 189 | + /** | |
| 190 | + * initializes the LDAP backend | |
| 191 | + * @param bool $force read the config settings no matter what | |
| 192 | + */ | |
| 193 | +    public function init($force = false) { | |
| 194 | + $this->readConfiguration($force); | |
| 195 | + $this->establishConnection(); | |
| 196 | + } | |
| 197 | + | |
| 198 | + /** | |
| 199 | + * Returns the LDAP handler | |
| 200 | + */ | |
| 201 | +    public function getConnectionResource() { | |
| 202 | +        if(!$this->ldapConnectionRes) { | |
| 203 | + $this->init(); | |
| 204 | +        } else if(!$this->ldap->isResource($this->ldapConnectionRes)) { | |
| 205 | + $this->ldapConnectionRes = null; | |
| 206 | + $this->establishConnection(); | |
| 207 | + } | |
| 208 | +        if(is_null($this->ldapConnectionRes)) { | |
| 209 | +            \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR); | |
| 210 | +            throw new ServerNotAvailableException('Connection to LDAP server could not be established'); | |
| 211 | + } | |
| 212 | + return $this->ldapConnectionRes; | |
| 213 | + } | |
| 214 | + | |
| 215 | + /** | |
| 216 | + * resets the connection resource | |
| 217 | + */ | |
| 218 | +    public function resetConnectionResource() { | |
| 219 | +        if(!is_null($this->ldapConnectionRes)) { | |
| 220 | + @$this->ldap->unbind($this->ldapConnectionRes); | |
| 221 | + $this->ldapConnectionRes = null; | |
| 222 | + $this->bindResult = []; | |
| 223 | + } | |
| 224 | + } | |
| 225 | + | |
| 226 | + /** | |
| 227 | + * @param string|null $key | |
| 228 | + * @return string | |
| 229 | + */ | |
| 230 | +    private function getCacheKey($key) { | |
| 231 | + $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; | |
| 232 | +        if(is_null($key)) { | |
| 233 | + return $prefix; | |
| 234 | + } | |
| 235 | +        return $prefix.hash('sha256', $key); | |
| 236 | + } | |
| 237 | + | |
| 238 | + /** | |
| 239 | + * @param string $key | |
| 240 | + * @return mixed|null | |
| 241 | + */ | |
| 242 | +    public function getFromCache($key) { | |
| 243 | +        if(!$this->configured) { | |
| 244 | + $this->readConfiguration(); | |
| 245 | + } | |
| 246 | +        if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { | |
| 247 | + return null; | |
| 248 | + } | |
| 249 | + $key = $this->getCacheKey($key); | |
| 250 | + | |
| 251 | + return json_decode(base64_decode($this->cache->get($key)), true); | |
| 252 | + } | |
| 253 | + | |
| 254 | + /** | |
| 255 | + * @param string $key | |
| 256 | + * @param mixed $value | |
| 257 | + * | |
| 258 | + * @return string | |
| 259 | + */ | |
| 260 | +    public function writeToCache($key, $value) { | |
| 261 | +        if(!$this->configured) { | |
| 262 | + $this->readConfiguration(); | |
| 263 | + } | |
| 264 | + if(is_null($this->cache) | |
| 265 | + || !$this->configuration->ldapCacheTTL | |
| 266 | +            || !$this->configuration->ldapConfigurationActive) { | |
| 267 | + return null; | |
| 268 | + } | |
| 269 | + $key = $this->getCacheKey($key); | |
| 270 | + $value = base64_encode(json_encode($value)); | |
| 271 | + $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); | |
| 272 | + } | |
| 273 | + | |
| 274 | +    public function clearCache() { | |
| 275 | +        if(!is_null($this->cache)) { | |
| 276 | + $this->cache->clear($this->getCacheKey(null)); | |
| 277 | + } | |
| 278 | + } | |
| 279 | + | |
| 280 | + /** | |
| 281 | + * Caches the general LDAP configuration. | |
| 282 | + * @param bool $force optional. true, if the re-read should be forced. defaults | |
| 283 | + * to false. | |
| 284 | + * @return null | |
| 285 | + */ | |
| 286 | +    private function readConfiguration($force = false) { | |
| 287 | +        if((!$this->configured || $force) && !is_null($this->configID)) { | |
| 288 | + $this->configuration->readConfiguration(); | |
| 289 | + $this->configured = $this->validateConfiguration(); | |
| 290 | + } | |
| 291 | + } | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * set LDAP configuration with values delivered by an array, not read from configuration | |
| 295 | + * @param array $config array that holds the config parameters in an associated array | |
| 296 | + * @param array &$setParameters optional; array where the set fields will be given to | |
| 297 | + * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters | |
| 298 | + */ | |
| 299 | +    public function setConfiguration($config, &$setParameters = null) { | |
| 300 | +        if(is_null($setParameters)) { | |
| 301 | + $setParameters = array(); | |
| 302 | + } | |
| 303 | + $this->doNotValidate = false; | |
| 304 | + $this->configuration->setConfiguration($config, $setParameters); | |
| 305 | +        if(count($setParameters) > 0) { | |
| 306 | + $this->configured = $this->validateConfiguration(); | |
| 307 | + } | |
| 308 | + | |
| 309 | + | |
| 310 | + return $this->configured; | |
| 311 | + } | |
| 312 | + | |
| 313 | + /** | |
| 314 | + * saves the current Configuration in the database and empties the | |
| 315 | + * cache | |
| 316 | + * @return null | |
| 317 | + */ | |
| 318 | +    public function saveConfiguration() { | |
| 319 | + $this->configuration->saveConfiguration(); | |
| 320 | + $this->clearCache(); | |
| 321 | + } | |
| 322 | + | |
| 323 | + /** | |
| 324 | + * get the current LDAP configuration | |
| 325 | + * @return array | |
| 326 | + */ | |
| 327 | +    public function getConfiguration() { | |
| 328 | + $this->readConfiguration(); | |
| 329 | + $config = $this->configuration->getConfiguration(); | |
| 330 | + $cta = $this->configuration->getConfigTranslationArray(); | |
| 331 | + $result = array(); | |
| 332 | +        foreach($cta as $dbkey => $configkey) { | |
| 333 | +            switch($configkey) { | |
| 334 | + case 'homeFolderNamingRule': | |
| 335 | +                    if(strpos($config[$configkey], 'attr:') === 0) { | |
| 336 | + $result[$dbkey] = substr($config[$configkey], 5); | |
| 337 | +                    } else { | |
| 338 | + $result[$dbkey] = ''; | |
| 339 | + } | |
| 340 | + break; | |
| 341 | + case 'ldapBase': | |
| 342 | + case 'ldapBaseUsers': | |
| 343 | + case 'ldapBaseGroups': | |
| 344 | + case 'ldapAttributesForUserSearch': | |
| 345 | + case 'ldapAttributesForGroupSearch': | |
| 346 | +                    if(is_array($config[$configkey])) { | |
| 347 | +                        $result[$dbkey] = implode("\n", $config[$configkey]); | |
| 348 | + break; | |
| 349 | + } //else follows default | |
| 350 | + default: | |
| 351 | + $result[$dbkey] = $config[$configkey]; | |
| 352 | + } | |
| 353 | + } | |
| 354 | + return $result; | |
| 355 | + } | |
| 356 | + | |
| 357 | +    private function doSoftValidation() { | |
| 358 | + //if User or Group Base are not set, take over Base DN setting | |
| 359 | +        foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) { | |
| 360 | + $val = $this->configuration->$keyBase; | |
| 361 | +            if(empty($val)) { | |
| 362 | + $this->configuration->$keyBase = $this->configuration->ldapBase; | |
| 363 | + } | |
| 364 | + } | |
| 365 | + | |
| 366 | +        foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute', | |
| 367 | + 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute') | |
| 368 | +                as $expertSetting => $effectiveSetting) { | |
| 369 | + $uuidOverride = $this->configuration->$expertSetting; | |
| 370 | +            if(!empty($uuidOverride)) { | |
| 371 | + $this->configuration->$effectiveSetting = $uuidOverride; | |
| 372 | +            } else { | |
| 373 | + $uuidAttributes = Access::UUID_ATTRIBUTES; | |
| 374 | + array_unshift($uuidAttributes, 'auto'); | |
| 375 | + if(!in_array($this->configuration->$effectiveSetting, | |
| 376 | + $uuidAttributes) | |
| 377 | +                    && (!is_null($this->configID))) { | |
| 378 | + $this->configuration->$effectiveSetting = 'auto'; | |
| 379 | + $this->configuration->saveConfiguration(); | |
| 380 | +                    \OCP\Util::writeLog('user_ldap', | |
| 381 | + 'Illegal value for the '. | |
| 382 | + $effectiveSetting.', '.'reset to '. | |
| 383 | + 'autodetect.', ILogger::INFO); | |
| 384 | + } | |
| 385 | + | |
| 386 | + } | |
| 387 | + } | |
| 388 | + | |
| 389 | + $backupPort = (int)$this->configuration->ldapBackupPort; | |
| 390 | +        if ($backupPort <= 0) { | |
| 391 | + $this->configuration->backupPort = $this->configuration->ldapPort; | |
| 392 | + } | |
| 393 | + | |
| 394 | + //make sure empty search attributes are saved as simple, empty array | |
| 395 | +        $saKeys = array('ldapAttributesForUserSearch', | |
| 396 | + 'ldapAttributesForGroupSearch'); | |
| 397 | +        foreach($saKeys as $key) { | |
| 398 | + $val = $this->configuration->$key; | |
| 399 | +            if(is_array($val) && count($val) === 1 && empty($val[0])) { | |
| 400 | + $this->configuration->$key = array(); | |
| 401 | + } | |
| 402 | + } | |
| 403 | + | |
| 404 | + if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) | |
| 405 | +            && $this->configuration->ldapTLS) { | |
| 406 | + $this->configuration->ldapTLS = false; | |
| 407 | + \OCP\Util::writeLog( | |
| 408 | + 'user_ldap', | |
| 409 | + 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.', | |
| 410 | + ILogger::INFO | |
| 411 | + ); | |
| 412 | + } | |
| 413 | + } | |
| 414 | + | |
| 415 | + /** | |
| 416 | + * @return bool | |
| 417 | + */ | |
| 418 | +    private function doCriticalValidation() { | |
| 419 | + $configurationOK = true; | |
| 420 | + $errorStr = 'Configuration Error (prefix '. | |
| 421 | + (string)$this->configPrefix .'): '; | |
| 422 | + | |
| 423 | + //options that shall not be empty | |
| 424 | +        $options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName', | |
| 425 | + 'ldapGroupDisplayName', 'ldapLoginFilter'); | |
| 426 | +        foreach($options as $key) { | |
| 427 | + $val = $this->configuration->$key; | |
| 428 | +            if(empty($val)) { | |
| 429 | +                switch($key) { | |
| 430 | + case 'ldapHost': | |
| 431 | + $subj = 'LDAP Host'; | |
| 432 | + break; | |
| 433 | + case 'ldapPort': | |
| 434 | + $subj = 'LDAP Port'; | |
| 435 | + break; | |
| 436 | + case 'ldapUserDisplayName': | |
| 437 | + $subj = 'LDAP User Display Name'; | |
| 438 | + break; | |
| 439 | + case 'ldapGroupDisplayName': | |
| 440 | + $subj = 'LDAP Group Display Name'; | |
| 441 | + break; | |
| 442 | + case 'ldapLoginFilter': | |
| 443 | + $subj = 'LDAP Login Filter'; | |
| 444 | + break; | |
| 445 | + default: | |
| 446 | + $subj = $key; | |
| 447 | + break; | |
| 448 | + } | |
| 449 | + $configurationOK = false; | |
| 450 | + \OCP\Util::writeLog( | |
| 451 | + 'user_ldap', | |
| 452 | + $errorStr.'No '.$subj.' given!', | |
| 453 | + ILogger::WARN | |
| 454 | + ); | |
| 455 | + } | |
| 456 | + } | |
| 457 | + | |
| 458 | + //combinations | |
| 459 | + $agent = $this->configuration->ldapAgentName; | |
| 460 | + $pwd = $this->configuration->ldapAgentPassword; | |
| 461 | + if ( | |
| 462 | + ($agent === '' && $pwd !== '') | |
| 463 | + || ($agent !== '' && $pwd === '') | |
| 464 | +        ) { | |
| 465 | + \OCP\Util::writeLog( | |
| 466 | + 'user_ldap', | |
| 467 | + $errorStr.'either no password is given for the user ' . | |
| 468 | + 'agent or a password is given, but not an LDAP agent.', | |
| 469 | + ILogger::WARN); | |
| 470 | + $configurationOK = false; | |
| 471 | + } | |
| 472 | + | |
| 473 | + $base = $this->configuration->ldapBase; | |
| 474 | + $baseUsers = $this->configuration->ldapBaseUsers; | |
| 475 | + $baseGroups = $this->configuration->ldapBaseGroups; | |
| 476 | + | |
| 477 | +        if(empty($base) && empty($baseUsers) && empty($baseGroups)) { | |
| 478 | + \OCP\Util::writeLog( | |
| 479 | + 'user_ldap', | |
| 480 | + $errorStr.'Not a single Base DN given.', | |
| 481 | + ILogger::WARN | |
| 482 | + ); | |
| 483 | + $configurationOK = false; | |
| 484 | + } | |
| 485 | + | |
| 486 | + if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') | |
| 487 | +            === false) { | |
| 488 | + \OCP\Util::writeLog( | |
| 489 | + 'user_ldap', | |
| 490 | + $errorStr.'login filter does not contain %uid place holder.', | |
| 491 | + ILogger::WARN | |
| 492 | + ); | |
| 493 | + $configurationOK = false; | |
| 494 | + } | |
| 495 | + | |
| 496 | + return $configurationOK; | |
| 497 | + } | |
| 498 | + | |
| 499 | + /** | |
| 500 | + * Validates the user specified configuration | |
| 501 | + * @return bool true if configuration seems OK, false otherwise | |
| 502 | + */ | |
| 503 | +    private function validateConfiguration() { | |
| 504 | + | |
| 505 | +        if($this->doNotValidate) { | |
| 506 | + //don't do a validation if it is a new configuration with pure | |
| 507 | + //default values. Will be allowed on changes via __set or | |
| 508 | + //setConfiguration | |
| 509 | + return false; | |
| 510 | + } | |
| 511 | + | |
| 512 | + // first step: "soft" checks: settings that are not really | |
| 513 | + // necessary, but advisable. If left empty, give an info message | |
| 514 | + $this->doSoftValidation(); | |
| 515 | + | |
| 516 | + //second step: critical checks. If left empty or filled wrong, mark as | |
| 517 | + //not configured and give a warning. | |
| 518 | + return $this->doCriticalValidation(); | |
| 519 | + } | |
| 520 | + | |
| 521 | + | |
| 522 | + /** | |
| 523 | + * Connects and Binds to LDAP | |
| 524 | + * | |
| 525 | + * @throws ServerNotAvailableException | |
| 526 | + */ | |
| 527 | +    private function establishConnection() { | |
| 528 | +        if(!$this->configuration->ldapConfigurationActive) { | |
| 529 | + return null; | |
| 530 | + } | |
| 531 | + static $phpLDAPinstalled = true; | |
| 532 | +        if(!$phpLDAPinstalled) { | |
| 533 | + return false; | |
| 534 | + } | |
| 535 | +        if(!$this->ignoreValidation && !$this->configured) { | |
| 536 | + \OCP\Util::writeLog( | |
| 537 | + 'user_ldap', | |
| 538 | + 'Configuration is invalid, cannot connect', | |
| 539 | + ILogger::WARN | |
| 540 | + ); | |
| 541 | + return false; | |
| 542 | + } | |
| 543 | +        if(!$this->ldapConnectionRes) { | |
| 544 | +            if(!$this->ldap->areLDAPFunctionsAvailable()) { | |
| 545 | + $phpLDAPinstalled = false; | |
| 546 | + \OCP\Util::writeLog( | |
| 547 | + 'user_ldap', | |
| 548 | + 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', | |
| 549 | + ILogger::ERROR | |
| 550 | + ); | |
| 551 | + | |
| 552 | + return false; | |
| 553 | + } | |
| 554 | +            if($this->configuration->turnOffCertCheck) { | |
| 555 | +                if(putenv('LDAPTLS_REQCERT=never')) { | |
| 556 | +                    \OCP\Util::writeLog('user_ldap', | |
| 557 | + 'Turned off SSL certificate validation successfully.', | |
| 558 | + ILogger::DEBUG); | |
| 559 | +                } else { | |
| 560 | + \OCP\Util::writeLog( | |
| 561 | + 'user_ldap', | |
| 562 | + 'Could not turn off SSL certificate validation.', | |
| 563 | + ILogger::WARN | |
| 564 | + ); | |
| 565 | + } | |
| 566 | + } | |
| 567 | + | |
| 568 | + $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer | |
| 569 | +                || $this->getFromCache('overrideMainServer')); | |
| 570 | + $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); | |
| 571 | + $bindStatus = false; | |
| 572 | +            try { | |
| 573 | +                if (!$isOverrideMainServer) { | |
| 574 | + $this->doConnect($this->configuration->ldapHost, | |
| 575 | + $this->configuration->ldapPort); | |
| 576 | + return $this->bind(); | |
| 577 | + } | |
| 578 | +            } catch (ServerNotAvailableException $e) { | |
| 579 | +                if(!$isBackupHost) { | |
| 580 | + throw $e; | |
| 581 | + } | |
| 582 | + } | |
| 583 | + | |
| 584 | + //if LDAP server is not reachable, try the Backup (Replica!) Server | |
| 585 | +            if($isBackupHost || $isOverrideMainServer) { | |
| 586 | + $this->doConnect($this->configuration->ldapBackupHost, | |
| 587 | + $this->configuration->ldapBackupPort); | |
| 588 | + $this->bindResult = []; | |
| 589 | + $bindStatus = $this->bind(); | |
| 590 | + $error = $this->ldap->isResource($this->ldapConnectionRes) ? | |
| 591 | + $this->ldap->errno($this->ldapConnectionRes) : -1; | |
| 592 | +                if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { | |
| 593 | + //when bind to backup server succeeded and failed to main server, | |
| 594 | + //skip contacting him until next cache refresh | |
| 595 | +                    $this->writeToCache('overrideMainServer', true); | |
| 596 | + } | |
| 597 | + } | |
| 598 | + | |
| 599 | + return $bindStatus; | |
| 600 | + } | |
| 601 | + return null; | |
| 602 | + } | |
| 603 | + | |
| 604 | + /** | |
| 605 | + * @param string $host | |
| 606 | + * @param string $port | |
| 607 | + * @return bool | |
| 608 | + * @throws \OC\ServerNotAvailableException | |
| 609 | + */ | |
| 610 | +    private function doConnect($host, $port) { | |
| 611 | +        if ($host === '') { | |
| 612 | + return false; | |
| 613 | + } | |
| 614 | + | |
| 615 | + $this->ldapConnectionRes = $this->ldap->connect($host, $port); | |
| 616 | + | |
| 617 | +        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { | |
| 618 | +            throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); | |
| 619 | + } | |
| 620 | + | |
| 621 | +        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { | |
| 622 | +            throw new ServerNotAvailableException('Could not disable LDAP referrals.'); | |
| 623 | + } | |
| 624 | + | |
| 625 | +        if($this->configuration->ldapTLS) { | |
| 626 | +            if(!$this->ldap->startTls($this->ldapConnectionRes)) { | |
| 627 | +                throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); | |
| 628 | + } | |
| 629 | + } | |
| 630 | + | |
| 631 | + return true; | |
| 632 | + } | |
| 633 | + | |
| 634 | + /** | |
| 635 | + * Binds to LDAP | |
| 636 | + */ | |
| 637 | +    public function bind() { | |
| 638 | +        if(!$this->configuration->ldapConfigurationActive) { | |
| 639 | + return false; | |
| 640 | + } | |
| 641 | + $cr = $this->ldapConnectionRes; | |
| 642 | +        if(!$this->ldap->isResource($cr)) { | |
| 643 | + $cr = $this->getConnectionResource(); | |
| 644 | + } | |
| 645 | + | |
| 646 | + if( | |
| 647 | + count($this->bindResult) !== 0 | |
| 648 | + && $this->bindResult['dn'] === $this->configuration->ldapAgentName | |
| 649 | + && \OC::$server->getHasher()->verify( | |
| 650 | + $this->configPrefix . $this->configuration->ldapAgentPassword, | |
| 651 | + $this->bindResult['hash'] | |
| 652 | + ) | |
| 653 | +        ) { | |
| 654 | + // don't attempt to bind again with the same data as before | |
| 655 | + // bind might have been invoked via getConnectionResource(), | |
| 656 | + // but we need results specifically for e.g. user login | |
| 657 | + return $this->bindResult['result']; | |
| 658 | + } | |
| 659 | + | |
| 660 | + $ldapLogin = @$this->ldap->bind($cr, | |
| 661 | + $this->configuration->ldapAgentName, | |
| 662 | + $this->configuration->ldapAgentPassword); | |
| 663 | + | |
| 664 | + $this->bindResult = [ | |
| 665 | + 'dn' => $this->configuration->ldapAgentName, | |
| 666 | + 'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword), | |
| 667 | + 'result' => $ldapLogin, | |
| 668 | + ]; | |
| 669 | + | |
| 670 | +        if(!$ldapLogin) { | |
| 671 | + $errno = $this->ldap->errno($cr); | |
| 672 | + | |
| 673 | +            \OCP\Util::writeLog('user_ldap', | |
| 674 | + 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), | |
| 675 | + ILogger::WARN); | |
| 676 | + | |
| 677 | + // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS | |
| 678 | +            if($errno !== 0x00 && $errno !== 0x31) { | |
| 679 | + $this->ldapConnectionRes = null; | |
| 680 | + } | |
| 681 | + | |
| 682 | + return false; | |
| 683 | + } | |
| 684 | + return true; | |
| 685 | + } | |
| 686 | 686 | |
| 687 | 687 | } | 
| @@ -59,1732 +59,1732 @@ discard block | ||
| 59 | 59 | * @package OCA\User_LDAP | 
| 60 | 60 | */ | 
| 61 | 61 |  class Access extends LDAPUtility { | 
| 62 | - const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid']; | |
| 63 | - | |
| 64 | - /** @var \OCA\User_LDAP\Connection */ | |
| 65 | - public $connection; | |
| 66 | - /** @var Manager */ | |
| 67 | - public $userManager; | |
| 68 | - //never ever check this var directly, always use getPagedSearchResultState | |
| 69 | - protected $pagedSearchedSuccessful; | |
| 70 | - | |
| 71 | - /** | |
| 72 | - * @var string[] $cookies an array of returned Paged Result cookies | |
| 73 | - */ | |
| 74 | - protected $cookies = array(); | |
| 75 | - | |
| 76 | - /** | |
| 77 | - * @var string $lastCookie the last cookie returned from a Paged Results | |
| 78 | - * operation, defaults to an empty string | |
| 79 | - */ | |
| 80 | - protected $lastCookie = ''; | |
| 81 | - | |
| 82 | - /** | |
| 83 | - * @var AbstractMapping $userMapper | |
| 84 | - */ | |
| 85 | - protected $userMapper; | |
| 86 | - | |
| 87 | - /** | |
| 88 | - * @var AbstractMapping $userMapper | |
| 89 | - */ | |
| 90 | - protected $groupMapper; | |
| 91 | - | |
| 92 | - /** | |
| 93 | - * @var \OCA\User_LDAP\Helper | |
| 94 | - */ | |
| 95 | - private $helper; | |
| 96 | - /** @var IConfig */ | |
| 97 | - private $config; | |
| 98 | - /** @var IUserManager */ | |
| 99 | - private $ncUserManager; | |
| 100 | - | |
| 101 | - public function __construct( | |
| 102 | - Connection $connection, | |
| 103 | - ILDAPWrapper $ldap, | |
| 104 | - Manager $userManager, | |
| 105 | - Helper $helper, | |
| 106 | - IConfig $config, | |
| 107 | - IUserManager $ncUserManager | |
| 108 | -	) { | |
| 109 | - parent::__construct($ldap); | |
| 110 | - $this->connection = $connection; | |
| 111 | - $this->userManager = $userManager; | |
| 112 | - $this->userManager->setLdapAccess($this); | |
| 113 | - $this->helper = $helper; | |
| 114 | - $this->config = $config; | |
| 115 | - $this->ncUserManager = $ncUserManager; | |
| 116 | - } | |
| 117 | - | |
| 118 | - /** | |
| 119 | - * sets the User Mapper | |
| 120 | - * @param AbstractMapping $mapper | |
| 121 | - */ | |
| 122 | -	public function setUserMapper(AbstractMapping $mapper) { | |
| 123 | - $this->userMapper = $mapper; | |
| 124 | - } | |
| 125 | - | |
| 126 | - /** | |
| 127 | - * returns the User Mapper | |
| 128 | - * @throws \Exception | |
| 129 | - * @return AbstractMapping | |
| 130 | - */ | |
| 131 | -	public function getUserMapper() { | |
| 132 | -		if(is_null($this->userMapper)) { | |
| 133 | -			throw new \Exception('UserMapper was not assigned to this Access instance.'); | |
| 134 | - } | |
| 135 | - return $this->userMapper; | |
| 136 | - } | |
| 137 | - | |
| 138 | - /** | |
| 139 | - * sets the Group Mapper | |
| 140 | - * @param AbstractMapping $mapper | |
| 141 | - */ | |
| 142 | -	public function setGroupMapper(AbstractMapping $mapper) { | |
| 143 | - $this->groupMapper = $mapper; | |
| 144 | - } | |
| 145 | - | |
| 146 | - /** | |
| 147 | - * returns the Group Mapper | |
| 148 | - * @throws \Exception | |
| 149 | - * @return AbstractMapping | |
| 150 | - */ | |
| 151 | -	public function getGroupMapper() { | |
| 152 | -		if(is_null($this->groupMapper)) { | |
| 153 | -			throw new \Exception('GroupMapper was not assigned to this Access instance.'); | |
| 154 | - } | |
| 155 | - return $this->groupMapper; | |
| 156 | - } | |
| 157 | - | |
| 158 | - /** | |
| 159 | - * @return bool | |
| 160 | - */ | |
| 161 | -	private function checkConnection() { | |
| 162 | - return ($this->connection instanceof Connection); | |
| 163 | - } | |
| 164 | - | |
| 165 | - /** | |
| 166 | - * returns the Connection instance | |
| 167 | - * @return \OCA\User_LDAP\Connection | |
| 168 | - */ | |
| 169 | -	public function getConnection() { | |
| 170 | - return $this->connection; | |
| 171 | - } | |
| 172 | - | |
| 173 | - /** | |
| 174 | - * reads a given attribute for an LDAP record identified by a DN | |
| 175 | - * | |
| 176 | - * @param string $dn the record in question | |
| 177 | - * @param string $attr the attribute that shall be retrieved | |
| 178 | - * if empty, just check the record's existence | |
| 179 | - * @param string $filter | |
| 180 | - * @return array|false an array of values on success or an empty | |
| 181 | - * array if $attr is empty, false otherwise | |
| 182 | - * @throws ServerNotAvailableException | |
| 183 | - */ | |
| 184 | -	public function readAttribute($dn, $attr, $filter = 'objectClass=*') { | |
| 185 | -		if(!$this->checkConnection()) { | |
| 186 | -			\OCP\Util::writeLog('user_ldap', | |
| 187 | - 'No LDAP Connector assigned, access impossible for readAttribute.', | |
| 188 | - ILogger::WARN); | |
| 189 | - return false; | |
| 190 | - } | |
| 191 | - $cr = $this->connection->getConnectionResource(); | |
| 192 | -		if(!$this->ldap->isResource($cr)) { | |
| 193 | - //LDAP not available | |
| 194 | -			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); | |
| 195 | - return false; | |
| 196 | - } | |
| 197 | - //Cancel possibly running Paged Results operation, otherwise we run in | |
| 198 | - //LDAP protocol errors | |
| 199 | - $this->abandonPagedSearch(); | |
| 200 | - // openLDAP requires that we init a new Paged Search. Not needed by AD, | |
| 201 | - // but does not hurt either. | |
| 202 | - $pagingSize = (int)$this->connection->ldapPagingSize; | |
| 203 | - // 0 won't result in replies, small numbers may leave out groups | |
| 204 | - // (cf. #12306), 500 is default for paging and should work everywhere. | |
| 205 | - $maxResults = $pagingSize > 20 ? $pagingSize : 500; | |
| 206 | - $attr = mb_strtolower($attr, 'UTF-8'); | |
| 207 | - // the actual read attribute later may contain parameters on a ranged | |
| 208 | - // request, e.g. member;range=99-199. Depends on server reply. | |
| 209 | - $attrToRead = $attr; | |
| 210 | - | |
| 211 | - $values = []; | |
| 212 | - $isRangeRequest = false; | |
| 213 | -		do { | |
| 214 | - $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); | |
| 215 | -			if(is_bool($result)) { | |
| 216 | - // when an exists request was run and it was successful, an empty | |
| 217 | - // array must be returned | |
| 218 | - return $result ? [] : false; | |
| 219 | - } | |
| 220 | - | |
| 221 | -			if (!$isRangeRequest) { | |
| 222 | - $values = $this->extractAttributeValuesFromResult($result, $attr); | |
| 223 | -				if (!empty($values)) { | |
| 224 | - return $values; | |
| 225 | - } | |
| 226 | - } | |
| 227 | - | |
| 228 | - $isRangeRequest = false; | |
| 229 | - $result = $this->extractRangeData($result, $attr); | |
| 230 | -			if (!empty($result)) { | |
| 231 | - $normalizedResult = $this->extractAttributeValuesFromResult( | |
| 232 | - [ $attr => $result['values'] ], | |
| 233 | - $attr | |
| 234 | - ); | |
| 235 | - $values = array_merge($values, $normalizedResult); | |
| 236 | - | |
| 237 | -				if($result['rangeHigh'] === '*') { | |
| 238 | - // when server replies with * as high range value, there are | |
| 239 | - // no more results left | |
| 240 | - return $values; | |
| 241 | -				} else { | |
| 242 | - $low = $result['rangeHigh'] + 1; | |
| 243 | - $attrToRead = $result['attributeName'] . ';range=' . $low . '-*'; | |
| 244 | - $isRangeRequest = true; | |
| 245 | - } | |
| 246 | - } | |
| 247 | - } while($isRangeRequest); | |
| 248 | - | |
| 249 | -		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG); | |
| 250 | - return false; | |
| 251 | - } | |
| 252 | - | |
| 253 | - /** | |
| 254 | - * Runs an read operation against LDAP | |
| 255 | - * | |
| 256 | - * @param resource $cr the LDAP connection | |
| 257 | - * @param string $dn | |
| 258 | - * @param string $attribute | |
| 259 | - * @param string $filter | |
| 260 | - * @param int $maxResults | |
| 261 | - * @return array|bool false if there was any error, true if an exists check | |
| 262 | - * was performed and the requested DN found, array with the | |
| 263 | - * returned data on a successful usual operation | |
| 264 | - * @throws ServerNotAvailableException | |
| 265 | - */ | |
| 266 | -	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) { | |
| 267 | - $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0); | |
| 268 | - $dn = $this->helper->DNasBaseParameter($dn); | |
| 269 | -		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute)); | |
| 270 | -		if (!$this->ldap->isResource($rr)) { | |
| 271 | -			if ($attribute !== '') { | |
| 272 | - //do not throw this message on userExists check, irritates | |
| 273 | -				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG); | |
| 274 | - } | |
| 275 | - //in case an error occurs , e.g. object does not exist | |
| 276 | - return false; | |
| 277 | - } | |
| 278 | -		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) { | |
| 279 | -			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG); | |
| 280 | - return true; | |
| 281 | - } | |
| 282 | -		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr); | |
| 283 | -		if (!$this->ldap->isResource($er)) { | |
| 284 | - //did not match the filter, return false | |
| 285 | - return false; | |
| 286 | - } | |
| 287 | - //LDAP attributes are not case sensitive | |
| 288 | - $result = \OCP\Util::mb_array_change_key_case( | |
| 289 | -			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8'); | |
| 290 | - | |
| 291 | - return $result; | |
| 292 | - } | |
| 293 | - | |
| 294 | - /** | |
| 295 | - * Normalizes a result grom getAttributes(), i.e. handles DNs and binary | |
| 296 | - * data if present. | |
| 297 | - * | |
| 298 | - * @param array $result from ILDAPWrapper::getAttributes() | |
| 299 | - * @param string $attribute the attribute name that was read | |
| 300 | - * @return string[] | |
| 301 | - */ | |
| 302 | -	public function extractAttributeValuesFromResult($result, $attribute) { | |
| 303 | - $values = []; | |
| 304 | -		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { | |
| 305 | - $lowercaseAttribute = strtolower($attribute); | |
| 306 | -			for($i=0;$i<$result[$attribute]['count'];$i++) { | |
| 307 | -				if($this->resemblesDN($attribute)) { | |
| 308 | - $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); | |
| 309 | -				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { | |
| 310 | - $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); | |
| 311 | -				} else { | |
| 312 | - $values[] = $result[$attribute][$i]; | |
| 313 | - } | |
| 314 | - } | |
| 315 | - } | |
| 316 | - return $values; | |
| 317 | - } | |
| 318 | - | |
| 319 | - /** | |
| 320 | - * Attempts to find ranged data in a getAttribute results and extracts the | |
| 321 | - * returned values as well as information on the range and full attribute | |
| 322 | - * name for further processing. | |
| 323 | - * | |
| 324 | - * @param array $result from ILDAPWrapper::getAttributes() | |
| 325 | - * @param string $attribute the attribute name that was read. Without ";range=…" | |
| 326 | - * @return array If a range was detected with keys 'values', 'attributeName', | |
| 327 | - * 'attributeFull' and 'rangeHigh', otherwise empty. | |
| 328 | - */ | |
| 329 | -	public function extractRangeData($result, $attribute) { | |
| 330 | - $keys = array_keys($result); | |
| 331 | -		foreach($keys as $key) { | |
| 332 | -			if($key !== $attribute && strpos($key, $attribute) === 0) { | |
| 333 | -				$queryData = explode(';', $key); | |
| 334 | -				if(strpos($queryData[1], 'range=') === 0) { | |
| 335 | - $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); | |
| 336 | - $data = [ | |
| 337 | - 'values' => $result[$key], | |
| 338 | - 'attributeName' => $queryData[0], | |
| 339 | - 'attributeFull' => $key, | |
| 340 | - 'rangeHigh' => $high, | |
| 341 | - ]; | |
| 342 | - return $data; | |
| 343 | - } | |
| 344 | - } | |
| 345 | - } | |
| 346 | - return []; | |
| 347 | - } | |
| 62 | + const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid']; | |
| 63 | + | |
| 64 | + /** @var \OCA\User_LDAP\Connection */ | |
| 65 | + public $connection; | |
| 66 | + /** @var Manager */ | |
| 67 | + public $userManager; | |
| 68 | + //never ever check this var directly, always use getPagedSearchResultState | |
| 69 | + protected $pagedSearchedSuccessful; | |
| 70 | + | |
| 71 | + /** | |
| 72 | + * @var string[] $cookies an array of returned Paged Result cookies | |
| 73 | + */ | |
| 74 | + protected $cookies = array(); | |
| 75 | + | |
| 76 | + /** | |
| 77 | + * @var string $lastCookie the last cookie returned from a Paged Results | |
| 78 | + * operation, defaults to an empty string | |
| 79 | + */ | |
| 80 | + protected $lastCookie = ''; | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * @var AbstractMapping $userMapper | |
| 84 | + */ | |
| 85 | + protected $userMapper; | |
| 86 | + | |
| 87 | + /** | |
| 88 | + * @var AbstractMapping $userMapper | |
| 89 | + */ | |
| 90 | + protected $groupMapper; | |
| 91 | + | |
| 92 | + /** | |
| 93 | + * @var \OCA\User_LDAP\Helper | |
| 94 | + */ | |
| 95 | + private $helper; | |
| 96 | + /** @var IConfig */ | |
| 97 | + private $config; | |
| 98 | + /** @var IUserManager */ | |
| 99 | + private $ncUserManager; | |
| 100 | + | |
| 101 | + public function __construct( | |
| 102 | + Connection $connection, | |
| 103 | + ILDAPWrapper $ldap, | |
| 104 | + Manager $userManager, | |
| 105 | + Helper $helper, | |
| 106 | + IConfig $config, | |
| 107 | + IUserManager $ncUserManager | |
| 108 | +    ) { | |
| 109 | + parent::__construct($ldap); | |
| 110 | + $this->connection = $connection; | |
| 111 | + $this->userManager = $userManager; | |
| 112 | + $this->userManager->setLdapAccess($this); | |
| 113 | + $this->helper = $helper; | |
| 114 | + $this->config = $config; | |
| 115 | + $this->ncUserManager = $ncUserManager; | |
| 116 | + } | |
| 117 | + | |
| 118 | + /** | |
| 119 | + * sets the User Mapper | |
| 120 | + * @param AbstractMapping $mapper | |
| 121 | + */ | |
| 122 | +    public function setUserMapper(AbstractMapping $mapper) { | |
| 123 | + $this->userMapper = $mapper; | |
| 124 | + } | |
| 125 | + | |
| 126 | + /** | |
| 127 | + * returns the User Mapper | |
| 128 | + * @throws \Exception | |
| 129 | + * @return AbstractMapping | |
| 130 | + */ | |
| 131 | +    public function getUserMapper() { | |
| 132 | +        if(is_null($this->userMapper)) { | |
| 133 | +            throw new \Exception('UserMapper was not assigned to this Access instance.'); | |
| 134 | + } | |
| 135 | + return $this->userMapper; | |
| 136 | + } | |
| 137 | + | |
| 138 | + /** | |
| 139 | + * sets the Group Mapper | |
| 140 | + * @param AbstractMapping $mapper | |
| 141 | + */ | |
| 142 | +    public function setGroupMapper(AbstractMapping $mapper) { | |
| 143 | + $this->groupMapper = $mapper; | |
| 144 | + } | |
| 145 | + | |
| 146 | + /** | |
| 147 | + * returns the Group Mapper | |
| 148 | + * @throws \Exception | |
| 149 | + * @return AbstractMapping | |
| 150 | + */ | |
| 151 | +    public function getGroupMapper() { | |
| 152 | +        if(is_null($this->groupMapper)) { | |
| 153 | +            throw new \Exception('GroupMapper was not assigned to this Access instance.'); | |
| 154 | + } | |
| 155 | + return $this->groupMapper; | |
| 156 | + } | |
| 157 | + | |
| 158 | + /** | |
| 159 | + * @return bool | |
| 160 | + */ | |
| 161 | +    private function checkConnection() { | |
| 162 | + return ($this->connection instanceof Connection); | |
| 163 | + } | |
| 164 | + | |
| 165 | + /** | |
| 166 | + * returns the Connection instance | |
| 167 | + * @return \OCA\User_LDAP\Connection | |
| 168 | + */ | |
| 169 | +    public function getConnection() { | |
| 170 | + return $this->connection; | |
| 171 | + } | |
| 172 | + | |
| 173 | + /** | |
| 174 | + * reads a given attribute for an LDAP record identified by a DN | |
| 175 | + * | |
| 176 | + * @param string $dn the record in question | |
| 177 | + * @param string $attr the attribute that shall be retrieved | |
| 178 | + * if empty, just check the record's existence | |
| 179 | + * @param string $filter | |
| 180 | + * @return array|false an array of values on success or an empty | |
| 181 | + * array if $attr is empty, false otherwise | |
| 182 | + * @throws ServerNotAvailableException | |
| 183 | + */ | |
| 184 | +    public function readAttribute($dn, $attr, $filter = 'objectClass=*') { | |
| 185 | +        if(!$this->checkConnection()) { | |
| 186 | +            \OCP\Util::writeLog('user_ldap', | |
| 187 | + 'No LDAP Connector assigned, access impossible for readAttribute.', | |
| 188 | + ILogger::WARN); | |
| 189 | + return false; | |
| 190 | + } | |
| 191 | + $cr = $this->connection->getConnectionResource(); | |
| 192 | +        if(!$this->ldap->isResource($cr)) { | |
| 193 | + //LDAP not available | |
| 194 | +            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); | |
| 195 | + return false; | |
| 196 | + } | |
| 197 | + //Cancel possibly running Paged Results operation, otherwise we run in | |
| 198 | + //LDAP protocol errors | |
| 199 | + $this->abandonPagedSearch(); | |
| 200 | + // openLDAP requires that we init a new Paged Search. Not needed by AD, | |
| 201 | + // but does not hurt either. | |
| 202 | + $pagingSize = (int)$this->connection->ldapPagingSize; | |
| 203 | + // 0 won't result in replies, small numbers may leave out groups | |
| 204 | + // (cf. #12306), 500 is default for paging and should work everywhere. | |
| 205 | + $maxResults = $pagingSize > 20 ? $pagingSize : 500; | |
| 206 | + $attr = mb_strtolower($attr, 'UTF-8'); | |
| 207 | + // the actual read attribute later may contain parameters on a ranged | |
| 208 | + // request, e.g. member;range=99-199. Depends on server reply. | |
| 209 | + $attrToRead = $attr; | |
| 210 | + | |
| 211 | + $values = []; | |
| 212 | + $isRangeRequest = false; | |
| 213 | +        do { | |
| 214 | + $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); | |
| 215 | +            if(is_bool($result)) { | |
| 216 | + // when an exists request was run and it was successful, an empty | |
| 217 | + // array must be returned | |
| 218 | + return $result ? [] : false; | |
| 219 | + } | |
| 220 | + | |
| 221 | +            if (!$isRangeRequest) { | |
| 222 | + $values = $this->extractAttributeValuesFromResult($result, $attr); | |
| 223 | +                if (!empty($values)) { | |
| 224 | + return $values; | |
| 225 | + } | |
| 226 | + } | |
| 227 | + | |
| 228 | + $isRangeRequest = false; | |
| 229 | + $result = $this->extractRangeData($result, $attr); | |
| 230 | +            if (!empty($result)) { | |
| 231 | + $normalizedResult = $this->extractAttributeValuesFromResult( | |
| 232 | + [ $attr => $result['values'] ], | |
| 233 | + $attr | |
| 234 | + ); | |
| 235 | + $values = array_merge($values, $normalizedResult); | |
| 236 | + | |
| 237 | +                if($result['rangeHigh'] === '*') { | |
| 238 | + // when server replies with * as high range value, there are | |
| 239 | + // no more results left | |
| 240 | + return $values; | |
| 241 | +                } else { | |
| 242 | + $low = $result['rangeHigh'] + 1; | |
| 243 | + $attrToRead = $result['attributeName'] . ';range=' . $low . '-*'; | |
| 244 | + $isRangeRequest = true; | |
| 245 | + } | |
| 246 | + } | |
| 247 | + } while($isRangeRequest); | |
| 248 | + | |
| 249 | +        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG); | |
| 250 | + return false; | |
| 251 | + } | |
| 252 | + | |
| 253 | + /** | |
| 254 | + * Runs an read operation against LDAP | |
| 255 | + * | |
| 256 | + * @param resource $cr the LDAP connection | |
| 257 | + * @param string $dn | |
| 258 | + * @param string $attribute | |
| 259 | + * @param string $filter | |
| 260 | + * @param int $maxResults | |
| 261 | + * @return array|bool false if there was any error, true if an exists check | |
| 262 | + * was performed and the requested DN found, array with the | |
| 263 | + * returned data on a successful usual operation | |
| 264 | + * @throws ServerNotAvailableException | |
| 265 | + */ | |
| 266 | +    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) { | |
| 267 | + $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0); | |
| 268 | + $dn = $this->helper->DNasBaseParameter($dn); | |
| 269 | +        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute)); | |
| 270 | +        if (!$this->ldap->isResource($rr)) { | |
| 271 | +            if ($attribute !== '') { | |
| 272 | + //do not throw this message on userExists check, irritates | |
| 273 | +                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG); | |
| 274 | + } | |
| 275 | + //in case an error occurs , e.g. object does not exist | |
| 276 | + return false; | |
| 277 | + } | |
| 278 | +        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) { | |
| 279 | +            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG); | |
| 280 | + return true; | |
| 281 | + } | |
| 282 | +        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr); | |
| 283 | +        if (!$this->ldap->isResource($er)) { | |
| 284 | + //did not match the filter, return false | |
| 285 | + return false; | |
| 286 | + } | |
| 287 | + //LDAP attributes are not case sensitive | |
| 288 | + $result = \OCP\Util::mb_array_change_key_case( | |
| 289 | +            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8'); | |
| 290 | + | |
| 291 | + return $result; | |
| 292 | + } | |
| 293 | + | |
| 294 | + /** | |
| 295 | + * Normalizes a result grom getAttributes(), i.e. handles DNs and binary | |
| 296 | + * data if present. | |
| 297 | + * | |
| 298 | + * @param array $result from ILDAPWrapper::getAttributes() | |
| 299 | + * @param string $attribute the attribute name that was read | |
| 300 | + * @return string[] | |
| 301 | + */ | |
| 302 | +    public function extractAttributeValuesFromResult($result, $attribute) { | |
| 303 | + $values = []; | |
| 304 | +        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { | |
| 305 | + $lowercaseAttribute = strtolower($attribute); | |
| 306 | +            for($i=0;$i<$result[$attribute]['count'];$i++) { | |
| 307 | +                if($this->resemblesDN($attribute)) { | |
| 308 | + $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); | |
| 309 | +                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { | |
| 310 | + $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); | |
| 311 | +                } else { | |
| 312 | + $values[] = $result[$attribute][$i]; | |
| 313 | + } | |
| 314 | + } | |
| 315 | + } | |
| 316 | + return $values; | |
| 317 | + } | |
| 318 | + | |
| 319 | + /** | |
| 320 | + * Attempts to find ranged data in a getAttribute results and extracts the | |
| 321 | + * returned values as well as information on the range and full attribute | |
| 322 | + * name for further processing. | |
| 323 | + * | |
| 324 | + * @param array $result from ILDAPWrapper::getAttributes() | |
| 325 | + * @param string $attribute the attribute name that was read. Without ";range=…" | |
| 326 | + * @return array If a range was detected with keys 'values', 'attributeName', | |
| 327 | + * 'attributeFull' and 'rangeHigh', otherwise empty. | |
| 328 | + */ | |
| 329 | +    public function extractRangeData($result, $attribute) { | |
| 330 | + $keys = array_keys($result); | |
| 331 | +        foreach($keys as $key) { | |
| 332 | +            if($key !== $attribute && strpos($key, $attribute) === 0) { | |
| 333 | +                $queryData = explode(';', $key); | |
| 334 | +                if(strpos($queryData[1], 'range=') === 0) { | |
| 335 | + $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); | |
| 336 | + $data = [ | |
| 337 | + 'values' => $result[$key], | |
| 338 | + 'attributeName' => $queryData[0], | |
| 339 | + 'attributeFull' => $key, | |
| 340 | + 'rangeHigh' => $high, | |
| 341 | + ]; | |
| 342 | + return $data; | |
| 343 | + } | |
| 344 | + } | |
| 345 | + } | |
| 346 | + return []; | |
| 347 | + } | |
| 348 | 348 | |
| 349 | - /** | |
| 350 | - * Set password for an LDAP user identified by a DN | |
| 351 | - * | |
| 352 | - * @param string $userDN the user in question | |
| 353 | - * @param string $password the new password | |
| 354 | - * @return bool | |
| 355 | - * @throws HintException | |
| 356 | - * @throws \Exception | |
| 357 | - */ | |
| 358 | -	public function setPassword($userDN, $password) { | |
| 359 | -		if((int)$this->connection->turnOnPasswordChange !== 1) { | |
| 360 | -			throw new \Exception('LDAP password changes are disabled.'); | |
| 361 | - } | |
| 362 | - $cr = $this->connection->getConnectionResource(); | |
| 363 | -		if(!$this->ldap->isResource($cr)) { | |
| 364 | - //LDAP not available | |
| 365 | -			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); | |
| 366 | - return false; | |
| 367 | - } | |
| 368 | -		try { | |
| 369 | -			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); | |
| 370 | -		} catch(ConstraintViolationException $e) { | |
| 371 | -			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); | |
| 372 | - } | |
| 373 | - } | |
| 374 | - | |
| 375 | - /** | |
| 376 | - * checks whether the given attributes value is probably a DN | |
| 377 | - * @param string $attr the attribute in question | |
| 378 | - * @return boolean if so true, otherwise false | |
| 379 | - */ | |
| 380 | -	private function resemblesDN($attr) { | |
| 381 | - $resemblingAttributes = array( | |
| 382 | - 'dn', | |
| 383 | - 'uniquemember', | |
| 384 | - 'member', | |
| 385 | - // memberOf is an "operational" attribute, without a definition in any RFC | |
| 386 | - 'memberof' | |
| 387 | - ); | |
| 388 | - return in_array($attr, $resemblingAttributes); | |
| 389 | - } | |
| 390 | - | |
| 391 | - /** | |
| 392 | - * checks whether the given string is probably a DN | |
| 393 | - * @param string $string | |
| 394 | - * @return boolean | |
| 395 | - */ | |
| 396 | -	public function stringResemblesDN($string) { | |
| 397 | - $r = $this->ldap->explodeDN($string, 0); | |
| 398 | - // if exploding a DN succeeds and does not end up in | |
| 399 | - // an empty array except for $r[count] being 0. | |
| 400 | - return (is_array($r) && count($r) > 1); | |
| 401 | - } | |
| 402 | - | |
| 403 | - /** | |
| 404 | - * returns a DN-string that is cleaned from not domain parts, e.g. | |
| 405 | - * cn=foo,cn=bar,dc=foobar,dc=server,dc=org | |
| 406 | - * becomes dc=foobar,dc=server,dc=org | |
| 407 | - * @param string $dn | |
| 408 | - * @return string | |
| 409 | - */ | |
| 410 | -	public function getDomainDNFromDN($dn) { | |
| 411 | - $allParts = $this->ldap->explodeDN($dn, 0); | |
| 412 | -		if($allParts === false) { | |
| 413 | - //not a valid DN | |
| 414 | - return ''; | |
| 415 | - } | |
| 416 | - $domainParts = array(); | |
| 417 | - $dcFound = false; | |
| 418 | -		foreach($allParts as $part) { | |
| 419 | -			if(!$dcFound && strpos($part, 'dc=') === 0) { | |
| 420 | - $dcFound = true; | |
| 421 | - } | |
| 422 | -			if($dcFound) { | |
| 423 | - $domainParts[] = $part; | |
| 424 | - } | |
| 425 | - } | |
| 426 | -		return implode(',', $domainParts); | |
| 427 | - } | |
| 428 | - | |
| 429 | - /** | |
| 430 | - * returns the LDAP DN for the given internal Nextcloud name of the group | |
| 431 | - * @param string $name the Nextcloud name in question | |
| 432 | - * @return string|false LDAP DN on success, otherwise false | |
| 433 | - */ | |
| 434 | -	public function groupname2dn($name) { | |
| 435 | - return $this->groupMapper->getDNByName($name); | |
| 436 | - } | |
| 437 | - | |
| 438 | - /** | |
| 439 | - * returns the LDAP DN for the given internal Nextcloud name of the user | |
| 440 | - * @param string $name the Nextcloud name in question | |
| 441 | - * @return string|false with the LDAP DN on success, otherwise false | |
| 442 | - */ | |
| 443 | -	public function username2dn($name) { | |
| 444 | - $fdn = $this->userMapper->getDNByName($name); | |
| 445 | - | |
| 446 | - //Check whether the DN belongs to the Base, to avoid issues on multi- | |
| 447 | - //server setups | |
| 448 | -		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 449 | - return $fdn; | |
| 450 | - } | |
| 451 | - | |
| 452 | - return false; | |
| 453 | - } | |
| 454 | - | |
| 455 | - /** | |
| 456 | - * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure | |
| 457 | - * @param string $fdn the dn of the group object | |
| 458 | - * @param string $ldapName optional, the display name of the object | |
| 459 | - * @return string|false with the name to use in Nextcloud, false on DN outside of search DN | |
| 460 | - */ | |
| 461 | -	public function dn2groupname($fdn, $ldapName = null) { | |
| 462 | - //To avoid bypassing the base DN settings under certain circumstances | |
| 463 | - //with the group support, check whether the provided DN matches one of | |
| 464 | - //the given Bases | |
| 465 | -		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { | |
| 466 | - return false; | |
| 467 | - } | |
| 468 | - | |
| 469 | - return $this->dn2ocname($fdn, $ldapName, false); | |
| 470 | - } | |
| 471 | - | |
| 472 | - /** | |
| 473 | - * accepts an array of group DNs and tests whether they match the user | |
| 474 | - * filter by doing read operations against the group entries. Returns an | |
| 475 | - * array of DNs that match the filter. | |
| 476 | - * | |
| 477 | - * @param string[] $groupDNs | |
| 478 | - * @return string[] | |
| 479 | - * @throws ServerNotAvailableException | |
| 480 | - */ | |
| 481 | -	public function groupsMatchFilter($groupDNs) { | |
| 482 | - $validGroupDNs = []; | |
| 483 | -		foreach($groupDNs as $dn) { | |
| 484 | - $cacheKey = 'groupsMatchFilter-'.$dn; | |
| 485 | - $groupMatchFilter = $this->connection->getFromCache($cacheKey); | |
| 486 | -			if(!is_null($groupMatchFilter)) { | |
| 487 | -				if($groupMatchFilter) { | |
| 488 | - $validGroupDNs[] = $dn; | |
| 489 | - } | |
| 490 | - continue; | |
| 491 | - } | |
| 492 | - | |
| 493 | - // Check the base DN first. If this is not met already, we don't | |
| 494 | - // need to ask the server at all. | |
| 495 | -			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { | |
| 496 | - $this->connection->writeToCache($cacheKey, false); | |
| 497 | - continue; | |
| 498 | - } | |
| 499 | - | |
| 500 | - $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter); | |
| 501 | -			if(is_array($result)) { | |
| 502 | - $this->connection->writeToCache($cacheKey, true); | |
| 503 | - $validGroupDNs[] = $dn; | |
| 504 | -			} else { | |
| 505 | - $this->connection->writeToCache($cacheKey, false); | |
| 506 | - } | |
| 507 | - | |
| 508 | - } | |
| 509 | - return $validGroupDNs; | |
| 510 | - } | |
| 511 | - | |
| 512 | - /** | |
| 513 | - * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure | |
| 514 | - * @param string $dn the dn of the user object | |
| 515 | - * @param string $ldapName optional, the display name of the object | |
| 516 | - * @return string|false with with the name to use in Nextcloud | |
| 517 | - */ | |
| 518 | -	public function dn2username($fdn, $ldapName = null) { | |
| 519 | - //To avoid bypassing the base DN settings under certain circumstances | |
| 520 | - //with the group support, check whether the provided DN matches one of | |
| 521 | - //the given Bases | |
| 522 | -		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 523 | - return false; | |
| 524 | - } | |
| 525 | - | |
| 526 | - return $this->dn2ocname($fdn, $ldapName, true); | |
| 527 | - } | |
| 528 | - | |
| 529 | - /** | |
| 530 | - * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN | |
| 531 | - * | |
| 532 | - * @param string $fdn the dn of the user object | |
| 533 | - * @param string|null $ldapName optional, the display name of the object | |
| 534 | - * @param bool $isUser optional, whether it is a user object (otherwise group assumed) | |
| 535 | - * @param bool|null $newlyMapped | |
| 536 | - * @param array|null $record | |
| 537 | - * @return false|string with with the name to use in Nextcloud | |
| 538 | - * @throws \Exception | |
| 539 | - */ | |
| 540 | -	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) { | |
| 541 | - $newlyMapped = false; | |
| 542 | -		if($isUser) { | |
| 543 | - $mapper = $this->getUserMapper(); | |
| 544 | - $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 545 | - $filter = $this->connection->ldapUserFilter; | |
| 546 | -		} else { | |
| 547 | - $mapper = $this->getGroupMapper(); | |
| 548 | - $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 549 | - $filter = $this->connection->ldapGroupFilter; | |
| 550 | - } | |
| 551 | - | |
| 552 | - //let's try to retrieve the Nextcloud name from the mappings table | |
| 553 | - $ncName = $mapper->getNameByDN($fdn); | |
| 554 | -		if(is_string($ncName)) { | |
| 555 | - return $ncName; | |
| 556 | - } | |
| 557 | - | |
| 558 | - //second try: get the UUID and check if it is known. Then, update the DN and return the name. | |
| 559 | - $uuid = $this->getUUID($fdn, $isUser, $record); | |
| 560 | -		if(is_string($uuid)) { | |
| 561 | - $ncName = $mapper->getNameByUUID($uuid); | |
| 562 | -			if(is_string($ncName)) { | |
| 563 | - $mapper->setDNbyUUID($fdn, $uuid); | |
| 564 | - return $ncName; | |
| 565 | - } | |
| 566 | -		} else { | |
| 567 | - //If the UUID can't be detected something is foul. | |
| 568 | -			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO); | |
| 569 | - return false; | |
| 570 | - } | |
| 571 | - | |
| 572 | -		if(is_null($ldapName)) { | |
| 573 | - $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter); | |
| 574 | -			if(!isset($ldapName[0]) && empty($ldapName[0])) { | |
| 575 | -				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO); | |
| 576 | - return false; | |
| 577 | - } | |
| 578 | - $ldapName = $ldapName[0]; | |
| 579 | - } | |
| 580 | - | |
| 581 | -		if($isUser) { | |
| 582 | - $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr; | |
| 583 | -			if ($usernameAttribute !== '') { | |
| 584 | - $username = $this->readAttribute($fdn, $usernameAttribute); | |
| 585 | - $username = $username[0]; | |
| 586 | -			} else { | |
| 587 | - $username = $uuid; | |
| 588 | - } | |
| 589 | -			try { | |
| 590 | - $intName = $this->sanitizeUsername($username); | |
| 591 | -			} catch (\InvalidArgumentException $e) { | |
| 592 | - \OC::$server->getLogger()->logException($e, [ | |
| 593 | - 'app' => 'user_ldap', | |
| 594 | - 'level' => ILogger::WARN, | |
| 595 | - ]); | |
| 596 | - // we don't attempt to set a username here. We can go for | |
| 597 | - // for an alternative 4 digit random number as we would append | |
| 598 | - // otherwise, however it's likely not enough space in bigger | |
| 599 | - // setups, and most importantly: this is not intended. | |
| 600 | - return false; | |
| 601 | - } | |
| 602 | -		} else { | |
| 603 | - $intName = $ldapName; | |
| 604 | - } | |
| 605 | - | |
| 606 | - //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups | |
| 607 | - //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check | |
| 608 | - //NOTE: mind, disabling cache affects only this instance! Using it | |
| 609 | - // outside of core user management will still cache the user as non-existing. | |
| 610 | - $originalTTL = $this->connection->ldapCacheTTL; | |
| 611 | - $this->connection->setConfiguration(['ldapCacheTTL' => 0]); | |
| 612 | - if( $intName !== '' | |
| 613 | - && (($isUser && !$this->ncUserManager->userExists($intName)) | |
| 614 | - || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName)) | |
| 615 | - ) | |
| 616 | -		) { | |
| 617 | - $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); | |
| 618 | - $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser); | |
| 619 | -			if($newlyMapped) { | |
| 620 | - return $intName; | |
| 621 | - } | |
| 622 | - } | |
| 623 | - | |
| 624 | - $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); | |
| 625 | - $altName = $this->createAltInternalOwnCloudName($intName, $isUser); | |
| 626 | -		if (is_string($altName)) { | |
| 627 | -			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { | |
| 628 | - $newlyMapped = true; | |
| 629 | - return $altName; | |
| 630 | - } | |
| 631 | - } | |
| 632 | - | |
| 633 | - //if everything else did not help.. | |
| 634 | -		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO); | |
| 635 | - return false; | |
| 636 | - } | |
| 637 | - | |
| 638 | - protected function mapAndAnnounceIfApplicable( | |
| 639 | - AbstractMapping $mapper, | |
| 640 | - string $fdn, | |
| 641 | - string $name, | |
| 642 | - string $uuid, | |
| 643 | - bool $isUser | |
| 644 | -	) :bool { | |
| 645 | -		if($mapper->map($fdn, $name, $uuid)) { | |
| 646 | -			if ($this->ncUserManager instanceof PublicEmitter && $isUser) { | |
| 647 | - $this->cacheUserExists($name); | |
| 648 | -				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]); | |
| 649 | - } | |
| 650 | - return true; | |
| 651 | - } | |
| 652 | - return false; | |
| 653 | - } | |
| 654 | - | |
| 655 | - /** | |
| 656 | - * gives back the user names as they are used ownClod internally | |
| 657 | - * @param array $ldapUsers as returned by fetchList() | |
| 658 | - * @return array an array with the user names to use in Nextcloud | |
| 659 | - * | |
| 660 | - * gives back the user names as they are used ownClod internally | |
| 661 | - */ | |
| 662 | -	public function nextcloudUserNames($ldapUsers) { | |
| 663 | - return $this->ldap2NextcloudNames($ldapUsers, true); | |
| 664 | - } | |
| 665 | - | |
| 666 | - /** | |
| 667 | - * gives back the group names as they are used ownClod internally | |
| 668 | - * @param array $ldapGroups as returned by fetchList() | |
| 669 | - * @return array an array with the group names to use in Nextcloud | |
| 670 | - * | |
| 671 | - * gives back the group names as they are used ownClod internally | |
| 672 | - */ | |
| 673 | -	public function nextcloudGroupNames($ldapGroups) { | |
| 674 | - return $this->ldap2NextcloudNames($ldapGroups, false); | |
| 675 | - } | |
| 676 | - | |
| 677 | - /** | |
| 678 | - * @param array $ldapObjects as returned by fetchList() | |
| 679 | - * @param bool $isUsers | |
| 680 | - * @return array | |
| 681 | - * @throws \Exception | |
| 682 | - */ | |
| 683 | -	private function ldap2NextcloudNames($ldapObjects, $isUsers) { | |
| 684 | -		if($isUsers) { | |
| 685 | - $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 686 | - $sndAttribute = $this->connection->ldapUserDisplayName2; | |
| 687 | -		} else { | |
| 688 | - $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 689 | - } | |
| 690 | - $nextcloudNames = []; | |
| 691 | - | |
| 692 | -		foreach($ldapObjects as $ldapObject) { | |
| 693 | - $nameByLDAP = null; | |
| 694 | - if( isset($ldapObject[$nameAttribute]) | |
| 695 | - && is_array($ldapObject[$nameAttribute]) | |
| 696 | - && isset($ldapObject[$nameAttribute][0]) | |
| 697 | -			) { | |
| 698 | - // might be set, but not necessarily. if so, we use it. | |
| 699 | - $nameByLDAP = $ldapObject[$nameAttribute][0]; | |
| 700 | - } | |
| 701 | - | |
| 702 | - $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); | |
| 703 | -			if($ncName) { | |
| 704 | - $nextcloudNames[] = $ncName; | |
| 705 | -				if($isUsers) { | |
| 706 | - $this->updateUserState($ncName); | |
| 707 | - //cache the user names so it does not need to be retrieved | |
| 708 | - //again later (e.g. sharing dialogue). | |
| 709 | -					if(is_null($nameByLDAP)) { | |
| 710 | - continue; | |
| 711 | - } | |
| 712 | - $sndName = isset($ldapObject[$sndAttribute][0]) | |
| 713 | - ? $ldapObject[$sndAttribute][0] : ''; | |
| 714 | - $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); | |
| 715 | -				} else if($nameByLDAP !== null) { | |
| 716 | - $this->cacheGroupDisplayName($ncName, $nameByLDAP); | |
| 717 | - } | |
| 718 | - } | |
| 719 | - } | |
| 720 | - return $nextcloudNames; | |
| 721 | - } | |
| 722 | - | |
| 723 | - /** | |
| 724 | - * removes the deleted-flag of a user if it was set | |
| 725 | - * | |
| 726 | - * @param string $ncname | |
| 727 | - * @throws \Exception | |
| 728 | - */ | |
| 729 | -	public function updateUserState($ncname) { | |
| 730 | - $user = $this->userManager->get($ncname); | |
| 731 | -		if($user instanceof OfflineUser) { | |
| 732 | - $user->unmark(); | |
| 733 | - } | |
| 734 | - } | |
| 735 | - | |
| 736 | - /** | |
| 737 | - * caches the user display name | |
| 738 | - * @param string $ocName the internal Nextcloud username | |
| 739 | - * @param string|false $home the home directory path | |
| 740 | - */ | |
| 741 | -	public function cacheUserHome($ocName, $home) { | |
| 742 | - $cacheKey = 'getHome'.$ocName; | |
| 743 | - $this->connection->writeToCache($cacheKey, $home); | |
| 744 | - } | |
| 745 | - | |
| 746 | - /** | |
| 747 | - * caches a user as existing | |
| 748 | - * @param string $ocName the internal Nextcloud username | |
| 749 | - */ | |
| 750 | -	public function cacheUserExists($ocName) { | |
| 751 | -		$this->connection->writeToCache('userExists'.$ocName, true); | |
| 752 | - } | |
| 753 | - | |
| 754 | - /** | |
| 755 | - * caches the user display name | |
| 756 | - * @param string $ocName the internal Nextcloud username | |
| 757 | - * @param string $displayName the display name | |
| 758 | - * @param string $displayName2 the second display name | |
| 759 | - */ | |
| 760 | -	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { | |
| 761 | - $user = $this->userManager->get($ocName); | |
| 762 | -		if($user === null) { | |
| 763 | - return; | |
| 764 | - } | |
| 765 | - $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); | |
| 766 | - $cacheKeyTrunk = 'getDisplayName'; | |
| 767 | - $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName); | |
| 768 | - } | |
| 769 | - | |
| 770 | -	public function cacheGroupDisplayName(string $ncName, string $displayName): void { | |
| 771 | - $cacheKey = 'group_getDisplayName' . $ncName; | |
| 772 | - $this->connection->writeToCache($cacheKey, $displayName); | |
| 773 | - } | |
| 774 | - | |
| 775 | - /** | |
| 776 | - * creates a unique name for internal Nextcloud use for users. Don't call it directly. | |
| 777 | - * @param string $name the display name of the object | |
| 778 | - * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 779 | - * | |
| 780 | - * Instead of using this method directly, call | |
| 781 | - * createAltInternalOwnCloudName($name, true) | |
| 782 | - */ | |
| 783 | -	private function _createAltInternalOwnCloudNameForUsers($name) { | |
| 784 | - $attempts = 0; | |
| 785 | - //while loop is just a precaution. If a name is not generated within | |
| 786 | - //20 attempts, something else is very wrong. Avoids infinite loop. | |
| 787 | -		while($attempts < 20){ | |
| 788 | - $altName = $name . '_' . rand(1000,9999); | |
| 789 | -			if(!$this->ncUserManager->userExists($altName)) { | |
| 790 | - return $altName; | |
| 791 | - } | |
| 792 | - $attempts++; | |
| 793 | - } | |
| 794 | - return false; | |
| 795 | - } | |
| 796 | - | |
| 797 | - /** | |
| 798 | - * creates a unique name for internal Nextcloud use for groups. Don't call it directly. | |
| 799 | - * @param string $name the display name of the object | |
| 800 | - * @return string|false with with the name to use in Nextcloud or false if unsuccessful. | |
| 801 | - * | |
| 802 | - * Instead of using this method directly, call | |
| 803 | - * createAltInternalOwnCloudName($name, false) | |
| 804 | - * | |
| 805 | - * Group names are also used as display names, so we do a sequential | |
| 806 | - * numbering, e.g. Developers_42 when there are 41 other groups called | |
| 807 | - * "Developers" | |
| 808 | - */ | |
| 809 | -	private function _createAltInternalOwnCloudNameForGroups($name) { | |
| 810 | - $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); | |
| 811 | -		if(!$usedNames || count($usedNames) === 0) { | |
| 812 | - $lastNo = 1; //will become name_2 | |
| 813 | -		} else { | |
| 814 | - natsort($usedNames); | |
| 815 | - $lastName = array_pop($usedNames); | |
| 816 | - $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1); | |
| 817 | - } | |
| 818 | - $altName = $name.'_'. (string)($lastNo+1); | |
| 819 | - unset($usedNames); | |
| 820 | - | |
| 821 | - $attempts = 1; | |
| 822 | -		while($attempts < 21){ | |
| 823 | - // Check to be really sure it is unique | |
| 824 | - // while loop is just a precaution. If a name is not generated within | |
| 825 | - // 20 attempts, something else is very wrong. Avoids infinite loop. | |
| 826 | -			if(!\OC::$server->getGroupManager()->groupExists($altName)) { | |
| 827 | - return $altName; | |
| 828 | - } | |
| 829 | - $altName = $name . '_' . ($lastNo + $attempts); | |
| 830 | - $attempts++; | |
| 831 | - } | |
| 832 | - return false; | |
| 833 | - } | |
| 834 | - | |
| 835 | - /** | |
| 836 | - * creates a unique name for internal Nextcloud use. | |
| 837 | - * @param string $name the display name of the object | |
| 838 | - * @param boolean $isUser whether name should be created for a user (true) or a group (false) | |
| 839 | - * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 840 | - */ | |
| 841 | -	private function createAltInternalOwnCloudName($name, $isUser) { | |
| 842 | - $originalTTL = $this->connection->ldapCacheTTL; | |
| 843 | -		$this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | |
| 844 | -		if($isUser) { | |
| 845 | - $altName = $this->_createAltInternalOwnCloudNameForUsers($name); | |
| 846 | -		} else { | |
| 847 | - $altName = $this->_createAltInternalOwnCloudNameForGroups($name); | |
| 848 | - } | |
| 849 | -		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 850 | - | |
| 851 | - return $altName; | |
| 852 | - } | |
| 853 | - | |
| 854 | - /** | |
| 855 | - * fetches a list of users according to a provided loginName and utilizing | |
| 856 | - * the login filter. | |
| 857 | - * | |
| 858 | - * @param string $loginName | |
| 859 | - * @param array $attributes optional, list of attributes to read | |
| 860 | - * @return array | |
| 861 | - */ | |
| 862 | -	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) { | |
| 863 | - $loginName = $this->escapeFilterPart($loginName); | |
| 864 | -		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 865 | - return $this->fetchListOfUsers($filter, $attributes); | |
| 866 | - } | |
| 867 | - | |
| 868 | - /** | |
| 869 | - * counts the number of users according to a provided loginName and | |
| 870 | - * utilizing the login filter. | |
| 871 | - * | |
| 872 | - * @param string $loginName | |
| 873 | - * @return int | |
| 874 | - */ | |
| 875 | -	public function countUsersByLoginName($loginName) { | |
| 876 | - $loginName = $this->escapeFilterPart($loginName); | |
| 877 | -		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 878 | - return $this->countUsers($filter); | |
| 879 | - } | |
| 880 | - | |
| 881 | - /** | |
| 882 | - * @param string $filter | |
| 883 | - * @param string|string[] $attr | |
| 884 | - * @param int $limit | |
| 885 | - * @param int $offset | |
| 886 | - * @param bool $forceApplyAttributes | |
| 887 | - * @return array | |
| 888 | - */ | |
| 889 | -	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) { | |
| 890 | - $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); | |
| 891 | - $recordsToUpdate = $ldapRecords; | |
| 892 | -		if(!$forceApplyAttributes) { | |
| 893 | - $isBackgroundJobModeAjax = $this->config | |
| 894 | -					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; | |
| 895 | -			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) { | |
| 896 | - $newlyMapped = false; | |
| 897 | - $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record); | |
| 898 | -				if(is_string($uid)) { | |
| 899 | - $this->cacheUserExists($uid); | |
| 900 | - } | |
| 901 | - return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax); | |
| 902 | - }); | |
| 903 | - } | |
| 904 | - $this->batchApplyUserAttributes($recordsToUpdate); | |
| 905 | - return $this->fetchList($ldapRecords, $this->manyAttributes($attr)); | |
| 906 | - } | |
| 907 | - | |
| 908 | - /** | |
| 909 | - * provided with an array of LDAP user records the method will fetch the | |
| 910 | - * user object and requests it to process the freshly fetched attributes and | |
| 911 | - * and their values | |
| 912 | - * | |
| 913 | - * @param array $ldapRecords | |
| 914 | - * @throws \Exception | |
| 915 | - */ | |
| 916 | -	public function batchApplyUserAttributes(array $ldapRecords){ | |
| 917 | - $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); | |
| 918 | -		foreach($ldapRecords as $userRecord) { | |
| 919 | -			if(!isset($userRecord[$displayNameAttribute])) { | |
| 920 | - // displayName is obligatory | |
| 921 | - continue; | |
| 922 | - } | |
| 923 | - $ocName = $this->dn2ocname($userRecord['dn'][0], null, true); | |
| 924 | -			if($ocName === false) { | |
| 925 | - continue; | |
| 926 | - } | |
| 927 | - $this->updateUserState($ocName); | |
| 928 | - $user = $this->userManager->get($ocName); | |
| 929 | -			if ($user !== null) { | |
| 930 | - $user->processAttributes($userRecord); | |
| 931 | -			} else { | |
| 932 | - \OC::$server->getLogger()->debug( | |
| 933 | - "The ldap user manager returned null for $ocName", | |
| 934 | - ['app'=>'user_ldap'] | |
| 935 | - ); | |
| 936 | - } | |
| 937 | - } | |
| 938 | - } | |
| 939 | - | |
| 940 | - /** | |
| 941 | - * @param string $filter | |
| 942 | - * @param string|string[] $attr | |
| 943 | - * @param int $limit | |
| 944 | - * @param int $offset | |
| 945 | - * @return array | |
| 946 | - */ | |
| 947 | -	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) { | |
| 948 | - return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), $this->manyAttributes($attr)); | |
| 949 | - } | |
| 950 | - | |
| 951 | - /** | |
| 952 | - * @param array $list | |
| 953 | - * @param bool $manyAttributes | |
| 954 | - * @return array | |
| 955 | - */ | |
| 956 | -	private function fetchList($list, $manyAttributes) { | |
| 957 | -		if(is_array($list)) { | |
| 958 | -			if($manyAttributes) { | |
| 959 | - return $list; | |
| 960 | -			} else { | |
| 961 | -				$list = array_reduce($list, function($carry, $item) { | |
| 962 | - $attribute = array_keys($item)[0]; | |
| 963 | - $carry[] = $item[$attribute][0]; | |
| 964 | - return $carry; | |
| 965 | - }, array()); | |
| 966 | - return array_unique($list, SORT_LOCALE_STRING); | |
| 967 | - } | |
| 968 | - } | |
| 969 | - | |
| 970 | - //error cause actually, maybe throw an exception in future. | |
| 971 | - return array(); | |
| 972 | - } | |
| 973 | - | |
| 974 | - /** | |
| 975 | - * executes an LDAP search, optimized for Users | |
| 976 | - * @param string $filter the LDAP filter for the search | |
| 977 | - * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 978 | - * @param integer $limit | |
| 979 | - * @param integer $offset | |
| 980 | - * @return array with the search result | |
| 981 | - * | |
| 982 | - * Executes an LDAP search | |
| 983 | - */ | |
| 984 | -	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { | |
| 985 | - $result = []; | |
| 986 | -		foreach($this->connection->ldapBaseUsers as $base) { | |
| 987 | - $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); | |
| 988 | - } | |
| 989 | - return $result; | |
| 990 | - } | |
| 991 | - | |
| 992 | - /** | |
| 993 | - * @param string $filter | |
| 994 | - * @param string|string[] $attr | |
| 995 | - * @param int $limit | |
| 996 | - * @param int $offset | |
| 997 | - * @return false|int | |
| 998 | - */ | |
| 999 | -	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 1000 | - $result = false; | |
| 1001 | -		foreach($this->connection->ldapBaseUsers as $base) { | |
| 1002 | - $count = $this->count($filter, [$base], $attr, $limit, $offset); | |
| 1003 | - $result = is_int($count) ? (int)$result + $count : $result; | |
| 1004 | - } | |
| 1005 | - return $result; | |
| 1006 | - } | |
| 1007 | - | |
| 1008 | - /** | |
| 1009 | - * executes an LDAP search, optimized for Groups | |
| 1010 | - * @param string $filter the LDAP filter for the search | |
| 1011 | - * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 1012 | - * @param integer $limit | |
| 1013 | - * @param integer $offset | |
| 1014 | - * @return array with the search result | |
| 1015 | - * | |
| 1016 | - * Executes an LDAP search | |
| 1017 | - */ | |
| 1018 | -	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { | |
| 1019 | - $result = []; | |
| 1020 | -		foreach($this->connection->ldapBaseGroups as $base) { | |
| 1021 | - $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); | |
| 1022 | - } | |
| 1023 | - return $result; | |
| 1024 | - } | |
| 1025 | - | |
| 1026 | - /** | |
| 1027 | - * returns the number of available groups | |
| 1028 | - * @param string $filter the LDAP search filter | |
| 1029 | - * @param string[] $attr optional | |
| 1030 | - * @param int|null $limit | |
| 1031 | - * @param int|null $offset | |
| 1032 | - * @return int|bool | |
| 1033 | - */ | |
| 1034 | -	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 1035 | - $result = false; | |
| 1036 | -		foreach($this->connection->ldapBaseGroups as $base) { | |
| 1037 | - $count = $this->count($filter, [$base], $attr, $limit, $offset); | |
| 1038 | - $result = is_int($count) ? (int)$result + $count : $result; | |
| 1039 | - } | |
| 1040 | - return $result; | |
| 1041 | - } | |
| 1042 | - | |
| 1043 | - /** | |
| 1044 | - * returns the number of available objects on the base DN | |
| 1045 | - * | |
| 1046 | - * @param int|null $limit | |
| 1047 | - * @param int|null $offset | |
| 1048 | - * @return int|bool | |
| 1049 | - */ | |
| 1050 | -	public function countObjects($limit = null, $offset = null) { | |
| 1051 | - $result = false; | |
| 1052 | -		foreach($this->connection->ldapBase as $base) { | |
| 1053 | -			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset); | |
| 1054 | - $result = is_int($count) ? (int)$result + $count : $result; | |
| 1055 | - } | |
| 1056 | - return $result; | |
| 1057 | - } | |
| 1058 | - | |
| 1059 | - /** | |
| 1060 | - * Returns the LDAP handler | |
| 1061 | - * @throws \OC\ServerNotAvailableException | |
| 1062 | - */ | |
| 1063 | - | |
| 1064 | - /** | |
| 1065 | - * @return mixed | |
| 1066 | - * @throws \OC\ServerNotAvailableException | |
| 1067 | - */ | |
| 1068 | -	private function invokeLDAPMethod() { | |
| 1069 | - $arguments = func_get_args(); | |
| 1070 | - $command = array_shift($arguments); | |
| 1071 | - $cr = array_shift($arguments); | |
| 1072 | -		if (!method_exists($this->ldap, $command)) { | |
| 1073 | - return null; | |
| 1074 | - } | |
| 1075 | - array_unshift($arguments, $cr); | |
| 1076 | - // php no longer supports call-time pass-by-reference | |
| 1077 | - // thus cannot support controlPagedResultResponse as the third argument | |
| 1078 | - // is a reference | |
| 1079 | -		$doMethod = function () use ($command, &$arguments) { | |
| 1080 | -			if ($command == 'controlPagedResultResponse') { | |
| 1081 | -				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.'); | |
| 1082 | -			} else { | |
| 1083 | - return call_user_func_array(array($this->ldap, $command), $arguments); | |
| 1084 | - } | |
| 1085 | - }; | |
| 1086 | -		try { | |
| 1087 | - $ret = $doMethod(); | |
| 1088 | -		} catch (ServerNotAvailableException $e) { | |
| 1089 | - /* Server connection lost, attempt to reestablish it | |
| 349 | + /** | |
| 350 | + * Set password for an LDAP user identified by a DN | |
| 351 | + * | |
| 352 | + * @param string $userDN the user in question | |
| 353 | + * @param string $password the new password | |
| 354 | + * @return bool | |
| 355 | + * @throws HintException | |
| 356 | + * @throws \Exception | |
| 357 | + */ | |
| 358 | +    public function setPassword($userDN, $password) { | |
| 359 | +        if((int)$this->connection->turnOnPasswordChange !== 1) { | |
| 360 | +            throw new \Exception('LDAP password changes are disabled.'); | |
| 361 | + } | |
| 362 | + $cr = $this->connection->getConnectionResource(); | |
| 363 | +        if(!$this->ldap->isResource($cr)) { | |
| 364 | + //LDAP not available | |
| 365 | +            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); | |
| 366 | + return false; | |
| 367 | + } | |
| 368 | +        try { | |
| 369 | +            return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); | |
| 370 | +        } catch(ConstraintViolationException $e) { | |
| 371 | +            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); | |
| 372 | + } | |
| 373 | + } | |
| 374 | + | |
| 375 | + /** | |
| 376 | + * checks whether the given attributes value is probably a DN | |
| 377 | + * @param string $attr the attribute in question | |
| 378 | + * @return boolean if so true, otherwise false | |
| 379 | + */ | |
| 380 | +    private function resemblesDN($attr) { | |
| 381 | + $resemblingAttributes = array( | |
| 382 | + 'dn', | |
| 383 | + 'uniquemember', | |
| 384 | + 'member', | |
| 385 | + // memberOf is an "operational" attribute, without a definition in any RFC | |
| 386 | + 'memberof' | |
| 387 | + ); | |
| 388 | + return in_array($attr, $resemblingAttributes); | |
| 389 | + } | |
| 390 | + | |
| 391 | + /** | |
| 392 | + * checks whether the given string is probably a DN | |
| 393 | + * @param string $string | |
| 394 | + * @return boolean | |
| 395 | + */ | |
| 396 | +    public function stringResemblesDN($string) { | |
| 397 | + $r = $this->ldap->explodeDN($string, 0); | |
| 398 | + // if exploding a DN succeeds and does not end up in | |
| 399 | + // an empty array except for $r[count] being 0. | |
| 400 | + return (is_array($r) && count($r) > 1); | |
| 401 | + } | |
| 402 | + | |
| 403 | + /** | |
| 404 | + * returns a DN-string that is cleaned from not domain parts, e.g. | |
| 405 | + * cn=foo,cn=bar,dc=foobar,dc=server,dc=org | |
| 406 | + * becomes dc=foobar,dc=server,dc=org | |
| 407 | + * @param string $dn | |
| 408 | + * @return string | |
| 409 | + */ | |
| 410 | +    public function getDomainDNFromDN($dn) { | |
| 411 | + $allParts = $this->ldap->explodeDN($dn, 0); | |
| 412 | +        if($allParts === false) { | |
| 413 | + //not a valid DN | |
| 414 | + return ''; | |
| 415 | + } | |
| 416 | + $domainParts = array(); | |
| 417 | + $dcFound = false; | |
| 418 | +        foreach($allParts as $part) { | |
| 419 | +            if(!$dcFound && strpos($part, 'dc=') === 0) { | |
| 420 | + $dcFound = true; | |
| 421 | + } | |
| 422 | +            if($dcFound) { | |
| 423 | + $domainParts[] = $part; | |
| 424 | + } | |
| 425 | + } | |
| 426 | +        return implode(',', $domainParts); | |
| 427 | + } | |
| 428 | + | |
| 429 | + /** | |
| 430 | + * returns the LDAP DN for the given internal Nextcloud name of the group | |
| 431 | + * @param string $name the Nextcloud name in question | |
| 432 | + * @return string|false LDAP DN on success, otherwise false | |
| 433 | + */ | |
| 434 | +    public function groupname2dn($name) { | |
| 435 | + return $this->groupMapper->getDNByName($name); | |
| 436 | + } | |
| 437 | + | |
| 438 | + /** | |
| 439 | + * returns the LDAP DN for the given internal Nextcloud name of the user | |
| 440 | + * @param string $name the Nextcloud name in question | |
| 441 | + * @return string|false with the LDAP DN on success, otherwise false | |
| 442 | + */ | |
| 443 | +    public function username2dn($name) { | |
| 444 | + $fdn = $this->userMapper->getDNByName($name); | |
| 445 | + | |
| 446 | + //Check whether the DN belongs to the Base, to avoid issues on multi- | |
| 447 | + //server setups | |
| 448 | +        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 449 | + return $fdn; | |
| 450 | + } | |
| 451 | + | |
| 452 | + return false; | |
| 453 | + } | |
| 454 | + | |
| 455 | + /** | |
| 456 | + * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure | |
| 457 | + * @param string $fdn the dn of the group object | |
| 458 | + * @param string $ldapName optional, the display name of the object | |
| 459 | + * @return string|false with the name to use in Nextcloud, false on DN outside of search DN | |
| 460 | + */ | |
| 461 | +    public function dn2groupname($fdn, $ldapName = null) { | |
| 462 | + //To avoid bypassing the base DN settings under certain circumstances | |
| 463 | + //with the group support, check whether the provided DN matches one of | |
| 464 | + //the given Bases | |
| 465 | +        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { | |
| 466 | + return false; | |
| 467 | + } | |
| 468 | + | |
| 469 | + return $this->dn2ocname($fdn, $ldapName, false); | |
| 470 | + } | |
| 471 | + | |
| 472 | + /** | |
| 473 | + * accepts an array of group DNs and tests whether they match the user | |
| 474 | + * filter by doing read operations against the group entries. Returns an | |
| 475 | + * array of DNs that match the filter. | |
| 476 | + * | |
| 477 | + * @param string[] $groupDNs | |
| 478 | + * @return string[] | |
| 479 | + * @throws ServerNotAvailableException | |
| 480 | + */ | |
| 481 | +    public function groupsMatchFilter($groupDNs) { | |
| 482 | + $validGroupDNs = []; | |
| 483 | +        foreach($groupDNs as $dn) { | |
| 484 | + $cacheKey = 'groupsMatchFilter-'.$dn; | |
| 485 | + $groupMatchFilter = $this->connection->getFromCache($cacheKey); | |
| 486 | +            if(!is_null($groupMatchFilter)) { | |
| 487 | +                if($groupMatchFilter) { | |
| 488 | + $validGroupDNs[] = $dn; | |
| 489 | + } | |
| 490 | + continue; | |
| 491 | + } | |
| 492 | + | |
| 493 | + // Check the base DN first. If this is not met already, we don't | |
| 494 | + // need to ask the server at all. | |
| 495 | +            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { | |
| 496 | + $this->connection->writeToCache($cacheKey, false); | |
| 497 | + continue; | |
| 498 | + } | |
| 499 | + | |
| 500 | + $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter); | |
| 501 | +            if(is_array($result)) { | |
| 502 | + $this->connection->writeToCache($cacheKey, true); | |
| 503 | + $validGroupDNs[] = $dn; | |
| 504 | +            } else { | |
| 505 | + $this->connection->writeToCache($cacheKey, false); | |
| 506 | + } | |
| 507 | + | |
| 508 | + } | |
| 509 | + return $validGroupDNs; | |
| 510 | + } | |
| 511 | + | |
| 512 | + /** | |
| 513 | + * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure | |
| 514 | + * @param string $dn the dn of the user object | |
| 515 | + * @param string $ldapName optional, the display name of the object | |
| 516 | + * @return string|false with with the name to use in Nextcloud | |
| 517 | + */ | |
| 518 | +    public function dn2username($fdn, $ldapName = null) { | |
| 519 | + //To avoid bypassing the base DN settings under certain circumstances | |
| 520 | + //with the group support, check whether the provided DN matches one of | |
| 521 | + //the given Bases | |
| 522 | +        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 523 | + return false; | |
| 524 | + } | |
| 525 | + | |
| 526 | + return $this->dn2ocname($fdn, $ldapName, true); | |
| 527 | + } | |
| 528 | + | |
| 529 | + /** | |
| 530 | + * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN | |
| 531 | + * | |
| 532 | + * @param string $fdn the dn of the user object | |
| 533 | + * @param string|null $ldapName optional, the display name of the object | |
| 534 | + * @param bool $isUser optional, whether it is a user object (otherwise group assumed) | |
| 535 | + * @param bool|null $newlyMapped | |
| 536 | + * @param array|null $record | |
| 537 | + * @return false|string with with the name to use in Nextcloud | |
| 538 | + * @throws \Exception | |
| 539 | + */ | |
| 540 | +    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) { | |
| 541 | + $newlyMapped = false; | |
| 542 | +        if($isUser) { | |
| 543 | + $mapper = $this->getUserMapper(); | |
| 544 | + $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 545 | + $filter = $this->connection->ldapUserFilter; | |
| 546 | +        } else { | |
| 547 | + $mapper = $this->getGroupMapper(); | |
| 548 | + $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 549 | + $filter = $this->connection->ldapGroupFilter; | |
| 550 | + } | |
| 551 | + | |
| 552 | + //let's try to retrieve the Nextcloud name from the mappings table | |
| 553 | + $ncName = $mapper->getNameByDN($fdn); | |
| 554 | +        if(is_string($ncName)) { | |
| 555 | + return $ncName; | |
| 556 | + } | |
| 557 | + | |
| 558 | + //second try: get the UUID and check if it is known. Then, update the DN and return the name. | |
| 559 | + $uuid = $this->getUUID($fdn, $isUser, $record); | |
| 560 | +        if(is_string($uuid)) { | |
| 561 | + $ncName = $mapper->getNameByUUID($uuid); | |
| 562 | +            if(is_string($ncName)) { | |
| 563 | + $mapper->setDNbyUUID($fdn, $uuid); | |
| 564 | + return $ncName; | |
| 565 | + } | |
| 566 | +        } else { | |
| 567 | + //If the UUID can't be detected something is foul. | |
| 568 | +            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO); | |
| 569 | + return false; | |
| 570 | + } | |
| 571 | + | |
| 572 | +        if(is_null($ldapName)) { | |
| 573 | + $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter); | |
| 574 | +            if(!isset($ldapName[0]) && empty($ldapName[0])) { | |
| 575 | +                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO); | |
| 576 | + return false; | |
| 577 | + } | |
| 578 | + $ldapName = $ldapName[0]; | |
| 579 | + } | |
| 580 | + | |
| 581 | +        if($isUser) { | |
| 582 | + $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr; | |
| 583 | +            if ($usernameAttribute !== '') { | |
| 584 | + $username = $this->readAttribute($fdn, $usernameAttribute); | |
| 585 | + $username = $username[0]; | |
| 586 | +            } else { | |
| 587 | + $username = $uuid; | |
| 588 | + } | |
| 589 | +            try { | |
| 590 | + $intName = $this->sanitizeUsername($username); | |
| 591 | +            } catch (\InvalidArgumentException $e) { | |
| 592 | + \OC::$server->getLogger()->logException($e, [ | |
| 593 | + 'app' => 'user_ldap', | |
| 594 | + 'level' => ILogger::WARN, | |
| 595 | + ]); | |
| 596 | + // we don't attempt to set a username here. We can go for | |
| 597 | + // for an alternative 4 digit random number as we would append | |
| 598 | + // otherwise, however it's likely not enough space in bigger | |
| 599 | + // setups, and most importantly: this is not intended. | |
| 600 | + return false; | |
| 601 | + } | |
| 602 | +        } else { | |
| 603 | + $intName = $ldapName; | |
| 604 | + } | |
| 605 | + | |
| 606 | + //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups | |
| 607 | + //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check | |
| 608 | + //NOTE: mind, disabling cache affects only this instance! Using it | |
| 609 | + // outside of core user management will still cache the user as non-existing. | |
| 610 | + $originalTTL = $this->connection->ldapCacheTTL; | |
| 611 | + $this->connection->setConfiguration(['ldapCacheTTL' => 0]); | |
| 612 | + if( $intName !== '' | |
| 613 | + && (($isUser && !$this->ncUserManager->userExists($intName)) | |
| 614 | + || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName)) | |
| 615 | + ) | |
| 616 | +        ) { | |
| 617 | + $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); | |
| 618 | + $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser); | |
| 619 | +            if($newlyMapped) { | |
| 620 | + return $intName; | |
| 621 | + } | |
| 622 | + } | |
| 623 | + | |
| 624 | + $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); | |
| 625 | + $altName = $this->createAltInternalOwnCloudName($intName, $isUser); | |
| 626 | +        if (is_string($altName)) { | |
| 627 | +            if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { | |
| 628 | + $newlyMapped = true; | |
| 629 | + return $altName; | |
| 630 | + } | |
| 631 | + } | |
| 632 | + | |
| 633 | + //if everything else did not help.. | |
| 634 | +        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO); | |
| 635 | + return false; | |
| 636 | + } | |
| 637 | + | |
| 638 | + protected function mapAndAnnounceIfApplicable( | |
| 639 | + AbstractMapping $mapper, | |
| 640 | + string $fdn, | |
| 641 | + string $name, | |
| 642 | + string $uuid, | |
| 643 | + bool $isUser | |
| 644 | +    ) :bool { | |
| 645 | +        if($mapper->map($fdn, $name, $uuid)) { | |
| 646 | +            if ($this->ncUserManager instanceof PublicEmitter && $isUser) { | |
| 647 | + $this->cacheUserExists($name); | |
| 648 | +                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]); | |
| 649 | + } | |
| 650 | + return true; | |
| 651 | + } | |
| 652 | + return false; | |
| 653 | + } | |
| 654 | + | |
| 655 | + /** | |
| 656 | + * gives back the user names as they are used ownClod internally | |
| 657 | + * @param array $ldapUsers as returned by fetchList() | |
| 658 | + * @return array an array with the user names to use in Nextcloud | |
| 659 | + * | |
| 660 | + * gives back the user names as they are used ownClod internally | |
| 661 | + */ | |
| 662 | +    public function nextcloudUserNames($ldapUsers) { | |
| 663 | + return $this->ldap2NextcloudNames($ldapUsers, true); | |
| 664 | + } | |
| 665 | + | |
| 666 | + /** | |
| 667 | + * gives back the group names as they are used ownClod internally | |
| 668 | + * @param array $ldapGroups as returned by fetchList() | |
| 669 | + * @return array an array with the group names to use in Nextcloud | |
| 670 | + * | |
| 671 | + * gives back the group names as they are used ownClod internally | |
| 672 | + */ | |
| 673 | +    public function nextcloudGroupNames($ldapGroups) { | |
| 674 | + return $this->ldap2NextcloudNames($ldapGroups, false); | |
| 675 | + } | |
| 676 | + | |
| 677 | + /** | |
| 678 | + * @param array $ldapObjects as returned by fetchList() | |
| 679 | + * @param bool $isUsers | |
| 680 | + * @return array | |
| 681 | + * @throws \Exception | |
| 682 | + */ | |
| 683 | +    private function ldap2NextcloudNames($ldapObjects, $isUsers) { | |
| 684 | +        if($isUsers) { | |
| 685 | + $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 686 | + $sndAttribute = $this->connection->ldapUserDisplayName2; | |
| 687 | +        } else { | |
| 688 | + $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 689 | + } | |
| 690 | + $nextcloudNames = []; | |
| 691 | + | |
| 692 | +        foreach($ldapObjects as $ldapObject) { | |
| 693 | + $nameByLDAP = null; | |
| 694 | + if( isset($ldapObject[$nameAttribute]) | |
| 695 | + && is_array($ldapObject[$nameAttribute]) | |
| 696 | + && isset($ldapObject[$nameAttribute][0]) | |
| 697 | +            ) { | |
| 698 | + // might be set, but not necessarily. if so, we use it. | |
| 699 | + $nameByLDAP = $ldapObject[$nameAttribute][0]; | |
| 700 | + } | |
| 701 | + | |
| 702 | + $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); | |
| 703 | +            if($ncName) { | |
| 704 | + $nextcloudNames[] = $ncName; | |
| 705 | +                if($isUsers) { | |
| 706 | + $this->updateUserState($ncName); | |
| 707 | + //cache the user names so it does not need to be retrieved | |
| 708 | + //again later (e.g. sharing dialogue). | |
| 709 | +                    if(is_null($nameByLDAP)) { | |
| 710 | + continue; | |
| 711 | + } | |
| 712 | + $sndName = isset($ldapObject[$sndAttribute][0]) | |
| 713 | + ? $ldapObject[$sndAttribute][0] : ''; | |
| 714 | + $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); | |
| 715 | +                } else if($nameByLDAP !== null) { | |
| 716 | + $this->cacheGroupDisplayName($ncName, $nameByLDAP); | |
| 717 | + } | |
| 718 | + } | |
| 719 | + } | |
| 720 | + return $nextcloudNames; | |
| 721 | + } | |
| 722 | + | |
| 723 | + /** | |
| 724 | + * removes the deleted-flag of a user if it was set | |
| 725 | + * | |
| 726 | + * @param string $ncname | |
| 727 | + * @throws \Exception | |
| 728 | + */ | |
| 729 | +    public function updateUserState($ncname) { | |
| 730 | + $user = $this->userManager->get($ncname); | |
| 731 | +        if($user instanceof OfflineUser) { | |
| 732 | + $user->unmark(); | |
| 733 | + } | |
| 734 | + } | |
| 735 | + | |
| 736 | + /** | |
| 737 | + * caches the user display name | |
| 738 | + * @param string $ocName the internal Nextcloud username | |
| 739 | + * @param string|false $home the home directory path | |
| 740 | + */ | |
| 741 | +    public function cacheUserHome($ocName, $home) { | |
| 742 | + $cacheKey = 'getHome'.$ocName; | |
| 743 | + $this->connection->writeToCache($cacheKey, $home); | |
| 744 | + } | |
| 745 | + | |
| 746 | + /** | |
| 747 | + * caches a user as existing | |
| 748 | + * @param string $ocName the internal Nextcloud username | |
| 749 | + */ | |
| 750 | +    public function cacheUserExists($ocName) { | |
| 751 | +        $this->connection->writeToCache('userExists'.$ocName, true); | |
| 752 | + } | |
| 753 | + | |
| 754 | + /** | |
| 755 | + * caches the user display name | |
| 756 | + * @param string $ocName the internal Nextcloud username | |
| 757 | + * @param string $displayName the display name | |
| 758 | + * @param string $displayName2 the second display name | |
| 759 | + */ | |
| 760 | +    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { | |
| 761 | + $user = $this->userManager->get($ocName); | |
| 762 | +        if($user === null) { | |
| 763 | + return; | |
| 764 | + } | |
| 765 | + $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); | |
| 766 | + $cacheKeyTrunk = 'getDisplayName'; | |
| 767 | + $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName); | |
| 768 | + } | |
| 769 | + | |
| 770 | +    public function cacheGroupDisplayName(string $ncName, string $displayName): void { | |
| 771 | + $cacheKey = 'group_getDisplayName' . $ncName; | |
| 772 | + $this->connection->writeToCache($cacheKey, $displayName); | |
| 773 | + } | |
| 774 | + | |
| 775 | + /** | |
| 776 | + * creates a unique name for internal Nextcloud use for users. Don't call it directly. | |
| 777 | + * @param string $name the display name of the object | |
| 778 | + * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 779 | + * | |
| 780 | + * Instead of using this method directly, call | |
| 781 | + * createAltInternalOwnCloudName($name, true) | |
| 782 | + */ | |
| 783 | +    private function _createAltInternalOwnCloudNameForUsers($name) { | |
| 784 | + $attempts = 0; | |
| 785 | + //while loop is just a precaution. If a name is not generated within | |
| 786 | + //20 attempts, something else is very wrong. Avoids infinite loop. | |
| 787 | +        while($attempts < 20){ | |
| 788 | + $altName = $name . '_' . rand(1000,9999); | |
| 789 | +            if(!$this->ncUserManager->userExists($altName)) { | |
| 790 | + return $altName; | |
| 791 | + } | |
| 792 | + $attempts++; | |
| 793 | + } | |
| 794 | + return false; | |
| 795 | + } | |
| 796 | + | |
| 797 | + /** | |
| 798 | + * creates a unique name for internal Nextcloud use for groups. Don't call it directly. | |
| 799 | + * @param string $name the display name of the object | |
| 800 | + * @return string|false with with the name to use in Nextcloud or false if unsuccessful. | |
| 801 | + * | |
| 802 | + * Instead of using this method directly, call | |
| 803 | + * createAltInternalOwnCloudName($name, false) | |
| 804 | + * | |
| 805 | + * Group names are also used as display names, so we do a sequential | |
| 806 | + * numbering, e.g. Developers_42 when there are 41 other groups called | |
| 807 | + * "Developers" | |
| 808 | + */ | |
| 809 | +    private function _createAltInternalOwnCloudNameForGroups($name) { | |
| 810 | + $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); | |
| 811 | +        if(!$usedNames || count($usedNames) === 0) { | |
| 812 | + $lastNo = 1; //will become name_2 | |
| 813 | +        } else { | |
| 814 | + natsort($usedNames); | |
| 815 | + $lastName = array_pop($usedNames); | |
| 816 | + $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1); | |
| 817 | + } | |
| 818 | + $altName = $name.'_'. (string)($lastNo+1); | |
| 819 | + unset($usedNames); | |
| 820 | + | |
| 821 | + $attempts = 1; | |
| 822 | +        while($attempts < 21){ | |
| 823 | + // Check to be really sure it is unique | |
| 824 | + // while loop is just a precaution. If a name is not generated within | |
| 825 | + // 20 attempts, something else is very wrong. Avoids infinite loop. | |
| 826 | +            if(!\OC::$server->getGroupManager()->groupExists($altName)) { | |
| 827 | + return $altName; | |
| 828 | + } | |
| 829 | + $altName = $name . '_' . ($lastNo + $attempts); | |
| 830 | + $attempts++; | |
| 831 | + } | |
| 832 | + return false; | |
| 833 | + } | |
| 834 | + | |
| 835 | + /** | |
| 836 | + * creates a unique name for internal Nextcloud use. | |
| 837 | + * @param string $name the display name of the object | |
| 838 | + * @param boolean $isUser whether name should be created for a user (true) or a group (false) | |
| 839 | + * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 840 | + */ | |
| 841 | +    private function createAltInternalOwnCloudName($name, $isUser) { | |
| 842 | + $originalTTL = $this->connection->ldapCacheTTL; | |
| 843 | +        $this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | |
| 844 | +        if($isUser) { | |
| 845 | + $altName = $this->_createAltInternalOwnCloudNameForUsers($name); | |
| 846 | +        } else { | |
| 847 | + $altName = $this->_createAltInternalOwnCloudNameForGroups($name); | |
| 848 | + } | |
| 849 | +        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 850 | + | |
| 851 | + return $altName; | |
| 852 | + } | |
| 853 | + | |
| 854 | + /** | |
| 855 | + * fetches a list of users according to a provided loginName and utilizing | |
| 856 | + * the login filter. | |
| 857 | + * | |
| 858 | + * @param string $loginName | |
| 859 | + * @param array $attributes optional, list of attributes to read | |
| 860 | + * @return array | |
| 861 | + */ | |
| 862 | +    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) { | |
| 863 | + $loginName = $this->escapeFilterPart($loginName); | |
| 864 | +        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 865 | + return $this->fetchListOfUsers($filter, $attributes); | |
| 866 | + } | |
| 867 | + | |
| 868 | + /** | |
| 869 | + * counts the number of users according to a provided loginName and | |
| 870 | + * utilizing the login filter. | |
| 871 | + * | |
| 872 | + * @param string $loginName | |
| 873 | + * @return int | |
| 874 | + */ | |
| 875 | +    public function countUsersByLoginName($loginName) { | |
| 876 | + $loginName = $this->escapeFilterPart($loginName); | |
| 877 | +        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 878 | + return $this->countUsers($filter); | |
| 879 | + } | |
| 880 | + | |
| 881 | + /** | |
| 882 | + * @param string $filter | |
| 883 | + * @param string|string[] $attr | |
| 884 | + * @param int $limit | |
| 885 | + * @param int $offset | |
| 886 | + * @param bool $forceApplyAttributes | |
| 887 | + * @return array | |
| 888 | + */ | |
| 889 | +    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) { | |
| 890 | + $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); | |
| 891 | + $recordsToUpdate = $ldapRecords; | |
| 892 | +        if(!$forceApplyAttributes) { | |
| 893 | + $isBackgroundJobModeAjax = $this->config | |
| 894 | +                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; | |
| 895 | +            $recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) { | |
| 896 | + $newlyMapped = false; | |
| 897 | + $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record); | |
| 898 | +                if(is_string($uid)) { | |
| 899 | + $this->cacheUserExists($uid); | |
| 900 | + } | |
| 901 | + return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax); | |
| 902 | + }); | |
| 903 | + } | |
| 904 | + $this->batchApplyUserAttributes($recordsToUpdate); | |
| 905 | + return $this->fetchList($ldapRecords, $this->manyAttributes($attr)); | |
| 906 | + } | |
| 907 | + | |
| 908 | + /** | |
| 909 | + * provided with an array of LDAP user records the method will fetch the | |
| 910 | + * user object and requests it to process the freshly fetched attributes and | |
| 911 | + * and their values | |
| 912 | + * | |
| 913 | + * @param array $ldapRecords | |
| 914 | + * @throws \Exception | |
| 915 | + */ | |
| 916 | +    public function batchApplyUserAttributes(array $ldapRecords){ | |
| 917 | + $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); | |
| 918 | +        foreach($ldapRecords as $userRecord) { | |
| 919 | +            if(!isset($userRecord[$displayNameAttribute])) { | |
| 920 | + // displayName is obligatory | |
| 921 | + continue; | |
| 922 | + } | |
| 923 | + $ocName = $this->dn2ocname($userRecord['dn'][0], null, true); | |
| 924 | +            if($ocName === false) { | |
| 925 | + continue; | |
| 926 | + } | |
| 927 | + $this->updateUserState($ocName); | |
| 928 | + $user = $this->userManager->get($ocName); | |
| 929 | +            if ($user !== null) { | |
| 930 | + $user->processAttributes($userRecord); | |
| 931 | +            } else { | |
| 932 | + \OC::$server->getLogger()->debug( | |
| 933 | + "The ldap user manager returned null for $ocName", | |
| 934 | + ['app'=>'user_ldap'] | |
| 935 | + ); | |
| 936 | + } | |
| 937 | + } | |
| 938 | + } | |
| 939 | + | |
| 940 | + /** | |
| 941 | + * @param string $filter | |
| 942 | + * @param string|string[] $attr | |
| 943 | + * @param int $limit | |
| 944 | + * @param int $offset | |
| 945 | + * @return array | |
| 946 | + */ | |
| 947 | +    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) { | |
| 948 | + return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), $this->manyAttributes($attr)); | |
| 949 | + } | |
| 950 | + | |
| 951 | + /** | |
| 952 | + * @param array $list | |
| 953 | + * @param bool $manyAttributes | |
| 954 | + * @return array | |
| 955 | + */ | |
| 956 | +    private function fetchList($list, $manyAttributes) { | |
| 957 | +        if(is_array($list)) { | |
| 958 | +            if($manyAttributes) { | |
| 959 | + return $list; | |
| 960 | +            } else { | |
| 961 | +                $list = array_reduce($list, function($carry, $item) { | |
| 962 | + $attribute = array_keys($item)[0]; | |
| 963 | + $carry[] = $item[$attribute][0]; | |
| 964 | + return $carry; | |
| 965 | + }, array()); | |
| 966 | + return array_unique($list, SORT_LOCALE_STRING); | |
| 967 | + } | |
| 968 | + } | |
| 969 | + | |
| 970 | + //error cause actually, maybe throw an exception in future. | |
| 971 | + return array(); | |
| 972 | + } | |
| 973 | + | |
| 974 | + /** | |
| 975 | + * executes an LDAP search, optimized for Users | |
| 976 | + * @param string $filter the LDAP filter for the search | |
| 977 | + * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 978 | + * @param integer $limit | |
| 979 | + * @param integer $offset | |
| 980 | + * @return array with the search result | |
| 981 | + * | |
| 982 | + * Executes an LDAP search | |
| 983 | + */ | |
| 984 | +    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { | |
| 985 | + $result = []; | |
| 986 | +        foreach($this->connection->ldapBaseUsers as $base) { | |
| 987 | + $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); | |
| 988 | + } | |
| 989 | + return $result; | |
| 990 | + } | |
| 991 | + | |
| 992 | + /** | |
| 993 | + * @param string $filter | |
| 994 | + * @param string|string[] $attr | |
| 995 | + * @param int $limit | |
| 996 | + * @param int $offset | |
| 997 | + * @return false|int | |
| 998 | + */ | |
| 999 | +    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 1000 | + $result = false; | |
| 1001 | +        foreach($this->connection->ldapBaseUsers as $base) { | |
| 1002 | + $count = $this->count($filter, [$base], $attr, $limit, $offset); | |
| 1003 | + $result = is_int($count) ? (int)$result + $count : $result; | |
| 1004 | + } | |
| 1005 | + return $result; | |
| 1006 | + } | |
| 1007 | + | |
| 1008 | + /** | |
| 1009 | + * executes an LDAP search, optimized for Groups | |
| 1010 | + * @param string $filter the LDAP filter for the search | |
| 1011 | + * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 1012 | + * @param integer $limit | |
| 1013 | + * @param integer $offset | |
| 1014 | + * @return array with the search result | |
| 1015 | + * | |
| 1016 | + * Executes an LDAP search | |
| 1017 | + */ | |
| 1018 | +    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { | |
| 1019 | + $result = []; | |
| 1020 | +        foreach($this->connection->ldapBaseGroups as $base) { | |
| 1021 | + $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); | |
| 1022 | + } | |
| 1023 | + return $result; | |
| 1024 | + } | |
| 1025 | + | |
| 1026 | + /** | |
| 1027 | + * returns the number of available groups | |
| 1028 | + * @param string $filter the LDAP search filter | |
| 1029 | + * @param string[] $attr optional | |
| 1030 | + * @param int|null $limit | |
| 1031 | + * @param int|null $offset | |
| 1032 | + * @return int|bool | |
| 1033 | + */ | |
| 1034 | +    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 1035 | + $result = false; | |
| 1036 | +        foreach($this->connection->ldapBaseGroups as $base) { | |
| 1037 | + $count = $this->count($filter, [$base], $attr, $limit, $offset); | |
| 1038 | + $result = is_int($count) ? (int)$result + $count : $result; | |
| 1039 | + } | |
| 1040 | + return $result; | |
| 1041 | + } | |
| 1042 | + | |
| 1043 | + /** | |
| 1044 | + * returns the number of available objects on the base DN | |
| 1045 | + * | |
| 1046 | + * @param int|null $limit | |
| 1047 | + * @param int|null $offset | |
| 1048 | + * @return int|bool | |
| 1049 | + */ | |
| 1050 | +    public function countObjects($limit = null, $offset = null) { | |
| 1051 | + $result = false; | |
| 1052 | +        foreach($this->connection->ldapBase as $base) { | |
| 1053 | +            $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset); | |
| 1054 | + $result = is_int($count) ? (int)$result + $count : $result; | |
| 1055 | + } | |
| 1056 | + return $result; | |
| 1057 | + } | |
| 1058 | + | |
| 1059 | + /** | |
| 1060 | + * Returns the LDAP handler | |
| 1061 | + * @throws \OC\ServerNotAvailableException | |
| 1062 | + */ | |
| 1063 | + | |
| 1064 | + /** | |
| 1065 | + * @return mixed | |
| 1066 | + * @throws \OC\ServerNotAvailableException | |
| 1067 | + */ | |
| 1068 | +    private function invokeLDAPMethod() { | |
| 1069 | + $arguments = func_get_args(); | |
| 1070 | + $command = array_shift($arguments); | |
| 1071 | + $cr = array_shift($arguments); | |
| 1072 | +        if (!method_exists($this->ldap, $command)) { | |
| 1073 | + return null; | |
| 1074 | + } | |
| 1075 | + array_unshift($arguments, $cr); | |
| 1076 | + // php no longer supports call-time pass-by-reference | |
| 1077 | + // thus cannot support controlPagedResultResponse as the third argument | |
| 1078 | + // is a reference | |
| 1079 | +        $doMethod = function () use ($command, &$arguments) { | |
| 1080 | +            if ($command == 'controlPagedResultResponse') { | |
| 1081 | +                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.'); | |
| 1082 | +            } else { | |
| 1083 | + return call_user_func_array(array($this->ldap, $command), $arguments); | |
| 1084 | + } | |
| 1085 | + }; | |
| 1086 | +        try { | |
| 1087 | + $ret = $doMethod(); | |
| 1088 | +        } catch (ServerNotAvailableException $e) { | |
| 1089 | + /* Server connection lost, attempt to reestablish it | |
| 1090 | 1090 | * Maybe implement exponential backoff? | 
| 1091 | 1091 | * This was enough to get solr indexer working which has large delays between LDAP fetches. | 
| 1092 | 1092 | */ | 
| 1093 | -			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG); | |
| 1094 | - $this->connection->resetConnectionResource(); | |
| 1095 | - $cr = $this->connection->getConnectionResource(); | |
| 1096 | - | |
| 1097 | -			if(!$this->ldap->isResource($cr)) { | |
| 1098 | - // Seems like we didn't find any resource. | |
| 1099 | -				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG); | |
| 1100 | - throw $e; | |
| 1101 | - } | |
| 1102 | - | |
| 1103 | - $arguments[0] = array_pad([], count($arguments[0]), $cr); | |
| 1104 | - $ret = $doMethod(); | |
| 1105 | - } | |
| 1106 | - return $ret; | |
| 1107 | - } | |
| 1108 | - | |
| 1109 | - /** | |
| 1110 | - * retrieved. Results will according to the order in the array. | |
| 1111 | - * | |
| 1112 | - * @param $filter | |
| 1113 | - * @param $base | |
| 1114 | - * @param string[]|string|null $attr | |
| 1115 | - * @param int $limit optional, maximum results to be counted | |
| 1116 | - * @param int $offset optional, a starting point | |
| 1117 | - * @return array|false array with the search result as first value and pagedSearchOK as | |
| 1118 | - * second | false if not successful | |
| 1119 | - * @throws ServerNotAvailableException | |
| 1120 | - */ | |
| 1121 | -	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { | |
| 1122 | -		if(!is_null($attr) && !is_array($attr)) { | |
| 1123 | - $attr = array(mb_strtolower($attr, 'UTF-8')); | |
| 1124 | - } | |
| 1125 | - | |
| 1126 | - // See if we have a resource, in case not cancel with message | |
| 1127 | - $cr = $this->connection->getConnectionResource(); | |
| 1128 | -		if(!$this->ldap->isResource($cr)) { | |
| 1129 | - // Seems like we didn't find any resource. | |
| 1130 | - // Return an empty array just like before. | |
| 1131 | -			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG); | |
| 1132 | - return false; | |
| 1133 | - } | |
| 1134 | - | |
| 1135 | - //check whether paged search should be attempted | |
| 1136 | - $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset); | |
| 1137 | - | |
| 1138 | - $linkResources = array_pad(array(), count($base), $cr); | |
| 1139 | -		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); | |
| 1140 | - // cannot use $cr anymore, might have changed in the previous call! | |
| 1141 | - $error = $this->ldap->errno($this->connection->getConnectionResource()); | |
| 1142 | -		if(!is_array($sr) || $error !== 0) { | |
| 1143 | -			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR); | |
| 1144 | - return false; | |
| 1145 | - } | |
| 1146 | - | |
| 1147 | - return array($sr, $pagedSearchOK); | |
| 1148 | - } | |
| 1149 | - | |
| 1150 | - /** | |
| 1151 | - * processes an LDAP paged search operation | |
| 1152 | - * @param array $sr the array containing the LDAP search resources | |
| 1153 | - * @param string $filter the LDAP filter for the search | |
| 1154 | - * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1155 | - * @param int $iFoundItems number of results in the single search operation | |
| 1156 | - * @param int $limit maximum results to be counted | |
| 1157 | - * @param int $offset a starting point | |
| 1158 | - * @param bool $pagedSearchOK whether a paged search has been executed | |
| 1159 | - * @param bool $skipHandling required for paged search when cookies to | |
| 1160 | - * prior results need to be gained | |
| 1161 | - * @return bool cookie validity, true if we have more pages, false otherwise. | |
| 1162 | - */ | |
| 1163 | -	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { | |
| 1164 | - $cookie = null; | |
| 1165 | -		if($pagedSearchOK) { | |
| 1166 | - $cr = $this->connection->getConnectionResource(); | |
| 1167 | -			foreach($sr as $key => $res) { | |
| 1168 | -				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { | |
| 1169 | - $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); | |
| 1170 | - } | |
| 1171 | - } | |
| 1172 | - | |
| 1173 | - //browsing through prior pages to get the cookie for the new one | |
| 1174 | -			if($skipHandling) { | |
| 1175 | - return false; | |
| 1176 | - } | |
| 1177 | - // if count is bigger, then the server does not support | |
| 1178 | - // paged search. Instead, he did a normal search. We set a | |
| 1179 | - // flag here, so the callee knows how to deal with it. | |
| 1180 | -			if($iFoundItems <= $limit) { | |
| 1181 | - $this->pagedSearchedSuccessful = true; | |
| 1182 | - } | |
| 1183 | -		} else { | |
| 1184 | -			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { | |
| 1185 | - \OC::$server->getLogger()->debug( | |
| 1186 | - 'Paged search was not available', | |
| 1187 | - [ 'app' => 'user_ldap' ] | |
| 1188 | - ); | |
| 1189 | - } | |
| 1190 | - } | |
| 1191 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1093 | +            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG); | |
| 1094 | + $this->connection->resetConnectionResource(); | |
| 1095 | + $cr = $this->connection->getConnectionResource(); | |
| 1096 | + | |
| 1097 | +            if(!$this->ldap->isResource($cr)) { | |
| 1098 | + // Seems like we didn't find any resource. | |
| 1099 | +                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG); | |
| 1100 | + throw $e; | |
| 1101 | + } | |
| 1102 | + | |
| 1103 | + $arguments[0] = array_pad([], count($arguments[0]), $cr); | |
| 1104 | + $ret = $doMethod(); | |
| 1105 | + } | |
| 1106 | + return $ret; | |
| 1107 | + } | |
| 1108 | + | |
| 1109 | + /** | |
| 1110 | + * retrieved. Results will according to the order in the array. | |
| 1111 | + * | |
| 1112 | + * @param $filter | |
| 1113 | + * @param $base | |
| 1114 | + * @param string[]|string|null $attr | |
| 1115 | + * @param int $limit optional, maximum results to be counted | |
| 1116 | + * @param int $offset optional, a starting point | |
| 1117 | + * @return array|false array with the search result as first value and pagedSearchOK as | |
| 1118 | + * second | false if not successful | |
| 1119 | + * @throws ServerNotAvailableException | |
| 1120 | + */ | |
| 1121 | +    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { | |
| 1122 | +        if(!is_null($attr) && !is_array($attr)) { | |
| 1123 | + $attr = array(mb_strtolower($attr, 'UTF-8')); | |
| 1124 | + } | |
| 1125 | + | |
| 1126 | + // See if we have a resource, in case not cancel with message | |
| 1127 | + $cr = $this->connection->getConnectionResource(); | |
| 1128 | +        if(!$this->ldap->isResource($cr)) { | |
| 1129 | + // Seems like we didn't find any resource. | |
| 1130 | + // Return an empty array just like before. | |
| 1131 | +            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG); | |
| 1132 | + return false; | |
| 1133 | + } | |
| 1134 | + | |
| 1135 | + //check whether paged search should be attempted | |
| 1136 | + $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset); | |
| 1137 | + | |
| 1138 | + $linkResources = array_pad(array(), count($base), $cr); | |
| 1139 | +        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); | |
| 1140 | + // cannot use $cr anymore, might have changed in the previous call! | |
| 1141 | + $error = $this->ldap->errno($this->connection->getConnectionResource()); | |
| 1142 | +        if(!is_array($sr) || $error !== 0) { | |
| 1143 | +            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR); | |
| 1144 | + return false; | |
| 1145 | + } | |
| 1146 | + | |
| 1147 | + return array($sr, $pagedSearchOK); | |
| 1148 | + } | |
| 1149 | + | |
| 1150 | + /** | |
| 1151 | + * processes an LDAP paged search operation | |
| 1152 | + * @param array $sr the array containing the LDAP search resources | |
| 1153 | + * @param string $filter the LDAP filter for the search | |
| 1154 | + * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1155 | + * @param int $iFoundItems number of results in the single search operation | |
| 1156 | + * @param int $limit maximum results to be counted | |
| 1157 | + * @param int $offset a starting point | |
| 1158 | + * @param bool $pagedSearchOK whether a paged search has been executed | |
| 1159 | + * @param bool $skipHandling required for paged search when cookies to | |
| 1160 | + * prior results need to be gained | |
| 1161 | + * @return bool cookie validity, true if we have more pages, false otherwise. | |
| 1162 | + */ | |
| 1163 | +    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { | |
| 1164 | + $cookie = null; | |
| 1165 | +        if($pagedSearchOK) { | |
| 1166 | + $cr = $this->connection->getConnectionResource(); | |
| 1167 | +            foreach($sr as $key => $res) { | |
| 1168 | +                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { | |
| 1169 | + $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); | |
| 1170 | + } | |
| 1171 | + } | |
| 1172 | + | |
| 1173 | + //browsing through prior pages to get the cookie for the new one | |
| 1174 | +            if($skipHandling) { | |
| 1175 | + return false; | |
| 1176 | + } | |
| 1177 | + // if count is bigger, then the server does not support | |
| 1178 | + // paged search. Instead, he did a normal search. We set a | |
| 1179 | + // flag here, so the callee knows how to deal with it. | |
| 1180 | +            if($iFoundItems <= $limit) { | |
| 1181 | + $this->pagedSearchedSuccessful = true; | |
| 1182 | + } | |
| 1183 | +        } else { | |
| 1184 | +            if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { | |
| 1185 | + \OC::$server->getLogger()->debug( | |
| 1186 | + 'Paged search was not available', | |
| 1187 | + [ 'app' => 'user_ldap' ] | |
| 1188 | + ); | |
| 1189 | + } | |
| 1190 | + } | |
| 1191 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1192 | 1192 | * Return cookie status. If we don't have more pages, with RHDS | 
| 1193 | 1193 | * cookie is null, with openldap cookie is an empty string and | 
| 1194 | 1194 | * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0 | 
| 1195 | 1195 | */ | 
| 1196 | - return !empty($cookie) || $cookie === '0'; | |
| 1197 | - } | |
| 1198 | - | |
| 1199 | - /** | |
| 1200 | - * executes an LDAP search, but counts the results only | |
| 1201 | - * | |
| 1202 | - * @param string $filter the LDAP filter for the search | |
| 1203 | - * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1204 | - * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1205 | - * retrieved. Results will according to the order in the array. | |
| 1206 | - * @param int $limit optional, maximum results to be counted | |
| 1207 | - * @param int $offset optional, a starting point | |
| 1208 | - * @param bool $skipHandling indicates whether the pages search operation is | |
| 1209 | - * completed | |
| 1210 | - * @return int|false Integer or false if the search could not be initialized | |
| 1211 | - * @throws ServerNotAvailableException | |
| 1212 | - */ | |
| 1213 | -	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1214 | -		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG); | |
| 1215 | - | |
| 1216 | - $limitPerPage = (int)$this->connection->ldapPagingSize; | |
| 1217 | -		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1218 | - $limitPerPage = $limit; | |
| 1219 | - } | |
| 1220 | - | |
| 1221 | - $counter = 0; | |
| 1222 | - $count = null; | |
| 1223 | - $this->connection->getConnectionResource(); | |
| 1224 | - | |
| 1225 | -		do { | |
| 1226 | - $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | |
| 1227 | -			if($search === false) { | |
| 1228 | - return $counter > 0 ? $counter : false; | |
| 1229 | - } | |
| 1230 | - list($sr, $pagedSearchOK) = $search; | |
| 1231 | - | |
| 1232 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1196 | + return !empty($cookie) || $cookie === '0'; | |
| 1197 | + } | |
| 1198 | + | |
| 1199 | + /** | |
| 1200 | + * executes an LDAP search, but counts the results only | |
| 1201 | + * | |
| 1202 | + * @param string $filter the LDAP filter for the search | |
| 1203 | + * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1204 | + * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1205 | + * retrieved. Results will according to the order in the array. | |
| 1206 | + * @param int $limit optional, maximum results to be counted | |
| 1207 | + * @param int $offset optional, a starting point | |
| 1208 | + * @param bool $skipHandling indicates whether the pages search operation is | |
| 1209 | + * completed | |
| 1210 | + * @return int|false Integer or false if the search could not be initialized | |
| 1211 | + * @throws ServerNotAvailableException | |
| 1212 | + */ | |
| 1213 | +    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1214 | +        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG); | |
| 1215 | + | |
| 1216 | + $limitPerPage = (int)$this->connection->ldapPagingSize; | |
| 1217 | +        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1218 | + $limitPerPage = $limit; | |
| 1219 | + } | |
| 1220 | + | |
| 1221 | + $counter = 0; | |
| 1222 | + $count = null; | |
| 1223 | + $this->connection->getConnectionResource(); | |
| 1224 | + | |
| 1225 | +        do { | |
| 1226 | + $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | |
| 1227 | +            if($search === false) { | |
| 1228 | + return $counter > 0 ? $counter : false; | |
| 1229 | + } | |
| 1230 | + list($sr, $pagedSearchOK) = $search; | |
| 1231 | + | |
| 1232 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1233 | 1233 | * countEntriesInSearchResults() method signature changed | 
| 1234 | 1234 | * by removing $limit and &$hasHitLimit parameters | 
| 1235 | 1235 | */ | 
| 1236 | - $count = $this->countEntriesInSearchResults($sr); | |
| 1237 | - $counter += $count; | |
| 1236 | + $count = $this->countEntriesInSearchResults($sr); | |
| 1237 | + $counter += $count; | |
| 1238 | 1238 | |
| 1239 | - $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage, | |
| 1240 | - $offset, $pagedSearchOK, $skipHandling); | |
| 1241 | - $offset += $limitPerPage; | |
| 1242 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1239 | + $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage, | |
| 1240 | + $offset, $pagedSearchOK, $skipHandling); | |
| 1241 | + $offset += $limitPerPage; | |
| 1242 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1243 | 1243 | * Continue now depends on $hasMorePages value | 
| 1244 | 1244 | */ | 
| 1245 | - $continue = $pagedSearchOK && $hasMorePages; | |
| 1246 | - } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); | |
| 1247 | - | |
| 1248 | - return $counter; | |
| 1249 | - } | |
| 1250 | - | |
| 1251 | - /** | |
| 1252 | - * @param array $searchResults | |
| 1253 | - * @return int | |
| 1254 | - */ | |
| 1255 | -	private function countEntriesInSearchResults($searchResults) { | |
| 1256 | - $counter = 0; | |
| 1257 | - | |
| 1258 | -		foreach($searchResults as $res) { | |
| 1259 | -			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res); | |
| 1260 | - $counter += $count; | |
| 1261 | - } | |
| 1262 | - | |
| 1263 | - return $counter; | |
| 1264 | - } | |
| 1265 | - | |
| 1266 | - /** | |
| 1267 | - * Executes an LDAP search | |
| 1268 | - * | |
| 1269 | - * @param string $filter the LDAP filter for the search | |
| 1270 | - * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1271 | - * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1272 | - * @param int $limit | |
| 1273 | - * @param int $offset | |
| 1274 | - * @param bool $skipHandling | |
| 1275 | - * @return array with the search result | |
| 1276 | - * @throws ServerNotAvailableException | |
| 1277 | - */ | |
| 1278 | -	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1279 | - $limitPerPage = (int)$this->connection->ldapPagingSize; | |
| 1280 | -		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1281 | - $limitPerPage = $limit; | |
| 1282 | - } | |
| 1283 | - | |
| 1284 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1245 | + $continue = $pagedSearchOK && $hasMorePages; | |
| 1246 | + } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); | |
| 1247 | + | |
| 1248 | + return $counter; | |
| 1249 | + } | |
| 1250 | + | |
| 1251 | + /** | |
| 1252 | + * @param array $searchResults | |
| 1253 | + * @return int | |
| 1254 | + */ | |
| 1255 | +    private function countEntriesInSearchResults($searchResults) { | |
| 1256 | + $counter = 0; | |
| 1257 | + | |
| 1258 | +        foreach($searchResults as $res) { | |
| 1259 | +            $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res); | |
| 1260 | + $counter += $count; | |
| 1261 | + } | |
| 1262 | + | |
| 1263 | + return $counter; | |
| 1264 | + } | |
| 1265 | + | |
| 1266 | + /** | |
| 1267 | + * Executes an LDAP search | |
| 1268 | + * | |
| 1269 | + * @param string $filter the LDAP filter for the search | |
| 1270 | + * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1271 | + * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1272 | + * @param int $limit | |
| 1273 | + * @param int $offset | |
| 1274 | + * @param bool $skipHandling | |
| 1275 | + * @return array with the search result | |
| 1276 | + * @throws ServerNotAvailableException | |
| 1277 | + */ | |
| 1278 | +    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1279 | + $limitPerPage = (int)$this->connection->ldapPagingSize; | |
| 1280 | +        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1281 | + $limitPerPage = $limit; | |
| 1282 | + } | |
| 1283 | + | |
| 1284 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1285 | 1285 | * As we can have pages with zero results and/or pages with less | 
| 1286 | 1286 | * than $limit results but with a still valid server 'cookie', | 
| 1287 | 1287 | * loops through until we get $continue equals true and | 
| 1288 | 1288 | * $findings['count'] < $limit | 
| 1289 | 1289 | */ | 
| 1290 | - $findings = []; | |
| 1291 | - $savedoffset = $offset; | |
| 1292 | -		do { | |
| 1293 | - $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | |
| 1294 | -			if($search === false) { | |
| 1295 | - return []; | |
| 1296 | - } | |
| 1297 | - list($sr, $pagedSearchOK) = $search; | |
| 1298 | - $cr = $this->connection->getConnectionResource(); | |
| 1299 | - | |
| 1300 | -			if($skipHandling) { | |
| 1301 | - //i.e. result do not need to be fetched, we just need the cookie | |
| 1302 | - //thus pass 1 or any other value as $iFoundItems because it is not | |
| 1303 | - //used | |
| 1304 | - $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage, | |
| 1305 | - $offset, $pagedSearchOK, | |
| 1306 | - $skipHandling); | |
| 1307 | - return array(); | |
| 1308 | - } | |
| 1309 | - | |
| 1310 | - $iFoundItems = 0; | |
| 1311 | -			foreach($sr as $res) { | |
| 1312 | -				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); | |
| 1313 | - $iFoundItems = max($iFoundItems, $findings['count']); | |
| 1314 | - unset($findings['count']); | |
| 1315 | - } | |
| 1316 | - | |
| 1317 | - $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems, | |
| 1318 | - $limitPerPage, $offset, $pagedSearchOK, | |
| 1319 | - $skipHandling); | |
| 1320 | - $offset += $limitPerPage; | |
| 1321 | - } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit)); | |
| 1322 | - // reseting offset | |
| 1323 | - $offset = $savedoffset; | |
| 1324 | - | |
| 1325 | - // if we're here, probably no connection resource is returned. | |
| 1326 | - // to make Nextcloud behave nicely, we simply give back an empty array. | |
| 1327 | -		if(is_null($findings)) { | |
| 1328 | - return array(); | |
| 1329 | - } | |
| 1330 | - | |
| 1331 | -		if(!is_null($attr)) { | |
| 1332 | - $selection = []; | |
| 1333 | - $i = 0; | |
| 1334 | -			foreach($findings as $item) { | |
| 1335 | -				if(!is_array($item)) { | |
| 1336 | - continue; | |
| 1337 | - } | |
| 1338 | - $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); | |
| 1339 | -				foreach($attr as $key) { | |
| 1340 | -					if(isset($item[$key])) { | |
| 1341 | -						if(is_array($item[$key]) && isset($item[$key]['count'])) { | |
| 1342 | - unset($item[$key]['count']); | |
| 1343 | - } | |
| 1344 | -						if($key !== 'dn') { | |
| 1345 | -							if($this->resemblesDN($key)) { | |
| 1346 | - $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]); | |
| 1347 | -							} else if($key === 'objectguid' || $key === 'guid') { | |
| 1348 | - $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])]; | |
| 1349 | -							} else { | |
| 1350 | - $selection[$i][$key] = $item[$key]; | |
| 1351 | - } | |
| 1352 | -						} else { | |
| 1353 | - $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])]; | |
| 1354 | - } | |
| 1355 | - } | |
| 1356 | - | |
| 1357 | - } | |
| 1358 | - $i++; | |
| 1359 | - } | |
| 1360 | - $findings = $selection; | |
| 1361 | - } | |
| 1362 | - //we slice the findings, when | |
| 1363 | - //a) paged search unsuccessful, though attempted | |
| 1364 | - //b) no paged search, but limit set | |
| 1365 | - if((!$this->getPagedSearchResultState() | |
| 1366 | - && $pagedSearchOK) | |
| 1367 | - || ( | |
| 1368 | - !$pagedSearchOK | |
| 1369 | - && !is_null($limit) | |
| 1370 | - ) | |
| 1371 | -		) { | |
| 1372 | - $findings = array_slice($findings, (int)$offset, $limit); | |
| 1373 | - } | |
| 1374 | - return $findings; | |
| 1375 | - } | |
| 1376 | - | |
| 1377 | - /** | |
| 1378 | - * @param string $name | |
| 1379 | - * @return string | |
| 1380 | - * @throws \InvalidArgumentException | |
| 1381 | - */ | |
| 1382 | -	public function sanitizeUsername($name) { | |
| 1383 | - $name = trim($name); | |
| 1384 | - | |
| 1385 | -		if($this->connection->ldapIgnoreNamingRules) { | |
| 1386 | - return $name; | |
| 1387 | - } | |
| 1388 | - | |
| 1389 | - // Transliteration to ASCII | |
| 1390 | -		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name); | |
| 1391 | -		if($transliterated !== false) { | |
| 1392 | - // depending on system config iconv can work or not | |
| 1393 | - $name = $transliterated; | |
| 1394 | - } | |
| 1395 | - | |
| 1396 | - // Replacements | |
| 1397 | -		$name = str_replace(' ', '_', $name); | |
| 1398 | - | |
| 1399 | - // Every remaining disallowed characters will be removed | |
| 1400 | -		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); | |
| 1401 | - | |
| 1402 | -		if($name === '') { | |
| 1403 | -			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters'); | |
| 1404 | - } | |
| 1405 | - | |
| 1406 | - return $name; | |
| 1407 | - } | |
| 1408 | - | |
| 1409 | - /** | |
| 1410 | - * escapes (user provided) parts for LDAP filter | |
| 1411 | - * @param string $input, the provided value | |
| 1412 | - * @param bool $allowAsterisk whether in * at the beginning should be preserved | |
| 1413 | - * @return string the escaped string | |
| 1414 | - */ | |
| 1415 | -	public function escapeFilterPart($input, $allowAsterisk = false) { | |
| 1416 | - $asterisk = ''; | |
| 1417 | -		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { | |
| 1418 | - $asterisk = '*'; | |
| 1419 | - $input = mb_substr($input, 1, null, 'UTF-8'); | |
| 1420 | - } | |
| 1421 | -		$search  = array('*', '\\', '(', ')'); | |
| 1422 | -		$replace = array('\\*', '\\\\', '\\(', '\\)'); | |
| 1423 | - return $asterisk . str_replace($search, $replace, $input); | |
| 1424 | - } | |
| 1425 | - | |
| 1426 | - /** | |
| 1427 | - * combines the input filters with AND | |
| 1428 | - * @param string[] $filters the filters to connect | |
| 1429 | - * @return string the combined filter | |
| 1430 | - */ | |
| 1431 | -	public function combineFilterWithAnd($filters) { | |
| 1432 | - return $this->combineFilter($filters, '&'); | |
| 1433 | - } | |
| 1434 | - | |
| 1435 | - /** | |
| 1436 | - * combines the input filters with OR | |
| 1437 | - * @param string[] $filters the filters to connect | |
| 1438 | - * @return string the combined filter | |
| 1439 | - * Combines Filter arguments with OR | |
| 1440 | - */ | |
| 1441 | -	public function combineFilterWithOr($filters) { | |
| 1442 | - return $this->combineFilter($filters, '|'); | |
| 1443 | - } | |
| 1444 | - | |
| 1445 | - /** | |
| 1446 | - * combines the input filters with given operator | |
| 1447 | - * @param string[] $filters the filters to connect | |
| 1448 | - * @param string $operator either & or | | |
| 1449 | - * @return string the combined filter | |
| 1450 | - */ | |
| 1451 | -	private function combineFilter($filters, $operator) { | |
| 1452 | -		$combinedFilter = '('.$operator; | |
| 1453 | -		foreach($filters as $filter) { | |
| 1454 | -			if ($filter !== '' && $filter[0] !== '(') { | |
| 1455 | -				$filter = '('.$filter.')'; | |
| 1456 | - } | |
| 1457 | - $combinedFilter.=$filter; | |
| 1458 | - } | |
| 1459 | - $combinedFilter.=')'; | |
| 1460 | - return $combinedFilter; | |
| 1461 | - } | |
| 1462 | - | |
| 1463 | - /** | |
| 1464 | - * creates a filter part for to perform search for users | |
| 1465 | - * @param string $search the search term | |
| 1466 | - * @return string the final filter part to use in LDAP searches | |
| 1467 | - */ | |
| 1468 | -	public function getFilterPartForUserSearch($search) { | |
| 1469 | - return $this->getFilterPartForSearch($search, | |
| 1470 | - $this->connection->ldapAttributesForUserSearch, | |
| 1471 | - $this->connection->ldapUserDisplayName); | |
| 1472 | - } | |
| 1473 | - | |
| 1474 | - /** | |
| 1475 | - * creates a filter part for to perform search for groups | |
| 1476 | - * @param string $search the search term | |
| 1477 | - * @return string the final filter part to use in LDAP searches | |
| 1478 | - */ | |
| 1479 | -	public function getFilterPartForGroupSearch($search) { | |
| 1480 | - return $this->getFilterPartForSearch($search, | |
| 1481 | - $this->connection->ldapAttributesForGroupSearch, | |
| 1482 | - $this->connection->ldapGroupDisplayName); | |
| 1483 | - } | |
| 1484 | - | |
| 1485 | - /** | |
| 1486 | - * creates a filter part for searches by splitting up the given search | |
| 1487 | - * string into single words | |
| 1488 | - * @param string $search the search term | |
| 1489 | - * @param string[] $searchAttributes needs to have at least two attributes, | |
| 1490 | - * otherwise it does not make sense :) | |
| 1491 | - * @return string the final filter part to use in LDAP searches | |
| 1492 | - * @throws \Exception | |
| 1493 | - */ | |
| 1494 | -	private function getAdvancedFilterPartForSearch($search, $searchAttributes) { | |
| 1495 | -		if(!is_array($searchAttributes) || count($searchAttributes) < 2) { | |
| 1496 | -			throw new \Exception('searchAttributes must be an array with at least two string'); | |
| 1497 | - } | |
| 1498 | -		$searchWords = explode(' ', trim($search)); | |
| 1499 | - $wordFilters = array(); | |
| 1500 | -		foreach($searchWords as $word) { | |
| 1501 | - $word = $this->prepareSearchTerm($word); | |
| 1502 | - //every word needs to appear at least once | |
| 1503 | - $wordMatchOneAttrFilters = array(); | |
| 1504 | -			foreach($searchAttributes as $attr) { | |
| 1505 | - $wordMatchOneAttrFilters[] = $attr . '=' . $word; | |
| 1506 | - } | |
| 1507 | - $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); | |
| 1508 | - } | |
| 1509 | - return $this->combineFilterWithAnd($wordFilters); | |
| 1510 | - } | |
| 1511 | - | |
| 1512 | - /** | |
| 1513 | - * creates a filter part for searches | |
| 1514 | - * @param string $search the search term | |
| 1515 | - * @param string[]|null $searchAttributes | |
| 1516 | - * @param string $fallbackAttribute a fallback attribute in case the user | |
| 1517 | - * did not define search attributes. Typically the display name attribute. | |
| 1518 | - * @return string the final filter part to use in LDAP searches | |
| 1519 | - */ | |
| 1520 | -	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { | |
| 1521 | - $filter = array(); | |
| 1522 | - $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); | |
| 1523 | -		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { | |
| 1524 | -			try { | |
| 1525 | - return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); | |
| 1526 | -			} catch(\Exception $e) { | |
| 1527 | - \OCP\Util::writeLog( | |
| 1528 | - 'user_ldap', | |
| 1529 | - 'Creating advanced filter for search failed, falling back to simple method.', | |
| 1530 | - ILogger::INFO | |
| 1531 | - ); | |
| 1532 | - } | |
| 1533 | - } | |
| 1534 | - | |
| 1535 | - $search = $this->prepareSearchTerm($search); | |
| 1536 | -		if(!is_array($searchAttributes) || count($searchAttributes) === 0) { | |
| 1537 | -			if ($fallbackAttribute === '') { | |
| 1538 | - return ''; | |
| 1539 | - } | |
| 1540 | - $filter[] = $fallbackAttribute . '=' . $search; | |
| 1541 | -		} else { | |
| 1542 | -			foreach($searchAttributes as $attribute) { | |
| 1543 | - $filter[] = $attribute . '=' . $search; | |
| 1544 | - } | |
| 1545 | - } | |
| 1546 | -		if(count($filter) === 1) { | |
| 1547 | -			return '('.$filter[0].')'; | |
| 1548 | - } | |
| 1549 | - return $this->combineFilterWithOr($filter); | |
| 1550 | - } | |
| 1551 | - | |
| 1552 | - /** | |
| 1553 | - * returns the search term depending on whether we are allowed | |
| 1554 | - * list users found by ldap with the current input appended by | |
| 1555 | - * a * | |
| 1556 | - * @return string | |
| 1557 | - */ | |
| 1558 | -	private function prepareSearchTerm($term) { | |
| 1559 | - $config = \OC::$server->getConfig(); | |
| 1560 | - | |
| 1561 | -		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes'); | |
| 1562 | - | |
| 1563 | - $result = $term; | |
| 1564 | -		if ($term === '') { | |
| 1565 | - $result = '*'; | |
| 1566 | -		} else if ($allowEnum !== 'no') { | |
| 1567 | - $result = $term . '*'; | |
| 1568 | - } | |
| 1569 | - return $result; | |
| 1570 | - } | |
| 1571 | - | |
| 1572 | - /** | |
| 1573 | - * returns the filter used for counting users | |
| 1574 | - * @return string | |
| 1575 | - */ | |
| 1576 | -	public function getFilterForUserCount() { | |
| 1577 | - $filter = $this->combineFilterWithAnd(array( | |
| 1578 | - $this->connection->ldapUserFilter, | |
| 1579 | - $this->connection->ldapUserDisplayName . '=*' | |
| 1580 | - )); | |
| 1581 | - | |
| 1582 | - return $filter; | |
| 1583 | - } | |
| 1584 | - | |
| 1585 | - /** | |
| 1586 | - * @param string $name | |
| 1587 | - * @param string $password | |
| 1588 | - * @return bool | |
| 1589 | - */ | |
| 1590 | -	public function areCredentialsValid($name, $password) { | |
| 1591 | - $name = $this->helper->DNasBaseParameter($name); | |
| 1592 | - $testConnection = clone $this->connection; | |
| 1593 | - $credentials = array( | |
| 1594 | - 'ldapAgentName' => $name, | |
| 1595 | - 'ldapAgentPassword' => $password | |
| 1596 | - ); | |
| 1597 | -		if(!$testConnection->setConfiguration($credentials)) { | |
| 1598 | - return false; | |
| 1599 | - } | |
| 1600 | - return $testConnection->bind(); | |
| 1601 | - } | |
| 1602 | - | |
| 1603 | - /** | |
| 1604 | - * reverse lookup of a DN given a known UUID | |
| 1605 | - * | |
| 1606 | - * @param string $uuid | |
| 1607 | - * @return string | |
| 1608 | - * @throws \Exception | |
| 1609 | - */ | |
| 1610 | -	public function getUserDnByUuid($uuid) { | |
| 1611 | - $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1612 | - $filter = $this->connection->ldapUserFilter; | |
| 1613 | - $base = $this->connection->ldapBaseUsers; | |
| 1614 | - | |
| 1615 | -		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') { | |
| 1616 | - // Sacrebleu! The UUID attribute is unknown :( We need first an | |
| 1617 | - // existing DN to be able to reliably detect it. | |
| 1618 | - $result = $this->search($filter, $base, ['dn'], 1); | |
| 1619 | -			if(!isset($result[0]) || !isset($result[0]['dn'])) { | |
| 1620 | -				throw new \Exception('Cannot determine UUID attribute'); | |
| 1621 | - } | |
| 1622 | - $dn = $result[0]['dn'][0]; | |
| 1623 | -			if(!$this->detectUuidAttribute($dn, true)) { | |
| 1624 | -				throw new \Exception('Cannot determine UUID attribute'); | |
| 1625 | - } | |
| 1626 | -		} else { | |
| 1627 | - // The UUID attribute is either known or an override is given. | |
| 1628 | - // By calling this method we ensure that $this->connection->$uuidAttr | |
| 1629 | - // is definitely set | |
| 1630 | -			if(!$this->detectUuidAttribute('', true)) { | |
| 1631 | -				throw new \Exception('Cannot determine UUID attribute'); | |
| 1632 | - } | |
| 1633 | - } | |
| 1634 | - | |
| 1635 | - $uuidAttr = $this->connection->ldapUuidUserAttribute; | |
| 1636 | -		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { | |
| 1637 | - $uuid = $this->formatGuid2ForFilterUser($uuid); | |
| 1638 | - } | |
| 1639 | - | |
| 1640 | - $filter = $uuidAttr . '=' . $uuid; | |
| 1641 | - $result = $this->searchUsers($filter, ['dn'], 2); | |
| 1642 | -		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { | |
| 1643 | - // we put the count into account to make sure that this is | |
| 1644 | - // really unique | |
| 1645 | - return $result[0]['dn'][0]; | |
| 1646 | - } | |
| 1647 | - | |
| 1648 | -		throw new \Exception('Cannot determine UUID attribute'); | |
| 1649 | - } | |
| 1650 | - | |
| 1651 | - /** | |
| 1652 | - * auto-detects the directory's UUID attribute | |
| 1653 | - * | |
| 1654 | - * @param string $dn a known DN used to check against | |
| 1655 | - * @param bool $isUser | |
| 1656 | - * @param bool $force the detection should be run, even if it is not set to auto | |
| 1657 | - * @param array|null $ldapRecord | |
| 1658 | - * @return bool true on success, false otherwise | |
| 1659 | - */ | |
| 1660 | -	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) { | |
| 1661 | -		if($isUser) { | |
| 1662 | - $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1663 | - $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1664 | -		} else { | |
| 1665 | - $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1666 | - $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1667 | - } | |
| 1668 | - | |
| 1669 | -		if(($this->connection->$uuidAttr !== 'auto') && !$force) { | |
| 1670 | - return true; | |
| 1671 | - } | |
| 1672 | - | |
| 1673 | -		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) { | |
| 1674 | - $this->connection->$uuidAttr = $uuidOverride; | |
| 1675 | - return true; | |
| 1676 | - } | |
| 1677 | - | |
| 1678 | -		foreach(self::UUID_ATTRIBUTES as $attribute) { | |
| 1679 | -			if($ldapRecord !== null) { | |
| 1680 | - // we have the info from LDAP already, we don't need to talk to the server again | |
| 1681 | -				if(isset($ldapRecord[$attribute])) { | |
| 1682 | - $this->connection->$uuidAttr = $attribute; | |
| 1683 | - return true; | |
| 1684 | -				} else { | |
| 1685 | - continue; | |
| 1686 | - } | |
| 1687 | - } | |
| 1688 | - | |
| 1689 | - $value = $this->readAttribute($dn, $attribute); | |
| 1690 | -			if(is_array($value) && isset($value[0]) && !empty($value[0])) { | |
| 1691 | - \OCP\Util::writeLog( | |
| 1692 | - 'user_ldap', | |
| 1693 | - 'Setting '.$attribute.' as '.$uuidAttr, | |
| 1694 | - ILogger::DEBUG | |
| 1695 | - ); | |
| 1696 | - $this->connection->$uuidAttr = $attribute; | |
| 1697 | - return true; | |
| 1698 | - } | |
| 1699 | - } | |
| 1700 | - \OCP\Util::writeLog( | |
| 1701 | - 'user_ldap', | |
| 1702 | - 'Could not autodetect the UUID attribute', | |
| 1703 | - ILogger::ERROR | |
| 1704 | - ); | |
| 1705 | - | |
| 1706 | - return false; | |
| 1707 | - } | |
| 1708 | - | |
| 1709 | - /** | |
| 1710 | - * @param string $dn | |
| 1711 | - * @param bool $isUser | |
| 1712 | - * @param null $ldapRecord | |
| 1713 | - * @return bool|string | |
| 1714 | - */ | |
| 1715 | -	public function getUUID($dn, $isUser = true, $ldapRecord = null) { | |
| 1716 | -		if($isUser) { | |
| 1717 | - $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1718 | - $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1719 | -		} else { | |
| 1720 | - $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1721 | - $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1722 | - } | |
| 1723 | - | |
| 1724 | - $uuid = false; | |
| 1725 | -		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { | |
| 1726 | - $attr = $this->connection->$uuidAttr; | |
| 1727 | - $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr); | |
| 1728 | - if( !is_array($uuid) | |
| 1729 | - && $uuidOverride !== '' | |
| 1730 | - && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) | |
| 1731 | -			{ | |
| 1732 | - $uuid = isset($ldapRecord[$this->connection->$uuidAttr]) | |
| 1733 | - ? $ldapRecord[$this->connection->$uuidAttr] | |
| 1734 | - : $this->readAttribute($dn, $this->connection->$uuidAttr); | |
| 1735 | - } | |
| 1736 | -			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { | |
| 1737 | - $uuid = $uuid[0]; | |
| 1738 | - } | |
| 1739 | - } | |
| 1740 | - | |
| 1741 | - return $uuid; | |
| 1742 | - } | |
| 1743 | - | |
| 1744 | - /** | |
| 1745 | - * converts a binary ObjectGUID into a string representation | |
| 1746 | - * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD | |
| 1747 | - * @return string | |
| 1748 | - * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198 | |
| 1749 | - */ | |
| 1750 | -	private function convertObjectGUID2Str($oguid) { | |
| 1751 | - $hex_guid = bin2hex($oguid); | |
| 1752 | - $hex_guid_to_guid_str = ''; | |
| 1753 | -		for($k = 1; $k <= 4; ++$k) { | |
| 1754 | - $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); | |
| 1755 | - } | |
| 1756 | - $hex_guid_to_guid_str .= '-'; | |
| 1757 | -		for($k = 1; $k <= 2; ++$k) { | |
| 1758 | - $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); | |
| 1759 | - } | |
| 1760 | - $hex_guid_to_guid_str .= '-'; | |
| 1761 | -		for($k = 1; $k <= 2; ++$k) { | |
| 1762 | - $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); | |
| 1763 | - } | |
| 1764 | - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); | |
| 1765 | - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20); | |
| 1766 | - | |
| 1767 | - return strtoupper($hex_guid_to_guid_str); | |
| 1768 | - } | |
| 1769 | - | |
| 1770 | - /** | |
| 1771 | - * the first three blocks of the string-converted GUID happen to be in | |
| 1772 | - * reverse order. In order to use it in a filter, this needs to be | |
| 1773 | - * corrected. Furthermore the dashes need to be replaced and \\ preprended | |
| 1774 | - * to every two hax figures. | |
| 1775 | - * | |
| 1776 | - * If an invalid string is passed, it will be returned without change. | |
| 1777 | - * | |
| 1778 | - * @param string $guid | |
| 1779 | - * @return string | |
| 1780 | - */ | |
| 1781 | -	public function formatGuid2ForFilterUser($guid) { | |
| 1782 | -		if(!is_string($guid)) { | |
| 1783 | -			throw new \InvalidArgumentException('String expected'); | |
| 1784 | - } | |
| 1785 | -		$blocks = explode('-', $guid); | |
| 1786 | -		if(count($blocks) !== 5) { | |
| 1787 | - /* | |
| 1290 | + $findings = []; | |
| 1291 | + $savedoffset = $offset; | |
| 1292 | +        do { | |
| 1293 | + $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | |
| 1294 | +            if($search === false) { | |
| 1295 | + return []; | |
| 1296 | + } | |
| 1297 | + list($sr, $pagedSearchOK) = $search; | |
| 1298 | + $cr = $this->connection->getConnectionResource(); | |
| 1299 | + | |
| 1300 | +            if($skipHandling) { | |
| 1301 | + //i.e. result do not need to be fetched, we just need the cookie | |
| 1302 | + //thus pass 1 or any other value as $iFoundItems because it is not | |
| 1303 | + //used | |
| 1304 | + $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage, | |
| 1305 | + $offset, $pagedSearchOK, | |
| 1306 | + $skipHandling); | |
| 1307 | + return array(); | |
| 1308 | + } | |
| 1309 | + | |
| 1310 | + $iFoundItems = 0; | |
| 1311 | +            foreach($sr as $res) { | |
| 1312 | +                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); | |
| 1313 | + $iFoundItems = max($iFoundItems, $findings['count']); | |
| 1314 | + unset($findings['count']); | |
| 1315 | + } | |
| 1316 | + | |
| 1317 | + $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems, | |
| 1318 | + $limitPerPage, $offset, $pagedSearchOK, | |
| 1319 | + $skipHandling); | |
| 1320 | + $offset += $limitPerPage; | |
| 1321 | + } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit)); | |
| 1322 | + // reseting offset | |
| 1323 | + $offset = $savedoffset; | |
| 1324 | + | |
| 1325 | + // if we're here, probably no connection resource is returned. | |
| 1326 | + // to make Nextcloud behave nicely, we simply give back an empty array. | |
| 1327 | +        if(is_null($findings)) { | |
| 1328 | + return array(); | |
| 1329 | + } | |
| 1330 | + | |
| 1331 | +        if(!is_null($attr)) { | |
| 1332 | + $selection = []; | |
| 1333 | + $i = 0; | |
| 1334 | +            foreach($findings as $item) { | |
| 1335 | +                if(!is_array($item)) { | |
| 1336 | + continue; | |
| 1337 | + } | |
| 1338 | + $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); | |
| 1339 | +                foreach($attr as $key) { | |
| 1340 | +                    if(isset($item[$key])) { | |
| 1341 | +                        if(is_array($item[$key]) && isset($item[$key]['count'])) { | |
| 1342 | + unset($item[$key]['count']); | |
| 1343 | + } | |
| 1344 | +                        if($key !== 'dn') { | |
| 1345 | +                            if($this->resemblesDN($key)) { | |
| 1346 | + $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]); | |
| 1347 | +                            } else if($key === 'objectguid' || $key === 'guid') { | |
| 1348 | + $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])]; | |
| 1349 | +                            } else { | |
| 1350 | + $selection[$i][$key] = $item[$key]; | |
| 1351 | + } | |
| 1352 | +                        } else { | |
| 1353 | + $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])]; | |
| 1354 | + } | |
| 1355 | + } | |
| 1356 | + | |
| 1357 | + } | |
| 1358 | + $i++; | |
| 1359 | + } | |
| 1360 | + $findings = $selection; | |
| 1361 | + } | |
| 1362 | + //we slice the findings, when | |
| 1363 | + //a) paged search unsuccessful, though attempted | |
| 1364 | + //b) no paged search, but limit set | |
| 1365 | + if((!$this->getPagedSearchResultState() | |
| 1366 | + && $pagedSearchOK) | |
| 1367 | + || ( | |
| 1368 | + !$pagedSearchOK | |
| 1369 | + && !is_null($limit) | |
| 1370 | + ) | |
| 1371 | +        ) { | |
| 1372 | + $findings = array_slice($findings, (int)$offset, $limit); | |
| 1373 | + } | |
| 1374 | + return $findings; | |
| 1375 | + } | |
| 1376 | + | |
| 1377 | + /** | |
| 1378 | + * @param string $name | |
| 1379 | + * @return string | |
| 1380 | + * @throws \InvalidArgumentException | |
| 1381 | + */ | |
| 1382 | +    public function sanitizeUsername($name) { | |
| 1383 | + $name = trim($name); | |
| 1384 | + | |
| 1385 | +        if($this->connection->ldapIgnoreNamingRules) { | |
| 1386 | + return $name; | |
| 1387 | + } | |
| 1388 | + | |
| 1389 | + // Transliteration to ASCII | |
| 1390 | +        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name); | |
| 1391 | +        if($transliterated !== false) { | |
| 1392 | + // depending on system config iconv can work or not | |
| 1393 | + $name = $transliterated; | |
| 1394 | + } | |
| 1395 | + | |
| 1396 | + // Replacements | |
| 1397 | +        $name = str_replace(' ', '_', $name); | |
| 1398 | + | |
| 1399 | + // Every remaining disallowed characters will be removed | |
| 1400 | +        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); | |
| 1401 | + | |
| 1402 | +        if($name === '') { | |
| 1403 | +            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters'); | |
| 1404 | + } | |
| 1405 | + | |
| 1406 | + return $name; | |
| 1407 | + } | |
| 1408 | + | |
| 1409 | + /** | |
| 1410 | + * escapes (user provided) parts for LDAP filter | |
| 1411 | + * @param string $input, the provided value | |
| 1412 | + * @param bool $allowAsterisk whether in * at the beginning should be preserved | |
| 1413 | + * @return string the escaped string | |
| 1414 | + */ | |
| 1415 | +    public function escapeFilterPart($input, $allowAsterisk = false) { | |
| 1416 | + $asterisk = ''; | |
| 1417 | +        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { | |
| 1418 | + $asterisk = '*'; | |
| 1419 | + $input = mb_substr($input, 1, null, 'UTF-8'); | |
| 1420 | + } | |
| 1421 | +        $search  = array('*', '\\', '(', ')'); | |
| 1422 | +        $replace = array('\\*', '\\\\', '\\(', '\\)'); | |
| 1423 | + return $asterisk . str_replace($search, $replace, $input); | |
| 1424 | + } | |
| 1425 | + | |
| 1426 | + /** | |
| 1427 | + * combines the input filters with AND | |
| 1428 | + * @param string[] $filters the filters to connect | |
| 1429 | + * @return string the combined filter | |
| 1430 | + */ | |
| 1431 | +    public function combineFilterWithAnd($filters) { | |
| 1432 | + return $this->combineFilter($filters, '&'); | |
| 1433 | + } | |
| 1434 | + | |
| 1435 | + /** | |
| 1436 | + * combines the input filters with OR | |
| 1437 | + * @param string[] $filters the filters to connect | |
| 1438 | + * @return string the combined filter | |
| 1439 | + * Combines Filter arguments with OR | |
| 1440 | + */ | |
| 1441 | +    public function combineFilterWithOr($filters) { | |
| 1442 | + return $this->combineFilter($filters, '|'); | |
| 1443 | + } | |
| 1444 | + | |
| 1445 | + /** | |
| 1446 | + * combines the input filters with given operator | |
| 1447 | + * @param string[] $filters the filters to connect | |
| 1448 | + * @param string $operator either & or | | |
| 1449 | + * @return string the combined filter | |
| 1450 | + */ | |
| 1451 | +    private function combineFilter($filters, $operator) { | |
| 1452 | +        $combinedFilter = '('.$operator; | |
| 1453 | +        foreach($filters as $filter) { | |
| 1454 | +            if ($filter !== '' && $filter[0] !== '(') { | |
| 1455 | +                $filter = '('.$filter.')'; | |
| 1456 | + } | |
| 1457 | + $combinedFilter.=$filter; | |
| 1458 | + } | |
| 1459 | + $combinedFilter.=')'; | |
| 1460 | + return $combinedFilter; | |
| 1461 | + } | |
| 1462 | + | |
| 1463 | + /** | |
| 1464 | + * creates a filter part for to perform search for users | |
| 1465 | + * @param string $search the search term | |
| 1466 | + * @return string the final filter part to use in LDAP searches | |
| 1467 | + */ | |
| 1468 | +    public function getFilterPartForUserSearch($search) { | |
| 1469 | + return $this->getFilterPartForSearch($search, | |
| 1470 | + $this->connection->ldapAttributesForUserSearch, | |
| 1471 | + $this->connection->ldapUserDisplayName); | |
| 1472 | + } | |
| 1473 | + | |
| 1474 | + /** | |
| 1475 | + * creates a filter part for to perform search for groups | |
| 1476 | + * @param string $search the search term | |
| 1477 | + * @return string the final filter part to use in LDAP searches | |
| 1478 | + */ | |
| 1479 | +    public function getFilterPartForGroupSearch($search) { | |
| 1480 | + return $this->getFilterPartForSearch($search, | |
| 1481 | + $this->connection->ldapAttributesForGroupSearch, | |
| 1482 | + $this->connection->ldapGroupDisplayName); | |
| 1483 | + } | |
| 1484 | + | |
| 1485 | + /** | |
| 1486 | + * creates a filter part for searches by splitting up the given search | |
| 1487 | + * string into single words | |
| 1488 | + * @param string $search the search term | |
| 1489 | + * @param string[] $searchAttributes needs to have at least two attributes, | |
| 1490 | + * otherwise it does not make sense :) | |
| 1491 | + * @return string the final filter part to use in LDAP searches | |
| 1492 | + * @throws \Exception | |
| 1493 | + */ | |
| 1494 | +    private function getAdvancedFilterPartForSearch($search, $searchAttributes) { | |
| 1495 | +        if(!is_array($searchAttributes) || count($searchAttributes) < 2) { | |
| 1496 | +            throw new \Exception('searchAttributes must be an array with at least two string'); | |
| 1497 | + } | |
| 1498 | +        $searchWords = explode(' ', trim($search)); | |
| 1499 | + $wordFilters = array(); | |
| 1500 | +        foreach($searchWords as $word) { | |
| 1501 | + $word = $this->prepareSearchTerm($word); | |
| 1502 | + //every word needs to appear at least once | |
| 1503 | + $wordMatchOneAttrFilters = array(); | |
| 1504 | +            foreach($searchAttributes as $attr) { | |
| 1505 | + $wordMatchOneAttrFilters[] = $attr . '=' . $word; | |
| 1506 | + } | |
| 1507 | + $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); | |
| 1508 | + } | |
| 1509 | + return $this->combineFilterWithAnd($wordFilters); | |
| 1510 | + } | |
| 1511 | + | |
| 1512 | + /** | |
| 1513 | + * creates a filter part for searches | |
| 1514 | + * @param string $search the search term | |
| 1515 | + * @param string[]|null $searchAttributes | |
| 1516 | + * @param string $fallbackAttribute a fallback attribute in case the user | |
| 1517 | + * did not define search attributes. Typically the display name attribute. | |
| 1518 | + * @return string the final filter part to use in LDAP searches | |
| 1519 | + */ | |
| 1520 | +    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { | |
| 1521 | + $filter = array(); | |
| 1522 | + $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); | |
| 1523 | +        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { | |
| 1524 | +            try { | |
| 1525 | + return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); | |
| 1526 | +            } catch(\Exception $e) { | |
| 1527 | + \OCP\Util::writeLog( | |
| 1528 | + 'user_ldap', | |
| 1529 | + 'Creating advanced filter for search failed, falling back to simple method.', | |
| 1530 | + ILogger::INFO | |
| 1531 | + ); | |
| 1532 | + } | |
| 1533 | + } | |
| 1534 | + | |
| 1535 | + $search = $this->prepareSearchTerm($search); | |
| 1536 | +        if(!is_array($searchAttributes) || count($searchAttributes) === 0) { | |
| 1537 | +            if ($fallbackAttribute === '') { | |
| 1538 | + return ''; | |
| 1539 | + } | |
| 1540 | + $filter[] = $fallbackAttribute . '=' . $search; | |
| 1541 | +        } else { | |
| 1542 | +            foreach($searchAttributes as $attribute) { | |
| 1543 | + $filter[] = $attribute . '=' . $search; | |
| 1544 | + } | |
| 1545 | + } | |
| 1546 | +        if(count($filter) === 1) { | |
| 1547 | +            return '('.$filter[0].')'; | |
| 1548 | + } | |
| 1549 | + return $this->combineFilterWithOr($filter); | |
| 1550 | + } | |
| 1551 | + | |
| 1552 | + /** | |
| 1553 | + * returns the search term depending on whether we are allowed | |
| 1554 | + * list users found by ldap with the current input appended by | |
| 1555 | + * a * | |
| 1556 | + * @return string | |
| 1557 | + */ | |
| 1558 | +    private function prepareSearchTerm($term) { | |
| 1559 | + $config = \OC::$server->getConfig(); | |
| 1560 | + | |
| 1561 | +        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes'); | |
| 1562 | + | |
| 1563 | + $result = $term; | |
| 1564 | +        if ($term === '') { | |
| 1565 | + $result = '*'; | |
| 1566 | +        } else if ($allowEnum !== 'no') { | |
| 1567 | + $result = $term . '*'; | |
| 1568 | + } | |
| 1569 | + return $result; | |
| 1570 | + } | |
| 1571 | + | |
| 1572 | + /** | |
| 1573 | + * returns the filter used for counting users | |
| 1574 | + * @return string | |
| 1575 | + */ | |
| 1576 | +    public function getFilterForUserCount() { | |
| 1577 | + $filter = $this->combineFilterWithAnd(array( | |
| 1578 | + $this->connection->ldapUserFilter, | |
| 1579 | + $this->connection->ldapUserDisplayName . '=*' | |
| 1580 | + )); | |
| 1581 | + | |
| 1582 | + return $filter; | |
| 1583 | + } | |
| 1584 | + | |
| 1585 | + /** | |
| 1586 | + * @param string $name | |
| 1587 | + * @param string $password | |
| 1588 | + * @return bool | |
| 1589 | + */ | |
| 1590 | +    public function areCredentialsValid($name, $password) { | |
| 1591 | + $name = $this->helper->DNasBaseParameter($name); | |
| 1592 | + $testConnection = clone $this->connection; | |
| 1593 | + $credentials = array( | |
| 1594 | + 'ldapAgentName' => $name, | |
| 1595 | + 'ldapAgentPassword' => $password | |
| 1596 | + ); | |
| 1597 | +        if(!$testConnection->setConfiguration($credentials)) { | |
| 1598 | + return false; | |
| 1599 | + } | |
| 1600 | + return $testConnection->bind(); | |
| 1601 | + } | |
| 1602 | + | |
| 1603 | + /** | |
| 1604 | + * reverse lookup of a DN given a known UUID | |
| 1605 | + * | |
| 1606 | + * @param string $uuid | |
| 1607 | + * @return string | |
| 1608 | + * @throws \Exception | |
| 1609 | + */ | |
| 1610 | +    public function getUserDnByUuid($uuid) { | |
| 1611 | + $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1612 | + $filter = $this->connection->ldapUserFilter; | |
| 1613 | + $base = $this->connection->ldapBaseUsers; | |
| 1614 | + | |
| 1615 | +        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') { | |
| 1616 | + // Sacrebleu! The UUID attribute is unknown :( We need first an | |
| 1617 | + // existing DN to be able to reliably detect it. | |
| 1618 | + $result = $this->search($filter, $base, ['dn'], 1); | |
| 1619 | +            if(!isset($result[0]) || !isset($result[0]['dn'])) { | |
| 1620 | +                throw new \Exception('Cannot determine UUID attribute'); | |
| 1621 | + } | |
| 1622 | + $dn = $result[0]['dn'][0]; | |
| 1623 | +            if(!$this->detectUuidAttribute($dn, true)) { | |
| 1624 | +                throw new \Exception('Cannot determine UUID attribute'); | |
| 1625 | + } | |
| 1626 | +        } else { | |
| 1627 | + // The UUID attribute is either known or an override is given. | |
| 1628 | + // By calling this method we ensure that $this->connection->$uuidAttr | |
| 1629 | + // is definitely set | |
| 1630 | +            if(!$this->detectUuidAttribute('', true)) { | |
| 1631 | +                throw new \Exception('Cannot determine UUID attribute'); | |
| 1632 | + } | |
| 1633 | + } | |
| 1634 | + | |
| 1635 | + $uuidAttr = $this->connection->ldapUuidUserAttribute; | |
| 1636 | +        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { | |
| 1637 | + $uuid = $this->formatGuid2ForFilterUser($uuid); | |
| 1638 | + } | |
| 1639 | + | |
| 1640 | + $filter = $uuidAttr . '=' . $uuid; | |
| 1641 | + $result = $this->searchUsers($filter, ['dn'], 2); | |
| 1642 | +        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { | |
| 1643 | + // we put the count into account to make sure that this is | |
| 1644 | + // really unique | |
| 1645 | + return $result[0]['dn'][0]; | |
| 1646 | + } | |
| 1647 | + | |
| 1648 | +        throw new \Exception('Cannot determine UUID attribute'); | |
| 1649 | + } | |
| 1650 | + | |
| 1651 | + /** | |
| 1652 | + * auto-detects the directory's UUID attribute | |
| 1653 | + * | |
| 1654 | + * @param string $dn a known DN used to check against | |
| 1655 | + * @param bool $isUser | |
| 1656 | + * @param bool $force the detection should be run, even if it is not set to auto | |
| 1657 | + * @param array|null $ldapRecord | |
| 1658 | + * @return bool true on success, false otherwise | |
| 1659 | + */ | |
| 1660 | +    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) { | |
| 1661 | +        if($isUser) { | |
| 1662 | + $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1663 | + $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1664 | +        } else { | |
| 1665 | + $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1666 | + $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1667 | + } | |
| 1668 | + | |
| 1669 | +        if(($this->connection->$uuidAttr !== 'auto') && !$force) { | |
| 1670 | + return true; | |
| 1671 | + } | |
| 1672 | + | |
| 1673 | +        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) { | |
| 1674 | + $this->connection->$uuidAttr = $uuidOverride; | |
| 1675 | + return true; | |
| 1676 | + } | |
| 1677 | + | |
| 1678 | +        foreach(self::UUID_ATTRIBUTES as $attribute) { | |
| 1679 | +            if($ldapRecord !== null) { | |
| 1680 | + // we have the info from LDAP already, we don't need to talk to the server again | |
| 1681 | +                if(isset($ldapRecord[$attribute])) { | |
| 1682 | + $this->connection->$uuidAttr = $attribute; | |
| 1683 | + return true; | |
| 1684 | +                } else { | |
| 1685 | + continue; | |
| 1686 | + } | |
| 1687 | + } | |
| 1688 | + | |
| 1689 | + $value = $this->readAttribute($dn, $attribute); | |
| 1690 | +            if(is_array($value) && isset($value[0]) && !empty($value[0])) { | |
| 1691 | + \OCP\Util::writeLog( | |
| 1692 | + 'user_ldap', | |
| 1693 | + 'Setting '.$attribute.' as '.$uuidAttr, | |
| 1694 | + ILogger::DEBUG | |
| 1695 | + ); | |
| 1696 | + $this->connection->$uuidAttr = $attribute; | |
| 1697 | + return true; | |
| 1698 | + } | |
| 1699 | + } | |
| 1700 | + \OCP\Util::writeLog( | |
| 1701 | + 'user_ldap', | |
| 1702 | + 'Could not autodetect the UUID attribute', | |
| 1703 | + ILogger::ERROR | |
| 1704 | + ); | |
| 1705 | + | |
| 1706 | + return false; | |
| 1707 | + } | |
| 1708 | + | |
| 1709 | + /** | |
| 1710 | + * @param string $dn | |
| 1711 | + * @param bool $isUser | |
| 1712 | + * @param null $ldapRecord | |
| 1713 | + * @return bool|string | |
| 1714 | + */ | |
| 1715 | +    public function getUUID($dn, $isUser = true, $ldapRecord = null) { | |
| 1716 | +        if($isUser) { | |
| 1717 | + $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1718 | + $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1719 | +        } else { | |
| 1720 | + $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1721 | + $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1722 | + } | |
| 1723 | + | |
| 1724 | + $uuid = false; | |
| 1725 | +        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { | |
| 1726 | + $attr = $this->connection->$uuidAttr; | |
| 1727 | + $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr); | |
| 1728 | + if( !is_array($uuid) | |
| 1729 | + && $uuidOverride !== '' | |
| 1730 | + && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) | |
| 1731 | +            { | |
| 1732 | + $uuid = isset($ldapRecord[$this->connection->$uuidAttr]) | |
| 1733 | + ? $ldapRecord[$this->connection->$uuidAttr] | |
| 1734 | + : $this->readAttribute($dn, $this->connection->$uuidAttr); | |
| 1735 | + } | |
| 1736 | +            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { | |
| 1737 | + $uuid = $uuid[0]; | |
| 1738 | + } | |
| 1739 | + } | |
| 1740 | + | |
| 1741 | + return $uuid; | |
| 1742 | + } | |
| 1743 | + | |
| 1744 | + /** | |
| 1745 | + * converts a binary ObjectGUID into a string representation | |
| 1746 | + * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD | |
| 1747 | + * @return string | |
| 1748 | + * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198 | |
| 1749 | + */ | |
| 1750 | +    private function convertObjectGUID2Str($oguid) { | |
| 1751 | + $hex_guid = bin2hex($oguid); | |
| 1752 | + $hex_guid_to_guid_str = ''; | |
| 1753 | +        for($k = 1; $k <= 4; ++$k) { | |
| 1754 | + $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); | |
| 1755 | + } | |
| 1756 | + $hex_guid_to_guid_str .= '-'; | |
| 1757 | +        for($k = 1; $k <= 2; ++$k) { | |
| 1758 | + $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); | |
| 1759 | + } | |
| 1760 | + $hex_guid_to_guid_str .= '-'; | |
| 1761 | +        for($k = 1; $k <= 2; ++$k) { | |
| 1762 | + $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); | |
| 1763 | + } | |
| 1764 | + $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); | |
| 1765 | + $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20); | |
| 1766 | + | |
| 1767 | + return strtoupper($hex_guid_to_guid_str); | |
| 1768 | + } | |
| 1769 | + | |
| 1770 | + /** | |
| 1771 | + * the first three blocks of the string-converted GUID happen to be in | |
| 1772 | + * reverse order. In order to use it in a filter, this needs to be | |
| 1773 | + * corrected. Furthermore the dashes need to be replaced and \\ preprended | |
| 1774 | + * to every two hax figures. | |
| 1775 | + * | |
| 1776 | + * If an invalid string is passed, it will be returned without change. | |
| 1777 | + * | |
| 1778 | + * @param string $guid | |
| 1779 | + * @return string | |
| 1780 | + */ | |
| 1781 | +    public function formatGuid2ForFilterUser($guid) { | |
| 1782 | +        if(!is_string($guid)) { | |
| 1783 | +            throw new \InvalidArgumentException('String expected'); | |
| 1784 | + } | |
| 1785 | +        $blocks = explode('-', $guid); | |
| 1786 | +        if(count($blocks) !== 5) { | |
| 1787 | + /* | |
| 1788 | 1788 | * Why not throw an Exception instead? This method is a utility | 
| 1789 | 1789 | * called only when trying to figure out whether a "missing" known | 
| 1790 | 1790 | * LDAP user was or was not renamed on the LDAP server. And this | 
| @@ -1795,279 +1795,279 @@ discard block | ||
| 1795 | 1795 | * an exception here would kill the experience for a valid, acting | 
| 1796 | 1796 | * user. Instead we write a log message. | 
| 1797 | 1797 | */ | 
| 1798 | - \OC::$server->getLogger()->info( | |
| 1799 | - 'Passed string does not resemble a valid GUID. Known UUID ' . | |
| 1800 | -				'({uuid}) probably does not match UUID configuration.', | |
| 1801 | - [ 'app' => 'user_ldap', 'uuid' => $guid ] | |
| 1802 | - ); | |
| 1803 | - return $guid; | |
| 1804 | - } | |
| 1805 | -		for($i=0; $i < 3; $i++) { | |
| 1806 | - $pairs = str_split($blocks[$i], 2); | |
| 1807 | - $pairs = array_reverse($pairs); | |
| 1808 | -			$blocks[$i] = implode('', $pairs); | |
| 1809 | - } | |
| 1810 | -		for($i=0; $i < 5; $i++) { | |
| 1811 | - $pairs = str_split($blocks[$i], 2); | |
| 1812 | -			$blocks[$i] = '\\' . implode('\\', $pairs); | |
| 1813 | - } | |
| 1814 | -		return implode('', $blocks); | |
| 1815 | - } | |
| 1816 | - | |
| 1817 | - /** | |
| 1818 | - * gets a SID of the domain of the given dn | |
| 1819 | - * @param string $dn | |
| 1820 | - * @return string|bool | |
| 1821 | - */ | |
| 1822 | -	public function getSID($dn) { | |
| 1823 | - $domainDN = $this->getDomainDNFromDN($dn); | |
| 1824 | - $cacheKey = 'getSID-'.$domainDN; | |
| 1825 | - $sid = $this->connection->getFromCache($cacheKey); | |
| 1826 | -		if(!is_null($sid)) { | |
| 1827 | - return $sid; | |
| 1828 | - } | |
| 1829 | - | |
| 1830 | - $objectSid = $this->readAttribute($domainDN, 'objectsid'); | |
| 1831 | -		if(!is_array($objectSid) || empty($objectSid)) { | |
| 1832 | - $this->connection->writeToCache($cacheKey, false); | |
| 1833 | - return false; | |
| 1834 | - } | |
| 1835 | - $domainObjectSid = $this->convertSID2Str($objectSid[0]); | |
| 1836 | - $this->connection->writeToCache($cacheKey, $domainObjectSid); | |
| 1837 | - | |
| 1838 | - return $domainObjectSid; | |
| 1839 | - } | |
| 1840 | - | |
| 1841 | - /** | |
| 1842 | - * converts a binary SID into a string representation | |
| 1843 | - * @param string $sid | |
| 1844 | - * @return string | |
| 1845 | - */ | |
| 1846 | -	public function convertSID2Str($sid) { | |
| 1847 | - // The format of a SID binary string is as follows: | |
| 1848 | - // 1 byte for the revision level | |
| 1849 | - // 1 byte for the number n of variable sub-ids | |
| 1850 | - // 6 bytes for identifier authority value | |
| 1851 | - // n*4 bytes for n sub-ids | |
| 1852 | - // | |
| 1853 | - // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f | |
| 1854 | - // Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444 | |
| 1855 | - $revision = ord($sid[0]); | |
| 1856 | - $numberSubID = ord($sid[1]); | |
| 1857 | - | |
| 1858 | - $subIdStart = 8; // 1 + 1 + 6 | |
| 1859 | - $subIdLength = 4; | |
| 1860 | -		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) { | |
| 1861 | - // Incorrect number of bytes present. | |
| 1862 | - return ''; | |
| 1863 | - } | |
| 1864 | - | |
| 1865 | - // 6 bytes = 48 bits can be represented using floats without loss of | |
| 1866 | - // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71) | |
| 1867 | - $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', ''); | |
| 1868 | - | |
| 1869 | - $subIDs = array(); | |
| 1870 | -		for ($i = 0; $i < $numberSubID; $i++) { | |
| 1871 | -			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength)); | |
| 1872 | -			$subIDs[] = sprintf('%u', $subID[1]); | |
| 1873 | - } | |
| 1874 | - | |
| 1875 | - // Result for example above: S-1-5-21-249921958-728525901-1594176202 | |
| 1876 | -		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs)); | |
| 1877 | - } | |
| 1878 | - | |
| 1879 | - /** | |
| 1880 | - * checks if the given DN is part of the given base DN(s) | |
| 1881 | - * @param string $dn the DN | |
| 1882 | - * @param string[] $bases array containing the allowed base DN or DNs | |
| 1883 | - * @return bool | |
| 1884 | - */ | |
| 1885 | -	public function isDNPartOfBase($dn, $bases) { | |
| 1886 | - $belongsToBase = false; | |
| 1887 | - $bases = $this->helper->sanitizeDN($bases); | |
| 1888 | - | |
| 1889 | -		foreach($bases as $base) { | |
| 1890 | - $belongsToBase = true; | |
| 1891 | -			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { | |
| 1892 | - $belongsToBase = false; | |
| 1893 | - } | |
| 1894 | -			if($belongsToBase) { | |
| 1895 | - break; | |
| 1896 | - } | |
| 1897 | - } | |
| 1898 | - return $belongsToBase; | |
| 1899 | - } | |
| 1900 | - | |
| 1901 | - /** | |
| 1902 | - * resets a running Paged Search operation | |
| 1903 | - * | |
| 1904 | - * @throws ServerNotAvailableException | |
| 1905 | - */ | |
| 1906 | -	private function abandonPagedSearch() { | |
| 1907 | - $cr = $this->connection->getConnectionResource(); | |
| 1908 | -		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie); | |
| 1909 | - $this->getPagedSearchResultState(); | |
| 1910 | - $this->lastCookie = ''; | |
| 1911 | - $this->cookies = []; | |
| 1912 | - } | |
| 1913 | - | |
| 1914 | - /** | |
| 1915 | - * get a cookie for the next LDAP paged search | |
| 1916 | - * @param string $base a string with the base DN for the search | |
| 1917 | - * @param string $filter the search filter to identify the correct search | |
| 1918 | - * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1919 | - * @param int $offset the offset for the new search to identify the correct search really good | |
| 1920 | - * @return string containing the key or empty if none is cached | |
| 1921 | - */ | |
| 1922 | -	private function getPagedResultCookie($base, $filter, $limit, $offset) { | |
| 1923 | -		if($offset === 0) { | |
| 1924 | - return ''; | |
| 1925 | - } | |
| 1926 | - $offset -= $limit; | |
| 1927 | - //we work with cache here | |
| 1928 | - $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; | |
| 1929 | - $cookie = ''; | |
| 1930 | -		if(isset($this->cookies[$cacheKey])) { | |
| 1931 | - $cookie = $this->cookies[$cacheKey]; | |
| 1932 | -			if(is_null($cookie)) { | |
| 1933 | - $cookie = ''; | |
| 1934 | - } | |
| 1935 | - } | |
| 1936 | - return $cookie; | |
| 1937 | - } | |
| 1938 | - | |
| 1939 | - /** | |
| 1940 | - * checks whether an LDAP paged search operation has more pages that can be | |
| 1941 | - * retrieved, typically when offset and limit are provided. | |
| 1942 | - * | |
| 1943 | - * Be very careful to use it: the last cookie value, which is inspected, can | |
| 1944 | - * be reset by other operations. Best, call it immediately after a search(), | |
| 1945 | - * searchUsers() or searchGroups() call. count-methods are probably safe as | |
| 1946 | - * well. Don't rely on it with any fetchList-method. | |
| 1947 | - * @return bool | |
| 1948 | - */ | |
| 1949 | -	public function hasMoreResults() { | |
| 1950 | -		if(empty($this->lastCookie) && $this->lastCookie !== '0') { | |
| 1951 | - // as in RFC 2696, when all results are returned, the cookie will | |
| 1952 | - // be empty. | |
| 1953 | - return false; | |
| 1954 | - } | |
| 1955 | - | |
| 1956 | - return true; | |
| 1957 | - } | |
| 1958 | - | |
| 1959 | - /** | |
| 1960 | - * set a cookie for LDAP paged search run | |
| 1961 | - * @param string $base a string with the base DN for the search | |
| 1962 | - * @param string $filter the search filter to identify the correct search | |
| 1963 | - * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1964 | - * @param int $offset the offset for the run search to identify the correct search really good | |
| 1965 | - * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response | |
| 1966 | - * @return void | |
| 1967 | - */ | |
| 1968 | -	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { | |
| 1969 | - // allow '0' for 389ds | |
| 1970 | -		if(!empty($cookie) || $cookie === '0') { | |
| 1971 | - $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; | |
| 1972 | - $this->cookies[$cacheKey] = $cookie; | |
| 1973 | - $this->lastCookie = $cookie; | |
| 1974 | - } | |
| 1975 | - } | |
| 1976 | - | |
| 1977 | - /** | |
| 1978 | - * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search. | |
| 1979 | - * @return boolean|null true on success, null or false otherwise | |
| 1980 | - */ | |
| 1981 | -	public function getPagedSearchResultState() { | |
| 1982 | - $result = $this->pagedSearchedSuccessful; | |
| 1983 | - $this->pagedSearchedSuccessful = null; | |
| 1984 | - return $result; | |
| 1985 | - } | |
| 1986 | - | |
| 1987 | - /** | |
| 1988 | - * Prepares a paged search, if possible | |
| 1989 | - * @param string $filter the LDAP filter for the search | |
| 1990 | - * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched | |
| 1991 | - * @param string[] $attr optional, when a certain attribute shall be filtered outside | |
| 1992 | - * @param int $limit | |
| 1993 | - * @param int $offset | |
| 1994 | - * @return bool|true | |
| 1995 | - */ | |
| 1996 | -	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) { | |
| 1997 | - $pagedSearchOK = false; | |
| 1998 | -		if ($limit !== 0) { | |
| 1999 | - $offset = (int)$offset; //can be null | |
| 2000 | -			\OCP\Util::writeLog('user_ldap', | |
| 2001 | - 'initializing paged search for Filter '.$filter.' base '.print_r($bases, true) | |
| 2002 | - .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, | |
| 2003 | - ILogger::DEBUG); | |
| 2004 | - //get the cookie from the search for the previous search, required by LDAP | |
| 2005 | -			foreach($bases as $base) { | |
| 2006 | - | |
| 2007 | - $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 2008 | -				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { | |
| 2009 | - // no cookie known from a potential previous search. We need | |
| 2010 | - // to start from 0 to come to the desired page. cookie value | |
| 2011 | - // of '0' is valid, because 389ds | |
| 2012 | - $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit; | |
| 2013 | - $this->search($filter, array($base), $attr, $limit, $reOffset, true); | |
| 2014 | - $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 2015 | - //still no cookie? obviously, the server does not like us. Let's skip paging efforts. | |
| 2016 | - // '0' is valid, because 389ds | |
| 2017 | - //TODO: remember this, probably does not change in the next request... | |
| 2018 | -					if(empty($cookie) && $cookie !== '0') { | |
| 2019 | - $cookie = null; | |
| 2020 | - } | |
| 2021 | - } | |
| 2022 | -				if(!is_null($cookie)) { | |
| 2023 | - //since offset = 0, this is a new search. We abandon other searches that might be ongoing. | |
| 2024 | - $this->abandonPagedSearch(); | |
| 2025 | -					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 2026 | - $this->connection->getConnectionResource(), $limit, | |
| 2027 | - false, $cookie); | |
| 2028 | -					if(!$pagedSearchOK) { | |
| 2029 | - return false; | |
| 2030 | - } | |
| 2031 | -					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG); | |
| 2032 | -				} else { | |
| 2033 | -					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset); | |
| 2034 | - \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]); | |
| 2035 | - } | |
| 2036 | - | |
| 2037 | - } | |
| 2038 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1798 | + \OC::$server->getLogger()->info( | |
| 1799 | + 'Passed string does not resemble a valid GUID. Known UUID ' . | |
| 1800 | +                '({uuid}) probably does not match UUID configuration.', | |
| 1801 | + [ 'app' => 'user_ldap', 'uuid' => $guid ] | |
| 1802 | + ); | |
| 1803 | + return $guid; | |
| 1804 | + } | |
| 1805 | +        for($i=0; $i < 3; $i++) { | |
| 1806 | + $pairs = str_split($blocks[$i], 2); | |
| 1807 | + $pairs = array_reverse($pairs); | |
| 1808 | +            $blocks[$i] = implode('', $pairs); | |
| 1809 | + } | |
| 1810 | +        for($i=0; $i < 5; $i++) { | |
| 1811 | + $pairs = str_split($blocks[$i], 2); | |
| 1812 | +            $blocks[$i] = '\\' . implode('\\', $pairs); | |
| 1813 | + } | |
| 1814 | +        return implode('', $blocks); | |
| 1815 | + } | |
| 1816 | + | |
| 1817 | + /** | |
| 1818 | + * gets a SID of the domain of the given dn | |
| 1819 | + * @param string $dn | |
| 1820 | + * @return string|bool | |
| 1821 | + */ | |
| 1822 | +    public function getSID($dn) { | |
| 1823 | + $domainDN = $this->getDomainDNFromDN($dn); | |
| 1824 | + $cacheKey = 'getSID-'.$domainDN; | |
| 1825 | + $sid = $this->connection->getFromCache($cacheKey); | |
| 1826 | +        if(!is_null($sid)) { | |
| 1827 | + return $sid; | |
| 1828 | + } | |
| 1829 | + | |
| 1830 | + $objectSid = $this->readAttribute($domainDN, 'objectsid'); | |
| 1831 | +        if(!is_array($objectSid) || empty($objectSid)) { | |
| 1832 | + $this->connection->writeToCache($cacheKey, false); | |
| 1833 | + return false; | |
| 1834 | + } | |
| 1835 | + $domainObjectSid = $this->convertSID2Str($objectSid[0]); | |
| 1836 | + $this->connection->writeToCache($cacheKey, $domainObjectSid); | |
| 1837 | + | |
| 1838 | + return $domainObjectSid; | |
| 1839 | + } | |
| 1840 | + | |
| 1841 | + /** | |
| 1842 | + * converts a binary SID into a string representation | |
| 1843 | + * @param string $sid | |
| 1844 | + * @return string | |
| 1845 | + */ | |
| 1846 | +    public function convertSID2Str($sid) { | |
| 1847 | + // The format of a SID binary string is as follows: | |
| 1848 | + // 1 byte for the revision level | |
| 1849 | + // 1 byte for the number n of variable sub-ids | |
| 1850 | + // 6 bytes for identifier authority value | |
| 1851 | + // n*4 bytes for n sub-ids | |
| 1852 | + // | |
| 1853 | + // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f | |
| 1854 | + // Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444 | |
| 1855 | + $revision = ord($sid[0]); | |
| 1856 | + $numberSubID = ord($sid[1]); | |
| 1857 | + | |
| 1858 | + $subIdStart = 8; // 1 + 1 + 6 | |
| 1859 | + $subIdLength = 4; | |
| 1860 | +        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) { | |
| 1861 | + // Incorrect number of bytes present. | |
| 1862 | + return ''; | |
| 1863 | + } | |
| 1864 | + | |
| 1865 | + // 6 bytes = 48 bits can be represented using floats without loss of | |
| 1866 | + // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71) | |
| 1867 | + $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', ''); | |
| 1868 | + | |
| 1869 | + $subIDs = array(); | |
| 1870 | +        for ($i = 0; $i < $numberSubID; $i++) { | |
| 1871 | +            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength)); | |
| 1872 | +            $subIDs[] = sprintf('%u', $subID[1]); | |
| 1873 | + } | |
| 1874 | + | |
| 1875 | + // Result for example above: S-1-5-21-249921958-728525901-1594176202 | |
| 1876 | +        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs)); | |
| 1877 | + } | |
| 1878 | + | |
| 1879 | + /** | |
| 1880 | + * checks if the given DN is part of the given base DN(s) | |
| 1881 | + * @param string $dn the DN | |
| 1882 | + * @param string[] $bases array containing the allowed base DN or DNs | |
| 1883 | + * @return bool | |
| 1884 | + */ | |
| 1885 | +    public function isDNPartOfBase($dn, $bases) { | |
| 1886 | + $belongsToBase = false; | |
| 1887 | + $bases = $this->helper->sanitizeDN($bases); | |
| 1888 | + | |
| 1889 | +        foreach($bases as $base) { | |
| 1890 | + $belongsToBase = true; | |
| 1891 | +            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { | |
| 1892 | + $belongsToBase = false; | |
| 1893 | + } | |
| 1894 | +            if($belongsToBase) { | |
| 1895 | + break; | |
| 1896 | + } | |
| 1897 | + } | |
| 1898 | + return $belongsToBase; | |
| 1899 | + } | |
| 1900 | + | |
| 1901 | + /** | |
| 1902 | + * resets a running Paged Search operation | |
| 1903 | + * | |
| 1904 | + * @throws ServerNotAvailableException | |
| 1905 | + */ | |
| 1906 | +    private function abandonPagedSearch() { | |
| 1907 | + $cr = $this->connection->getConnectionResource(); | |
| 1908 | +        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie); | |
| 1909 | + $this->getPagedSearchResultState(); | |
| 1910 | + $this->lastCookie = ''; | |
| 1911 | + $this->cookies = []; | |
| 1912 | + } | |
| 1913 | + | |
| 1914 | + /** | |
| 1915 | + * get a cookie for the next LDAP paged search | |
| 1916 | + * @param string $base a string with the base DN for the search | |
| 1917 | + * @param string $filter the search filter to identify the correct search | |
| 1918 | + * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1919 | + * @param int $offset the offset for the new search to identify the correct search really good | |
| 1920 | + * @return string containing the key or empty if none is cached | |
| 1921 | + */ | |
| 1922 | +    private function getPagedResultCookie($base, $filter, $limit, $offset) { | |
| 1923 | +        if($offset === 0) { | |
| 1924 | + return ''; | |
| 1925 | + } | |
| 1926 | + $offset -= $limit; | |
| 1927 | + //we work with cache here | |
| 1928 | + $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; | |
| 1929 | + $cookie = ''; | |
| 1930 | +        if(isset($this->cookies[$cacheKey])) { | |
| 1931 | + $cookie = $this->cookies[$cacheKey]; | |
| 1932 | +            if(is_null($cookie)) { | |
| 1933 | + $cookie = ''; | |
| 1934 | + } | |
| 1935 | + } | |
| 1936 | + return $cookie; | |
| 1937 | + } | |
| 1938 | + | |
| 1939 | + /** | |
| 1940 | + * checks whether an LDAP paged search operation has more pages that can be | |
| 1941 | + * retrieved, typically when offset and limit are provided. | |
| 1942 | + * | |
| 1943 | + * Be very careful to use it: the last cookie value, which is inspected, can | |
| 1944 | + * be reset by other operations. Best, call it immediately after a search(), | |
| 1945 | + * searchUsers() or searchGroups() call. count-methods are probably safe as | |
| 1946 | + * well. Don't rely on it with any fetchList-method. | |
| 1947 | + * @return bool | |
| 1948 | + */ | |
| 1949 | +    public function hasMoreResults() { | |
| 1950 | +        if(empty($this->lastCookie) && $this->lastCookie !== '0') { | |
| 1951 | + // as in RFC 2696, when all results are returned, the cookie will | |
| 1952 | + // be empty. | |
| 1953 | + return false; | |
| 1954 | + } | |
| 1955 | + | |
| 1956 | + return true; | |
| 1957 | + } | |
| 1958 | + | |
| 1959 | + /** | |
| 1960 | + * set a cookie for LDAP paged search run | |
| 1961 | + * @param string $base a string with the base DN for the search | |
| 1962 | + * @param string $filter the search filter to identify the correct search | |
| 1963 | + * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1964 | + * @param int $offset the offset for the run search to identify the correct search really good | |
| 1965 | + * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response | |
| 1966 | + * @return void | |
| 1967 | + */ | |
| 1968 | +    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { | |
| 1969 | + // allow '0' for 389ds | |
| 1970 | +        if(!empty($cookie) || $cookie === '0') { | |
| 1971 | + $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; | |
| 1972 | + $this->cookies[$cacheKey] = $cookie; | |
| 1973 | + $this->lastCookie = $cookie; | |
| 1974 | + } | |
| 1975 | + } | |
| 1976 | + | |
| 1977 | + /** | |
| 1978 | + * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search. | |
| 1979 | + * @return boolean|null true on success, null or false otherwise | |
| 1980 | + */ | |
| 1981 | +    public function getPagedSearchResultState() { | |
| 1982 | + $result = $this->pagedSearchedSuccessful; | |
| 1983 | + $this->pagedSearchedSuccessful = null; | |
| 1984 | + return $result; | |
| 1985 | + } | |
| 1986 | + | |
| 1987 | + /** | |
| 1988 | + * Prepares a paged search, if possible | |
| 1989 | + * @param string $filter the LDAP filter for the search | |
| 1990 | + * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched | |
| 1991 | + * @param string[] $attr optional, when a certain attribute shall be filtered outside | |
| 1992 | + * @param int $limit | |
| 1993 | + * @param int $offset | |
| 1994 | + * @return bool|true | |
| 1995 | + */ | |
| 1996 | +    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) { | |
| 1997 | + $pagedSearchOK = false; | |
| 1998 | +        if ($limit !== 0) { | |
| 1999 | + $offset = (int)$offset; //can be null | |
| 2000 | +            \OCP\Util::writeLog('user_ldap', | |
| 2001 | + 'initializing paged search for Filter '.$filter.' base '.print_r($bases, true) | |
| 2002 | + .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, | |
| 2003 | + ILogger::DEBUG); | |
| 2004 | + //get the cookie from the search for the previous search, required by LDAP | |
| 2005 | +            foreach($bases as $base) { | |
| 2006 | + | |
| 2007 | + $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 2008 | +                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { | |
| 2009 | + // no cookie known from a potential previous search. We need | |
| 2010 | + // to start from 0 to come to the desired page. cookie value | |
| 2011 | + // of '0' is valid, because 389ds | |
| 2012 | + $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit; | |
| 2013 | + $this->search($filter, array($base), $attr, $limit, $reOffset, true); | |
| 2014 | + $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 2015 | + //still no cookie? obviously, the server does not like us. Let's skip paging efforts. | |
| 2016 | + // '0' is valid, because 389ds | |
| 2017 | + //TODO: remember this, probably does not change in the next request... | |
| 2018 | +                    if(empty($cookie) && $cookie !== '0') { | |
| 2019 | + $cookie = null; | |
| 2020 | + } | |
| 2021 | + } | |
| 2022 | +                if(!is_null($cookie)) { | |
| 2023 | + //since offset = 0, this is a new search. We abandon other searches that might be ongoing. | |
| 2024 | + $this->abandonPagedSearch(); | |
| 2025 | +                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 2026 | + $this->connection->getConnectionResource(), $limit, | |
| 2027 | + false, $cookie); | |
| 2028 | +                    if(!$pagedSearchOK) { | |
| 2029 | + return false; | |
| 2030 | + } | |
| 2031 | +                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG); | |
| 2032 | +                } else { | |
| 2033 | +                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset); | |
| 2034 | + \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]); | |
| 2035 | + } | |
| 2036 | + | |
| 2037 | + } | |
| 2038 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 2039 | 2039 | * We coudn't get paged searches working with our RHDS for login ($limit = 0), | 
| 2040 | 2040 | * due to pages with zero results. | 
| 2041 | 2041 | * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination | 
| 2042 | 2042 | * if we don't have a previous paged search. | 
| 2043 | 2043 | */ | 
| 2044 | -		} else if ($limit === 0 && !empty($this->lastCookie)) { | |
| 2045 | - // a search without limit was requested. However, if we do use | |
| 2046 | - // Paged Search once, we always must do it. This requires us to | |
| 2047 | - // initialize it with the configured page size. | |
| 2048 | - $this->abandonPagedSearch(); | |
| 2049 | - // in case someone set it to 0 … use 500, otherwise no results will | |
| 2050 | - // be returned. | |
| 2051 | - $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500; | |
| 2052 | -			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 2053 | - $this->connection->getConnectionResource(), | |
| 2054 | - $pageSize, false, ''); | |
| 2055 | - } | |
| 2056 | - | |
| 2057 | - return $pagedSearchOK; | |
| 2058 | - } | |
| 2059 | - | |
| 2060 | - /** | |
| 2061 | - * Is more than one $attr used for search? | |
| 2062 | - * | |
| 2063 | - * @param string|string[]|null $attr | |
| 2064 | - * @return bool | |
| 2065 | - */ | |
| 2066 | -	private function manyAttributes($attr): bool { | |
| 2067 | -		if (\is_array($attr)) { | |
| 2068 | - return \count($attr) > 1; | |
| 2069 | - } | |
| 2070 | - return false; | |
| 2071 | - } | |
| 2044 | +        } else if ($limit === 0 && !empty($this->lastCookie)) { | |
| 2045 | + // a search without limit was requested. However, if we do use | |
| 2046 | + // Paged Search once, we always must do it. This requires us to | |
| 2047 | + // initialize it with the configured page size. | |
| 2048 | + $this->abandonPagedSearch(); | |
| 2049 | + // in case someone set it to 0 … use 500, otherwise no results will | |
| 2050 | + // be returned. | |
| 2051 | + $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500; | |
| 2052 | +            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 2053 | + $this->connection->getConnectionResource(), | |
| 2054 | + $pageSize, false, ''); | |
| 2055 | + } | |
| 2056 | + | |
| 2057 | + return $pagedSearchOK; | |
| 2058 | + } | |
| 2059 | + | |
| 2060 | + /** | |
| 2061 | + * Is more than one $attr used for search? | |
| 2062 | + * | |
| 2063 | + * @param string|string[]|null $attr | |
| 2064 | + * @return bool | |
| 2065 | + */ | |
| 2066 | +    private function manyAttributes($attr): bool { | |
| 2067 | +        if (\is_array($attr)) { | |
| 2068 | + return \count($attr) > 1; | |
| 2069 | + } | |
| 2070 | + return false; | |
| 2071 | + } | |
| 2072 | 2072 | |
| 2073 | 2073 | } | 
| @@ -129,7 +129,7 @@ discard block | ||
| 129 | 129 | * @return AbstractMapping | 
| 130 | 130 | */ | 
| 131 | 131 |  	public function getUserMapper() { | 
| 132 | -		if(is_null($this->userMapper)) { | |
| 132 | +		if (is_null($this->userMapper)) { | |
| 133 | 133 |  			throw new \Exception('UserMapper was not assigned to this Access instance.'); | 
| 134 | 134 | } | 
| 135 | 135 | return $this->userMapper; | 
| @@ -149,7 +149,7 @@ discard block | ||
| 149 | 149 | * @return AbstractMapping | 
| 150 | 150 | */ | 
| 151 | 151 |  	public function getGroupMapper() { | 
| 152 | -		if(is_null($this->groupMapper)) { | |
| 152 | +		if (is_null($this->groupMapper)) { | |
| 153 | 153 |  			throw new \Exception('GroupMapper was not assigned to this Access instance.'); | 
| 154 | 154 | } | 
| 155 | 155 | return $this->groupMapper; | 
| @@ -182,14 +182,14 @@ discard block | ||
| 182 | 182 | * @throws ServerNotAvailableException | 
| 183 | 183 | */ | 
| 184 | 184 |  	public function readAttribute($dn, $attr, $filter = 'objectClass=*') { | 
| 185 | -		if(!$this->checkConnection()) { | |
| 185 | +		if (!$this->checkConnection()) { | |
| 186 | 186 |  			\OCP\Util::writeLog('user_ldap', | 
| 187 | 187 | 'No LDAP Connector assigned, access impossible for readAttribute.', | 
| 188 | 188 | ILogger::WARN); | 
| 189 | 189 | return false; | 
| 190 | 190 | } | 
| 191 | 191 | $cr = $this->connection->getConnectionResource(); | 
| 192 | -		if(!$this->ldap->isResource($cr)) { | |
| 192 | +		if (!$this->ldap->isResource($cr)) { | |
| 193 | 193 | //LDAP not available | 
| 194 | 194 |  			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); | 
| 195 | 195 | return false; | 
| @@ -199,7 +199,7 @@ discard block | ||
| 199 | 199 | $this->abandonPagedSearch(); | 
| 200 | 200 | // openLDAP requires that we init a new Paged Search. Not needed by AD, | 
| 201 | 201 | // but does not hurt either. | 
| 202 | - $pagingSize = (int)$this->connection->ldapPagingSize; | |
| 202 | + $pagingSize = (int) $this->connection->ldapPagingSize; | |
| 203 | 203 | // 0 won't result in replies, small numbers may leave out groups | 
| 204 | 204 | // (cf. #12306), 500 is default for paging and should work everywhere. | 
| 205 | 205 | $maxResults = $pagingSize > 20 ? $pagingSize : 500; | 
| @@ -212,7 +212,7 @@ discard block | ||
| 212 | 212 | $isRangeRequest = false; | 
| 213 | 213 |  		do { | 
| 214 | 214 | $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); | 
| 215 | -			if(is_bool($result)) { | |
| 215 | +			if (is_bool($result)) { | |
| 216 | 216 | // when an exists request was run and it was successful, an empty | 
| 217 | 217 | // array must be returned | 
| 218 | 218 | return $result ? [] : false; | 
| @@ -229,22 +229,22 @@ discard block | ||
| 229 | 229 | $result = $this->extractRangeData($result, $attr); | 
| 230 | 230 |  			if (!empty($result)) { | 
| 231 | 231 | $normalizedResult = $this->extractAttributeValuesFromResult( | 
| 232 | - [ $attr => $result['values'] ], | |
| 232 | + [$attr => $result['values']], | |
| 233 | 233 | $attr | 
| 234 | 234 | ); | 
| 235 | 235 | $values = array_merge($values, $normalizedResult); | 
| 236 | 236 | |
| 237 | -				if($result['rangeHigh'] === '*') { | |
| 237 | +				if ($result['rangeHigh'] === '*') { | |
| 238 | 238 | // when server replies with * as high range value, there are | 
| 239 | 239 | // no more results left | 
| 240 | 240 | return $values; | 
| 241 | 241 |  				} else { | 
| 242 | - $low = $result['rangeHigh'] + 1; | |
| 243 | - $attrToRead = $result['attributeName'] . ';range=' . $low . '-*'; | |
| 242 | + $low = $result['rangeHigh'] + 1; | |
| 243 | + $attrToRead = $result['attributeName'].';range='.$low.'-*'; | |
| 244 | 244 | $isRangeRequest = true; | 
| 245 | 245 | } | 
| 246 | 246 | } | 
| 247 | - } while($isRangeRequest); | |
| 247 | + } while ($isRangeRequest); | |
| 248 | 248 | |
| 249 | 249 |  		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG); | 
| 250 | 250 | return false; | 
| @@ -270,13 +270,13 @@ discard block | ||
| 270 | 270 |  		if (!$this->ldap->isResource($rr)) { | 
| 271 | 271 |  			if ($attribute !== '') { | 
| 272 | 272 | //do not throw this message on userExists check, irritates | 
| 273 | -				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG); | |
| 273 | +				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, ILogger::DEBUG); | |
| 274 | 274 | } | 
| 275 | 275 | //in case an error occurs , e.g. object does not exist | 
| 276 | 276 | return false; | 
| 277 | 277 | } | 
| 278 | 278 |  		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) { | 
| 279 | -			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG); | |
| 279 | +			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', ILogger::DEBUG); | |
| 280 | 280 | return true; | 
| 281 | 281 | } | 
| 282 | 282 |  		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr); | 
| @@ -301,12 +301,12 @@ discard block | ||
| 301 | 301 | */ | 
| 302 | 302 |  	public function extractAttributeValuesFromResult($result, $attribute) { | 
| 303 | 303 | $values = []; | 
| 304 | -		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { | |
| 304 | +		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) { | |
| 305 | 305 | $lowercaseAttribute = strtolower($attribute); | 
| 306 | -			for($i=0;$i<$result[$attribute]['count'];$i++) { | |
| 307 | -				if($this->resemblesDN($attribute)) { | |
| 306 | +			for ($i = 0; $i < $result[$attribute]['count']; $i++) { | |
| 307 | +				if ($this->resemblesDN($attribute)) { | |
| 308 | 308 | $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); | 
| 309 | -				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { | |
| 309 | +				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { | |
| 310 | 310 | $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); | 
| 311 | 311 |  				} else { | 
| 312 | 312 | $values[] = $result[$attribute][$i]; | 
| @@ -328,10 +328,10 @@ discard block | ||
| 328 | 328 | */ | 
| 329 | 329 |  	public function extractRangeData($result, $attribute) { | 
| 330 | 330 | $keys = array_keys($result); | 
| 331 | -		foreach($keys as $key) { | |
| 332 | -			if($key !== $attribute && strpos($key, $attribute) === 0) { | |
| 331 | +		foreach ($keys as $key) { | |
| 332 | +			if ($key !== $attribute && strpos($key, $attribute) === 0) { | |
| 333 | 333 |  				$queryData = explode(';', $key); | 
| 334 | -				if(strpos($queryData[1], 'range=') === 0) { | |
| 334 | +				if (strpos($queryData[1], 'range=') === 0) { | |
| 335 | 335 | $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); | 
| 336 | 336 | $data = [ | 
| 337 | 337 | 'values' => $result[$key], | 
| @@ -356,18 +356,18 @@ discard block | ||
| 356 | 356 | * @throws \Exception | 
| 357 | 357 | */ | 
| 358 | 358 |  	public function setPassword($userDN, $password) { | 
| 359 | -		if((int)$this->connection->turnOnPasswordChange !== 1) { | |
| 359 | +		if ((int) $this->connection->turnOnPasswordChange !== 1) { | |
| 360 | 360 |  			throw new \Exception('LDAP password changes are disabled.'); | 
| 361 | 361 | } | 
| 362 | 362 | $cr = $this->connection->getConnectionResource(); | 
| 363 | -		if(!$this->ldap->isResource($cr)) { | |
| 363 | +		if (!$this->ldap->isResource($cr)) { | |
| 364 | 364 | //LDAP not available | 
| 365 | 365 |  			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG); | 
| 366 | 366 | return false; | 
| 367 | 367 | } | 
| 368 | 368 |  		try { | 
| 369 | 369 |  			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); | 
| 370 | -		} catch(ConstraintViolationException $e) { | |
| 370 | +		} catch (ConstraintViolationException $e) { | |
| 371 | 371 |  			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); | 
| 372 | 372 | } | 
| 373 | 373 | } | 
| @@ -409,17 +409,17 @@ discard block | ||
| 409 | 409 | */ | 
| 410 | 410 |  	public function getDomainDNFromDN($dn) { | 
| 411 | 411 | $allParts = $this->ldap->explodeDN($dn, 0); | 
| 412 | -		if($allParts === false) { | |
| 412 | +		if ($allParts === false) { | |
| 413 | 413 | //not a valid DN | 
| 414 | 414 | return ''; | 
| 415 | 415 | } | 
| 416 | 416 | $domainParts = array(); | 
| 417 | 417 | $dcFound = false; | 
| 418 | -		foreach($allParts as $part) { | |
| 419 | -			if(!$dcFound && strpos($part, 'dc=') === 0) { | |
| 418 | +		foreach ($allParts as $part) { | |
| 419 | +			if (!$dcFound && strpos($part, 'dc=') === 0) { | |
| 420 | 420 | $dcFound = true; | 
| 421 | 421 | } | 
| 422 | -			if($dcFound) { | |
| 422 | +			if ($dcFound) { | |
| 423 | 423 | $domainParts[] = $part; | 
| 424 | 424 | } | 
| 425 | 425 | } | 
| @@ -445,7 +445,7 @@ discard block | ||
| 445 | 445 | |
| 446 | 446 | //Check whether the DN belongs to the Base, to avoid issues on multi- | 
| 447 | 447 | //server setups | 
| 448 | -		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 448 | +		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 449 | 449 | return $fdn; | 
| 450 | 450 | } | 
| 451 | 451 | |
| @@ -462,7 +462,7 @@ discard block | ||
| 462 | 462 | //To avoid bypassing the base DN settings under certain circumstances | 
| 463 | 463 | //with the group support, check whether the provided DN matches one of | 
| 464 | 464 | //the given Bases | 
| 465 | -		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { | |
| 465 | +		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { | |
| 466 | 466 | return false; | 
| 467 | 467 | } | 
| 468 | 468 | |
| @@ -480,11 +480,11 @@ discard block | ||
| 480 | 480 | */ | 
| 481 | 481 |  	public function groupsMatchFilter($groupDNs) { | 
| 482 | 482 | $validGroupDNs = []; | 
| 483 | -		foreach($groupDNs as $dn) { | |
| 483 | +		foreach ($groupDNs as $dn) { | |
| 484 | 484 | $cacheKey = 'groupsMatchFilter-'.$dn; | 
| 485 | 485 | $groupMatchFilter = $this->connection->getFromCache($cacheKey); | 
| 486 | -			if(!is_null($groupMatchFilter)) { | |
| 487 | -				if($groupMatchFilter) { | |
| 486 | +			if (!is_null($groupMatchFilter)) { | |
| 487 | +				if ($groupMatchFilter) { | |
| 488 | 488 | $validGroupDNs[] = $dn; | 
| 489 | 489 | } | 
| 490 | 490 | continue; | 
| @@ -492,13 +492,13 @@ discard block | ||
| 492 | 492 | |
| 493 | 493 | // Check the base DN first. If this is not met already, we don't | 
| 494 | 494 | // need to ask the server at all. | 
| 495 | -			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { | |
| 495 | +			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { | |
| 496 | 496 | $this->connection->writeToCache($cacheKey, false); | 
| 497 | 497 | continue; | 
| 498 | 498 | } | 
| 499 | 499 | |
| 500 | 500 | $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter); | 
| 501 | -			if(is_array($result)) { | |
| 501 | +			if (is_array($result)) { | |
| 502 | 502 | $this->connection->writeToCache($cacheKey, true); | 
| 503 | 503 | $validGroupDNs[] = $dn; | 
| 504 | 504 |  			} else { | 
| @@ -519,7 +519,7 @@ discard block | ||
| 519 | 519 | //To avoid bypassing the base DN settings under certain circumstances | 
| 520 | 520 | //with the group support, check whether the provided DN matches one of | 
| 521 | 521 | //the given Bases | 
| 522 | -		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 522 | +		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 523 | 523 | return false; | 
| 524 | 524 | } | 
| 525 | 525 | |
| @@ -539,7 +539,7 @@ discard block | ||
| 539 | 539 | */ | 
| 540 | 540 |  	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) { | 
| 541 | 541 | $newlyMapped = false; | 
| 542 | -		if($isUser) { | |
| 542 | +		if ($isUser) { | |
| 543 | 543 | $mapper = $this->getUserMapper(); | 
| 544 | 544 | $nameAttribute = $this->connection->ldapUserDisplayName; | 
| 545 | 545 | $filter = $this->connection->ldapUserFilter; | 
| @@ -551,15 +551,15 @@ discard block | ||
| 551 | 551 | |
| 552 | 552 | //let's try to retrieve the Nextcloud name from the mappings table | 
| 553 | 553 | $ncName = $mapper->getNameByDN($fdn); | 
| 554 | -		if(is_string($ncName)) { | |
| 554 | +		if (is_string($ncName)) { | |
| 555 | 555 | return $ncName; | 
| 556 | 556 | } | 
| 557 | 557 | |
| 558 | 558 | //second try: get the UUID and check if it is known. Then, update the DN and return the name. | 
| 559 | 559 | $uuid = $this->getUUID($fdn, $isUser, $record); | 
| 560 | -		if(is_string($uuid)) { | |
| 560 | +		if (is_string($uuid)) { | |
| 561 | 561 | $ncName = $mapper->getNameByUUID($uuid); | 
| 562 | -			if(is_string($ncName)) { | |
| 562 | +			if (is_string($ncName)) { | |
| 563 | 563 | $mapper->setDNbyUUID($fdn, $uuid); | 
| 564 | 564 | return $ncName; | 
| 565 | 565 | } | 
| @@ -569,17 +569,17 @@ discard block | ||
| 569 | 569 | return false; | 
| 570 | 570 | } | 
| 571 | 571 | |
| 572 | -		if(is_null($ldapName)) { | |
| 572 | +		if (is_null($ldapName)) { | |
| 573 | 573 | $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter); | 
| 574 | -			if(!isset($ldapName[0]) && empty($ldapName[0])) { | |
| 574 | +			if (!isset($ldapName[0]) && empty($ldapName[0])) { | |
| 575 | 575 |  				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO); | 
| 576 | 576 | return false; | 
| 577 | 577 | } | 
| 578 | 578 | $ldapName = $ldapName[0]; | 
| 579 | 579 | } | 
| 580 | 580 | |
| 581 | -		if($isUser) { | |
| 582 | - $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr; | |
| 581 | +		if ($isUser) { | |
| 582 | + $usernameAttribute = (string) $this->connection->ldapExpertUsernameAttr; | |
| 583 | 583 |  			if ($usernameAttribute !== '') { | 
| 584 | 584 | $username = $this->readAttribute($fdn, $usernameAttribute); | 
| 585 | 585 | $username = $username[0]; | 
| @@ -609,14 +609,14 @@ discard block | ||
| 609 | 609 | // outside of core user management will still cache the user as non-existing. | 
| 610 | 610 | $originalTTL = $this->connection->ldapCacheTTL; | 
| 611 | 611 | $this->connection->setConfiguration(['ldapCacheTTL' => 0]); | 
| 612 | - if( $intName !== '' | |
| 612 | + if ($intName !== '' | |
| 613 | 613 | && (($isUser && !$this->ncUserManager->userExists($intName)) | 
| 614 | 614 | || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName)) | 
| 615 | 615 | ) | 
| 616 | 616 |  		) { | 
| 617 | 617 | $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); | 
| 618 | 618 | $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser); | 
| 619 | -			if($newlyMapped) { | |
| 619 | +			if ($newlyMapped) { | |
| 620 | 620 | return $intName; | 
| 621 | 621 | } | 
| 622 | 622 | } | 
| @@ -624,7 +624,7 @@ discard block | ||
| 624 | 624 | $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]); | 
| 625 | 625 | $altName = $this->createAltInternalOwnCloudName($intName, $isUser); | 
| 626 | 626 |  		if (is_string($altName)) { | 
| 627 | -			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { | |
| 627 | +			if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) { | |
| 628 | 628 | $newlyMapped = true; | 
| 629 | 629 | return $altName; | 
| 630 | 630 | } | 
| @@ -642,7 +642,7 @@ discard block | ||
| 642 | 642 | string $uuid, | 
| 643 | 643 | bool $isUser | 
| 644 | 644 |  	) :bool { | 
| 645 | -		if($mapper->map($fdn, $name, $uuid)) { | |
| 645 | +		if ($mapper->map($fdn, $name, $uuid)) { | |
| 646 | 646 |  			if ($this->ncUserManager instanceof PublicEmitter && $isUser) { | 
| 647 | 647 | $this->cacheUserExists($name); | 
| 648 | 648 |  				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]); | 
| @@ -681,7 +681,7 @@ discard block | ||
| 681 | 681 | * @throws \Exception | 
| 682 | 682 | */ | 
| 683 | 683 |  	private function ldap2NextcloudNames($ldapObjects, $isUsers) { | 
| 684 | -		if($isUsers) { | |
| 684 | +		if ($isUsers) { | |
| 685 | 685 | $nameAttribute = $this->connection->ldapUserDisplayName; | 
| 686 | 686 | $sndAttribute = $this->connection->ldapUserDisplayName2; | 
| 687 | 687 |  		} else { | 
| @@ -689,9 +689,9 @@ discard block | ||
| 689 | 689 | } | 
| 690 | 690 | $nextcloudNames = []; | 
| 691 | 691 | |
| 692 | -		foreach($ldapObjects as $ldapObject) { | |
| 692 | +		foreach ($ldapObjects as $ldapObject) { | |
| 693 | 693 | $nameByLDAP = null; | 
| 694 | - if( isset($ldapObject[$nameAttribute]) | |
| 694 | + if (isset($ldapObject[$nameAttribute]) | |
| 695 | 695 | && is_array($ldapObject[$nameAttribute]) | 
| 696 | 696 | && isset($ldapObject[$nameAttribute][0]) | 
| 697 | 697 |  			) { | 
| @@ -700,19 +700,19 @@ discard block | ||
| 700 | 700 | } | 
| 701 | 701 | |
| 702 | 702 | $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); | 
| 703 | -			if($ncName) { | |
| 703 | +			if ($ncName) { | |
| 704 | 704 | $nextcloudNames[] = $ncName; | 
| 705 | -				if($isUsers) { | |
| 705 | +				if ($isUsers) { | |
| 706 | 706 | $this->updateUserState($ncName); | 
| 707 | 707 | //cache the user names so it does not need to be retrieved | 
| 708 | 708 | //again later (e.g. sharing dialogue). | 
| 709 | -					if(is_null($nameByLDAP)) { | |
| 709 | +					if (is_null($nameByLDAP)) { | |
| 710 | 710 | continue; | 
| 711 | 711 | } | 
| 712 | 712 | $sndName = isset($ldapObject[$sndAttribute][0]) | 
| 713 | 713 | ? $ldapObject[$sndAttribute][0] : ''; | 
| 714 | 714 | $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); | 
| 715 | -				} else if($nameByLDAP !== null) { | |
| 715 | +				} else if ($nameByLDAP !== null) { | |
| 716 | 716 | $this->cacheGroupDisplayName($ncName, $nameByLDAP); | 
| 717 | 717 | } | 
| 718 | 718 | } | 
| @@ -728,7 +728,7 @@ discard block | ||
| 728 | 728 | */ | 
| 729 | 729 |  	public function updateUserState($ncname) { | 
| 730 | 730 | $user = $this->userManager->get($ncname); | 
| 731 | -		if($user instanceof OfflineUser) { | |
| 731 | +		if ($user instanceof OfflineUser) { | |
| 732 | 732 | $user->unmark(); | 
| 733 | 733 | } | 
| 734 | 734 | } | 
| @@ -759,7 +759,7 @@ discard block | ||
| 759 | 759 | */ | 
| 760 | 760 |  	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { | 
| 761 | 761 | $user = $this->userManager->get($ocName); | 
| 762 | -		if($user === null) { | |
| 762 | +		if ($user === null) { | |
| 763 | 763 | return; | 
| 764 | 764 | } | 
| 765 | 765 | $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); | 
| @@ -768,7 +768,7 @@ discard block | ||
| 768 | 768 | } | 
| 769 | 769 | |
| 770 | 770 |  	public function cacheGroupDisplayName(string $ncName, string $displayName): void { | 
| 771 | - $cacheKey = 'group_getDisplayName' . $ncName; | |
| 771 | + $cacheKey = 'group_getDisplayName'.$ncName; | |
| 772 | 772 | $this->connection->writeToCache($cacheKey, $displayName); | 
| 773 | 773 | } | 
| 774 | 774 | |
| @@ -784,9 +784,9 @@ discard block | ||
| 784 | 784 | $attempts = 0; | 
| 785 | 785 | //while loop is just a precaution. If a name is not generated within | 
| 786 | 786 | //20 attempts, something else is very wrong. Avoids infinite loop. | 
| 787 | -		while($attempts < 20){ | |
| 788 | - $altName = $name . '_' . rand(1000,9999); | |
| 789 | -			if(!$this->ncUserManager->userExists($altName)) { | |
| 787 | +		while ($attempts < 20) { | |
| 788 | + $altName = $name.'_'.rand(1000, 9999); | |
| 789 | +			if (!$this->ncUserManager->userExists($altName)) { | |
| 790 | 790 | return $altName; | 
| 791 | 791 | } | 
| 792 | 792 | $attempts++; | 
| @@ -808,25 +808,25 @@ discard block | ||
| 808 | 808 | */ | 
| 809 | 809 |  	private function _createAltInternalOwnCloudNameForGroups($name) { | 
| 810 | 810 | $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); | 
| 811 | -		if(!$usedNames || count($usedNames) === 0) { | |
| 811 | +		if (!$usedNames || count($usedNames) === 0) { | |
| 812 | 812 | $lastNo = 1; //will become name_2 | 
| 813 | 813 |  		} else { | 
| 814 | 814 | natsort($usedNames); | 
| 815 | 815 | $lastName = array_pop($usedNames); | 
| 816 | - $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1); | |
| 816 | + $lastNo = (int) substr($lastName, strrpos($lastName, '_') + 1); | |
| 817 | 817 | } | 
| 818 | - $altName = $name.'_'. (string)($lastNo+1); | |
| 818 | + $altName = $name.'_'.(string) ($lastNo + 1); | |
| 819 | 819 | unset($usedNames); | 
| 820 | 820 | |
| 821 | 821 | $attempts = 1; | 
| 822 | -		while($attempts < 21){ | |
| 822 | +		while ($attempts < 21) { | |
| 823 | 823 | // Check to be really sure it is unique | 
| 824 | 824 | // while loop is just a precaution. If a name is not generated within | 
| 825 | 825 | // 20 attempts, something else is very wrong. Avoids infinite loop. | 
| 826 | -			if(!\OC::$server->getGroupManager()->groupExists($altName)) { | |
| 826 | +			if (!\OC::$server->getGroupManager()->groupExists($altName)) { | |
| 827 | 827 | return $altName; | 
| 828 | 828 | } | 
| 829 | - $altName = $name . '_' . ($lastNo + $attempts); | |
| 829 | + $altName = $name.'_'.($lastNo + $attempts); | |
| 830 | 830 | $attempts++; | 
| 831 | 831 | } | 
| 832 | 832 | return false; | 
| @@ -841,7 +841,7 @@ discard block | ||
| 841 | 841 |  	private function createAltInternalOwnCloudName($name, $isUser) { | 
| 842 | 842 | $originalTTL = $this->connection->ldapCacheTTL; | 
| 843 | 843 |  		$this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | 
| 844 | -		if($isUser) { | |
| 844 | +		if ($isUser) { | |
| 845 | 845 | $altName = $this->_createAltInternalOwnCloudNameForUsers($name); | 
| 846 | 846 |  		} else { | 
| 847 | 847 | $altName = $this->_createAltInternalOwnCloudNameForGroups($name); | 
| @@ -889,13 +889,13 @@ discard block | ||
| 889 | 889 |  	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) { | 
| 890 | 890 | $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); | 
| 891 | 891 | $recordsToUpdate = $ldapRecords; | 
| 892 | -		if(!$forceApplyAttributes) { | |
| 892 | +		if (!$forceApplyAttributes) { | |
| 893 | 893 | $isBackgroundJobModeAjax = $this->config | 
| 894 | 894 |  					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax'; | 
| 895 | 895 |  			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) { | 
| 896 | 896 | $newlyMapped = false; | 
| 897 | 897 | $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record); | 
| 898 | -				if(is_string($uid)) { | |
| 898 | +				if (is_string($uid)) { | |
| 899 | 899 | $this->cacheUserExists($uid); | 
| 900 | 900 | } | 
| 901 | 901 | return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax); | 
| @@ -913,15 +913,15 @@ discard block | ||
| 913 | 913 | * @param array $ldapRecords | 
| 914 | 914 | * @throws \Exception | 
| 915 | 915 | */ | 
| 916 | -	public function batchApplyUserAttributes(array $ldapRecords){ | |
| 916 | +	public function batchApplyUserAttributes(array $ldapRecords) { | |
| 917 | 917 | $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); | 
| 918 | -		foreach($ldapRecords as $userRecord) { | |
| 919 | -			if(!isset($userRecord[$displayNameAttribute])) { | |
| 918 | +		foreach ($ldapRecords as $userRecord) { | |
| 919 | +			if (!isset($userRecord[$displayNameAttribute])) { | |
| 920 | 920 | // displayName is obligatory | 
| 921 | 921 | continue; | 
| 922 | 922 | } | 
| 923 | - $ocName = $this->dn2ocname($userRecord['dn'][0], null, true); | |
| 924 | -			if($ocName === false) { | |
| 923 | + $ocName = $this->dn2ocname($userRecord['dn'][0], null, true); | |
| 924 | +			if ($ocName === false) { | |
| 925 | 925 | continue; | 
| 926 | 926 | } | 
| 927 | 927 | $this->updateUserState($ocName); | 
| @@ -954,8 +954,8 @@ discard block | ||
| 954 | 954 | * @return array | 
| 955 | 955 | */ | 
| 956 | 956 |  	private function fetchList($list, $manyAttributes) { | 
| 957 | -		if(is_array($list)) { | |
| 958 | -			if($manyAttributes) { | |
| 957 | +		if (is_array($list)) { | |
| 958 | +			if ($manyAttributes) { | |
| 959 | 959 | return $list; | 
| 960 | 960 |  			} else { | 
| 961 | 961 |  				$list = array_reduce($list, function($carry, $item) { | 
| @@ -983,7 +983,7 @@ discard block | ||
| 983 | 983 | */ | 
| 984 | 984 |  	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { | 
| 985 | 985 | $result = []; | 
| 986 | -		foreach($this->connection->ldapBaseUsers as $base) { | |
| 986 | +		foreach ($this->connection->ldapBaseUsers as $base) { | |
| 987 | 987 | $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); | 
| 988 | 988 | } | 
| 989 | 989 | return $result; | 
| @@ -998,9 +998,9 @@ discard block | ||
| 998 | 998 | */ | 
| 999 | 999 |  	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) { | 
| 1000 | 1000 | $result = false; | 
| 1001 | -		foreach($this->connection->ldapBaseUsers as $base) { | |
| 1001 | +		foreach ($this->connection->ldapBaseUsers as $base) { | |
| 1002 | 1002 | $count = $this->count($filter, [$base], $attr, $limit, $offset); | 
| 1003 | - $result = is_int($count) ? (int)$result + $count : $result; | |
| 1003 | + $result = is_int($count) ? (int) $result + $count : $result; | |
| 1004 | 1004 | } | 
| 1005 | 1005 | return $result; | 
| 1006 | 1006 | } | 
| @@ -1017,7 +1017,7 @@ discard block | ||
| 1017 | 1017 | */ | 
| 1018 | 1018 |  	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { | 
| 1019 | 1019 | $result = []; | 
| 1020 | -		foreach($this->connection->ldapBaseGroups as $base) { | |
| 1020 | +		foreach ($this->connection->ldapBaseGroups as $base) { | |
| 1021 | 1021 | $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset)); | 
| 1022 | 1022 | } | 
| 1023 | 1023 | return $result; | 
| @@ -1033,9 +1033,9 @@ discard block | ||
| 1033 | 1033 | */ | 
| 1034 | 1034 |  	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) { | 
| 1035 | 1035 | $result = false; | 
| 1036 | -		foreach($this->connection->ldapBaseGroups as $base) { | |
| 1036 | +		foreach ($this->connection->ldapBaseGroups as $base) { | |
| 1037 | 1037 | $count = $this->count($filter, [$base], $attr, $limit, $offset); | 
| 1038 | - $result = is_int($count) ? (int)$result + $count : $result; | |
| 1038 | + $result = is_int($count) ? (int) $result + $count : $result; | |
| 1039 | 1039 | } | 
| 1040 | 1040 | return $result; | 
| 1041 | 1041 | } | 
| @@ -1049,9 +1049,9 @@ discard block | ||
| 1049 | 1049 | */ | 
| 1050 | 1050 |  	public function countObjects($limit = null, $offset = null) { | 
| 1051 | 1051 | $result = false; | 
| 1052 | -		foreach($this->connection->ldapBase as $base) { | |
| 1052 | +		foreach ($this->connection->ldapBase as $base) { | |
| 1053 | 1053 |  			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset); | 
| 1054 | - $result = is_int($count) ? (int)$result + $count : $result; | |
| 1054 | + $result = is_int($count) ? (int) $result + $count : $result; | |
| 1055 | 1055 | } | 
| 1056 | 1056 | return $result; | 
| 1057 | 1057 | } | 
| @@ -1076,7 +1076,7 @@ discard block | ||
| 1076 | 1076 | // php no longer supports call-time pass-by-reference | 
| 1077 | 1077 | // thus cannot support controlPagedResultResponse as the third argument | 
| 1078 | 1078 | // is a reference | 
| 1079 | -		$doMethod = function () use ($command, &$arguments) { | |
| 1079 | +		$doMethod = function() use ($command, &$arguments) { | |
| 1080 | 1080 |  			if ($command == 'controlPagedResultResponse') { | 
| 1081 | 1081 |  				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.'); | 
| 1082 | 1082 |  			} else { | 
| @@ -1094,7 +1094,7 @@ discard block | ||
| 1094 | 1094 | $this->connection->resetConnectionResource(); | 
| 1095 | 1095 | $cr = $this->connection->getConnectionResource(); | 
| 1096 | 1096 | |
| 1097 | -			if(!$this->ldap->isResource($cr)) { | |
| 1097 | +			if (!$this->ldap->isResource($cr)) { | |
| 1098 | 1098 | // Seems like we didn't find any resource. | 
| 1099 | 1099 |  				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG); | 
| 1100 | 1100 | throw $e; | 
| @@ -1119,13 +1119,13 @@ discard block | ||
| 1119 | 1119 | * @throws ServerNotAvailableException | 
| 1120 | 1120 | */ | 
| 1121 | 1121 |  	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { | 
| 1122 | -		if(!is_null($attr) && !is_array($attr)) { | |
| 1122 | +		if (!is_null($attr) && !is_array($attr)) { | |
| 1123 | 1123 | $attr = array(mb_strtolower($attr, 'UTF-8')); | 
| 1124 | 1124 | } | 
| 1125 | 1125 | |
| 1126 | 1126 | // See if we have a resource, in case not cancel with message | 
| 1127 | 1127 | $cr = $this->connection->getConnectionResource(); | 
| 1128 | -		if(!$this->ldap->isResource($cr)) { | |
| 1128 | +		if (!$this->ldap->isResource($cr)) { | |
| 1129 | 1129 | // Seems like we didn't find any resource. | 
| 1130 | 1130 | // Return an empty array just like before. | 
| 1131 | 1131 |  			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG); | 
| @@ -1133,13 +1133,13 @@ discard block | ||
| 1133 | 1133 | } | 
| 1134 | 1134 | |
| 1135 | 1135 | //check whether paged search should be attempted | 
| 1136 | - $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset); | |
| 1136 | + $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int) $limit, $offset); | |
| 1137 | 1137 | |
| 1138 | 1138 | $linkResources = array_pad(array(), count($base), $cr); | 
| 1139 | 1139 |  		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); | 
| 1140 | 1140 | // cannot use $cr anymore, might have changed in the previous call! | 
| 1141 | 1141 | $error = $this->ldap->errno($this->connection->getConnectionResource()); | 
| 1142 | -		if(!is_array($sr) || $error !== 0) { | |
| 1142 | +		if (!is_array($sr) || $error !== 0) { | |
| 1143 | 1143 |  			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR); | 
| 1144 | 1144 | return false; | 
| 1145 | 1145 | } | 
| @@ -1162,29 +1162,29 @@ discard block | ||
| 1162 | 1162 | */ | 
| 1163 | 1163 |  	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { | 
| 1164 | 1164 | $cookie = null; | 
| 1165 | -		if($pagedSearchOK) { | |
| 1165 | +		if ($pagedSearchOK) { | |
| 1166 | 1166 | $cr = $this->connection->getConnectionResource(); | 
| 1167 | -			foreach($sr as $key => $res) { | |
| 1168 | -				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { | |
| 1167 | +			foreach ($sr as $key => $res) { | |
| 1168 | +				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { | |
| 1169 | 1169 | $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); | 
| 1170 | 1170 | } | 
| 1171 | 1171 | } | 
| 1172 | 1172 | |
| 1173 | 1173 | //browsing through prior pages to get the cookie for the new one | 
| 1174 | -			if($skipHandling) { | |
| 1174 | +			if ($skipHandling) { | |
| 1175 | 1175 | return false; | 
| 1176 | 1176 | } | 
| 1177 | 1177 | // if count is bigger, then the server does not support | 
| 1178 | 1178 | // paged search. Instead, he did a normal search. We set a | 
| 1179 | 1179 | // flag here, so the callee knows how to deal with it. | 
| 1180 | -			if($iFoundItems <= $limit) { | |
| 1180 | +			if ($iFoundItems <= $limit) { | |
| 1181 | 1181 | $this->pagedSearchedSuccessful = true; | 
| 1182 | 1182 | } | 
| 1183 | 1183 |  		} else { | 
| 1184 | -			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) { | |
| 1184 | +			if (!is_null($limit) && (int) $this->connection->ldapPagingSize !== 0) { | |
| 1185 | 1185 | \OC::$server->getLogger()->debug( | 
| 1186 | 1186 | 'Paged search was not available', | 
| 1187 | - [ 'app' => 'user_ldap' ] | |
| 1187 | + ['app' => 'user_ldap'] | |
| 1188 | 1188 | ); | 
| 1189 | 1189 | } | 
| 1190 | 1190 | } | 
| @@ -1213,8 +1213,8 @@ discard block | ||
| 1213 | 1213 |  	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | 
| 1214 | 1214 |  		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG); | 
| 1215 | 1215 | |
| 1216 | - $limitPerPage = (int)$this->connection->ldapPagingSize; | |
| 1217 | -		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1216 | + $limitPerPage = (int) $this->connection->ldapPagingSize; | |
| 1217 | +		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1218 | 1218 | $limitPerPage = $limit; | 
| 1219 | 1219 | } | 
| 1220 | 1220 | |
| @@ -1224,7 +1224,7 @@ discard block | ||
| 1224 | 1224 | |
| 1225 | 1225 |  		do { | 
| 1226 | 1226 | $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | 
| 1227 | -			if($search === false) { | |
| 1227 | +			if ($search === false) { | |
| 1228 | 1228 | return $counter > 0 ? $counter : false; | 
| 1229 | 1229 | } | 
| 1230 | 1230 | list($sr, $pagedSearchOK) = $search; | 
| @@ -1243,7 +1243,7 @@ discard block | ||
| 1243 | 1243 | * Continue now depends on $hasMorePages value | 
| 1244 | 1244 | */ | 
| 1245 | 1245 | $continue = $pagedSearchOK && $hasMorePages; | 
| 1246 | - } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); | |
| 1246 | + } while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); | |
| 1247 | 1247 | |
| 1248 | 1248 | return $counter; | 
| 1249 | 1249 | } | 
| @@ -1255,8 +1255,8 @@ discard block | ||
| 1255 | 1255 |  	private function countEntriesInSearchResults($searchResults) { | 
| 1256 | 1256 | $counter = 0; | 
| 1257 | 1257 | |
| 1258 | -		foreach($searchResults as $res) { | |
| 1259 | -			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res); | |
| 1258 | +		foreach ($searchResults as $res) { | |
| 1259 | +			$count = (int) $this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res); | |
| 1260 | 1260 | $counter += $count; | 
| 1261 | 1261 | } | 
| 1262 | 1262 | |
| @@ -1276,8 +1276,8 @@ discard block | ||
| 1276 | 1276 | * @throws ServerNotAvailableException | 
| 1277 | 1277 | */ | 
| 1278 | 1278 |  	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | 
| 1279 | - $limitPerPage = (int)$this->connection->ldapPagingSize; | |
| 1280 | -		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1279 | + $limitPerPage = (int) $this->connection->ldapPagingSize; | |
| 1280 | +		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1281 | 1281 | $limitPerPage = $limit; | 
| 1282 | 1282 | } | 
| 1283 | 1283 | |
| @@ -1291,13 +1291,13 @@ discard block | ||
| 1291 | 1291 | $savedoffset = $offset; | 
| 1292 | 1292 |  		do { | 
| 1293 | 1293 | $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | 
| 1294 | -			if($search === false) { | |
| 1294 | +			if ($search === false) { | |
| 1295 | 1295 | return []; | 
| 1296 | 1296 | } | 
| 1297 | 1297 | list($sr, $pagedSearchOK) = $search; | 
| 1298 | 1298 | $cr = $this->connection->getConnectionResource(); | 
| 1299 | 1299 | |
| 1300 | -			if($skipHandling) { | |
| 1300 | +			if ($skipHandling) { | |
| 1301 | 1301 | //i.e. result do not need to be fetched, we just need the cookie | 
| 1302 | 1302 | //thus pass 1 or any other value as $iFoundItems because it is not | 
| 1303 | 1303 | //used | 
| @@ -1308,7 +1308,7 @@ discard block | ||
| 1308 | 1308 | } | 
| 1309 | 1309 | |
| 1310 | 1310 | $iFoundItems = 0; | 
| 1311 | -			foreach($sr as $res) { | |
| 1311 | +			foreach ($sr as $res) { | |
| 1312 | 1312 |  				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); | 
| 1313 | 1313 | $iFoundItems = max($iFoundItems, $findings['count']); | 
| 1314 | 1314 | unset($findings['count']); | 
| @@ -1324,27 +1324,27 @@ discard block | ||
| 1324 | 1324 | |
| 1325 | 1325 | // if we're here, probably no connection resource is returned. | 
| 1326 | 1326 | // to make Nextcloud behave nicely, we simply give back an empty array. | 
| 1327 | -		if(is_null($findings)) { | |
| 1327 | +		if (is_null($findings)) { | |
| 1328 | 1328 | return array(); | 
| 1329 | 1329 | } | 
| 1330 | 1330 | |
| 1331 | -		if(!is_null($attr)) { | |
| 1331 | +		if (!is_null($attr)) { | |
| 1332 | 1332 | $selection = []; | 
| 1333 | 1333 | $i = 0; | 
| 1334 | -			foreach($findings as $item) { | |
| 1335 | -				if(!is_array($item)) { | |
| 1334 | +			foreach ($findings as $item) { | |
| 1335 | +				if (!is_array($item)) { | |
| 1336 | 1336 | continue; | 
| 1337 | 1337 | } | 
| 1338 | 1338 | $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); | 
| 1339 | -				foreach($attr as $key) { | |
| 1340 | -					if(isset($item[$key])) { | |
| 1341 | -						if(is_array($item[$key]) && isset($item[$key]['count'])) { | |
| 1339 | +				foreach ($attr as $key) { | |
| 1340 | +					if (isset($item[$key])) { | |
| 1341 | +						if (is_array($item[$key]) && isset($item[$key]['count'])) { | |
| 1342 | 1342 | unset($item[$key]['count']); | 
| 1343 | 1343 | } | 
| 1344 | -						if($key !== 'dn') { | |
| 1345 | -							if($this->resemblesDN($key)) { | |
| 1344 | +						if ($key !== 'dn') { | |
| 1345 | +							if ($this->resemblesDN($key)) { | |
| 1346 | 1346 | $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]); | 
| 1347 | -							} else if($key === 'objectguid' || $key === 'guid') { | |
| 1347 | +							} else if ($key === 'objectguid' || $key === 'guid') { | |
| 1348 | 1348 | $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])]; | 
| 1349 | 1349 |  							} else { | 
| 1350 | 1350 | $selection[$i][$key] = $item[$key]; | 
| @@ -1362,14 +1362,14 @@ discard block | ||
| 1362 | 1362 | //we slice the findings, when | 
| 1363 | 1363 | //a) paged search unsuccessful, though attempted | 
| 1364 | 1364 | //b) no paged search, but limit set | 
| 1365 | - if((!$this->getPagedSearchResultState() | |
| 1365 | + if ((!$this->getPagedSearchResultState() | |
| 1366 | 1366 | && $pagedSearchOK) | 
| 1367 | 1367 | || ( | 
| 1368 | 1368 | !$pagedSearchOK | 
| 1369 | 1369 | && !is_null($limit) | 
| 1370 | 1370 | ) | 
| 1371 | 1371 |  		) { | 
| 1372 | - $findings = array_slice($findings, (int)$offset, $limit); | |
| 1372 | + $findings = array_slice($findings, (int) $offset, $limit); | |
| 1373 | 1373 | } | 
| 1374 | 1374 | return $findings; | 
| 1375 | 1375 | } | 
| @@ -1382,13 +1382,13 @@ discard block | ||
| 1382 | 1382 |  	public function sanitizeUsername($name) { | 
| 1383 | 1383 | $name = trim($name); | 
| 1384 | 1384 | |
| 1385 | -		if($this->connection->ldapIgnoreNamingRules) { | |
| 1385 | +		if ($this->connection->ldapIgnoreNamingRules) { | |
| 1386 | 1386 | return $name; | 
| 1387 | 1387 | } | 
| 1388 | 1388 | |
| 1389 | 1389 | // Transliteration to ASCII | 
| 1390 | 1390 |  		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name); | 
| 1391 | -		if($transliterated !== false) { | |
| 1391 | +		if ($transliterated !== false) { | |
| 1392 | 1392 | // depending on system config iconv can work or not | 
| 1393 | 1393 | $name = $transliterated; | 
| 1394 | 1394 | } | 
| @@ -1399,7 +1399,7 @@ discard block | ||
| 1399 | 1399 | // Every remaining disallowed characters will be removed | 
| 1400 | 1400 |  		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); | 
| 1401 | 1401 | |
| 1402 | -		if($name === '') { | |
| 1402 | +		if ($name === '') { | |
| 1403 | 1403 |  			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters'); | 
| 1404 | 1404 | } | 
| 1405 | 1405 | |
| @@ -1414,13 +1414,13 @@ discard block | ||
| 1414 | 1414 | */ | 
| 1415 | 1415 |  	public function escapeFilterPart($input, $allowAsterisk = false) { | 
| 1416 | 1416 | $asterisk = ''; | 
| 1417 | -		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { | |
| 1417 | +		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { | |
| 1418 | 1418 | $asterisk = '*'; | 
| 1419 | 1419 | $input = mb_substr($input, 1, null, 'UTF-8'); | 
| 1420 | 1420 | } | 
| 1421 | 1421 |  		$search  = array('*', '\\', '(', ')'); | 
| 1422 | 1422 |  		$replace = array('\\*', '\\\\', '\\(', '\\)'); | 
| 1423 | - return $asterisk . str_replace($search, $replace, $input); | |
| 1423 | + return $asterisk.str_replace($search, $replace, $input); | |
| 1424 | 1424 | } | 
| 1425 | 1425 | |
| 1426 | 1426 | /** | 
| @@ -1450,13 +1450,13 @@ discard block | ||
| 1450 | 1450 | */ | 
| 1451 | 1451 |  	private function combineFilter($filters, $operator) { | 
| 1452 | 1452 |  		$combinedFilter = '('.$operator; | 
| 1453 | -		foreach($filters as $filter) { | |
| 1453 | +		foreach ($filters as $filter) { | |
| 1454 | 1454 |  			if ($filter !== '' && $filter[0] !== '(') { | 
| 1455 | 1455 |  				$filter = '('.$filter.')'; | 
| 1456 | 1456 | } | 
| 1457 | - $combinedFilter.=$filter; | |
| 1457 | + $combinedFilter .= $filter; | |
| 1458 | 1458 | } | 
| 1459 | - $combinedFilter.=')'; | |
| 1459 | + $combinedFilter .= ')'; | |
| 1460 | 1460 | return $combinedFilter; | 
| 1461 | 1461 | } | 
| 1462 | 1462 | |
| @@ -1492,17 +1492,17 @@ discard block | ||
| 1492 | 1492 | * @throws \Exception | 
| 1493 | 1493 | */ | 
| 1494 | 1494 |  	private function getAdvancedFilterPartForSearch($search, $searchAttributes) { | 
| 1495 | -		if(!is_array($searchAttributes) || count($searchAttributes) < 2) { | |
| 1495 | +		if (!is_array($searchAttributes) || count($searchAttributes) < 2) { | |
| 1496 | 1496 |  			throw new \Exception('searchAttributes must be an array with at least two string'); | 
| 1497 | 1497 | } | 
| 1498 | 1498 |  		$searchWords = explode(' ', trim($search)); | 
| 1499 | 1499 | $wordFilters = array(); | 
| 1500 | -		foreach($searchWords as $word) { | |
| 1500 | +		foreach ($searchWords as $word) { | |
| 1501 | 1501 | $word = $this->prepareSearchTerm($word); | 
| 1502 | 1502 | //every word needs to appear at least once | 
| 1503 | 1503 | $wordMatchOneAttrFilters = array(); | 
| 1504 | -			foreach($searchAttributes as $attr) { | |
| 1505 | - $wordMatchOneAttrFilters[] = $attr . '=' . $word; | |
| 1504 | +			foreach ($searchAttributes as $attr) { | |
| 1505 | + $wordMatchOneAttrFilters[] = $attr.'='.$word; | |
| 1506 | 1506 | } | 
| 1507 | 1507 | $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); | 
| 1508 | 1508 | } | 
| @@ -1520,10 +1520,10 @@ discard block | ||
| 1520 | 1520 |  	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { | 
| 1521 | 1521 | $filter = array(); | 
| 1522 | 1522 | $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); | 
| 1523 | -		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { | |
| 1523 | +		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { | |
| 1524 | 1524 |  			try { | 
| 1525 | 1525 | return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); | 
| 1526 | -			} catch(\Exception $e) { | |
| 1526 | +			} catch (\Exception $e) { | |
| 1527 | 1527 | \OCP\Util::writeLog( | 
| 1528 | 1528 | 'user_ldap', | 
| 1529 | 1529 | 'Creating advanced filter for search failed, falling back to simple method.', | 
| @@ -1533,17 +1533,17 @@ discard block | ||
| 1533 | 1533 | } | 
| 1534 | 1534 | |
| 1535 | 1535 | $search = $this->prepareSearchTerm($search); | 
| 1536 | -		if(!is_array($searchAttributes) || count($searchAttributes) === 0) { | |
| 1536 | +		if (!is_array($searchAttributes) || count($searchAttributes) === 0) { | |
| 1537 | 1537 |  			if ($fallbackAttribute === '') { | 
| 1538 | 1538 | return ''; | 
| 1539 | 1539 | } | 
| 1540 | - $filter[] = $fallbackAttribute . '=' . $search; | |
| 1540 | + $filter[] = $fallbackAttribute.'='.$search; | |
| 1541 | 1541 |  		} else { | 
| 1542 | -			foreach($searchAttributes as $attribute) { | |
| 1543 | - $filter[] = $attribute . '=' . $search; | |
| 1542 | +			foreach ($searchAttributes as $attribute) { | |
| 1543 | + $filter[] = $attribute.'='.$search; | |
| 1544 | 1544 | } | 
| 1545 | 1545 | } | 
| 1546 | -		if(count($filter) === 1) { | |
| 1546 | +		if (count($filter) === 1) { | |
| 1547 | 1547 |  			return '('.$filter[0].')'; | 
| 1548 | 1548 | } | 
| 1549 | 1549 | return $this->combineFilterWithOr($filter); | 
| @@ -1564,7 +1564,7 @@ discard block | ||
| 1564 | 1564 |  		if ($term === '') { | 
| 1565 | 1565 | $result = '*'; | 
| 1566 | 1566 |  		} else if ($allowEnum !== 'no') { | 
| 1567 | - $result = $term . '*'; | |
| 1567 | + $result = $term.'*'; | |
| 1568 | 1568 | } | 
| 1569 | 1569 | return $result; | 
| 1570 | 1570 | } | 
| @@ -1576,7 +1576,7 @@ discard block | ||
| 1576 | 1576 |  	public function getFilterForUserCount() { | 
| 1577 | 1577 | $filter = $this->combineFilterWithAnd(array( | 
| 1578 | 1578 | $this->connection->ldapUserFilter, | 
| 1579 | - $this->connection->ldapUserDisplayName . '=*' | |
| 1579 | + $this->connection->ldapUserDisplayName.'=*' | |
| 1580 | 1580 | )); | 
| 1581 | 1581 | |
| 1582 | 1582 | return $filter; | 
| @@ -1594,7 +1594,7 @@ discard block | ||
| 1594 | 1594 | 'ldapAgentName' => $name, | 
| 1595 | 1595 | 'ldapAgentPassword' => $password | 
| 1596 | 1596 | ); | 
| 1597 | -		if(!$testConnection->setConfiguration($credentials)) { | |
| 1597 | +		if (!$testConnection->setConfiguration($credentials)) { | |
| 1598 | 1598 | return false; | 
| 1599 | 1599 | } | 
| 1600 | 1600 | return $testConnection->bind(); | 
| @@ -1616,30 +1616,30 @@ discard block | ||
| 1616 | 1616 | // Sacrebleu! The UUID attribute is unknown :( We need first an | 
| 1617 | 1617 | // existing DN to be able to reliably detect it. | 
| 1618 | 1618 | $result = $this->search($filter, $base, ['dn'], 1); | 
| 1619 | -			if(!isset($result[0]) || !isset($result[0]['dn'])) { | |
| 1619 | +			if (!isset($result[0]) || !isset($result[0]['dn'])) { | |
| 1620 | 1620 |  				throw new \Exception('Cannot determine UUID attribute'); | 
| 1621 | 1621 | } | 
| 1622 | 1622 | $dn = $result[0]['dn'][0]; | 
| 1623 | -			if(!$this->detectUuidAttribute($dn, true)) { | |
| 1623 | +			if (!$this->detectUuidAttribute($dn, true)) { | |
| 1624 | 1624 |  				throw new \Exception('Cannot determine UUID attribute'); | 
| 1625 | 1625 | } | 
| 1626 | 1626 |  		} else { | 
| 1627 | 1627 | // The UUID attribute is either known or an override is given. | 
| 1628 | 1628 | // By calling this method we ensure that $this->connection->$uuidAttr | 
| 1629 | 1629 | // is definitely set | 
| 1630 | -			if(!$this->detectUuidAttribute('', true)) { | |
| 1630 | +			if (!$this->detectUuidAttribute('', true)) { | |
| 1631 | 1631 |  				throw new \Exception('Cannot determine UUID attribute'); | 
| 1632 | 1632 | } | 
| 1633 | 1633 | } | 
| 1634 | 1634 | |
| 1635 | 1635 | $uuidAttr = $this->connection->ldapUuidUserAttribute; | 
| 1636 | -		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { | |
| 1636 | +		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { | |
| 1637 | 1637 | $uuid = $this->formatGuid2ForFilterUser($uuid); | 
| 1638 | 1638 | } | 
| 1639 | 1639 | |
| 1640 | - $filter = $uuidAttr . '=' . $uuid; | |
| 1640 | + $filter = $uuidAttr.'='.$uuid; | |
| 1641 | 1641 | $result = $this->searchUsers($filter, ['dn'], 2); | 
| 1642 | -		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { | |
| 1642 | +		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { | |
| 1643 | 1643 | // we put the count into account to make sure that this is | 
| 1644 | 1644 | // really unique | 
| 1645 | 1645 | return $result[0]['dn'][0]; | 
| @@ -1658,7 +1658,7 @@ discard block | ||
| 1658 | 1658 | * @return bool true on success, false otherwise | 
| 1659 | 1659 | */ | 
| 1660 | 1660 |  	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) { | 
| 1661 | -		if($isUser) { | |
| 1661 | +		if ($isUser) { | |
| 1662 | 1662 | $uuidAttr = 'ldapUuidUserAttribute'; | 
| 1663 | 1663 | $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | 
| 1664 | 1664 |  		} else { | 
| @@ -1666,7 +1666,7 @@ discard block | ||
| 1666 | 1666 | $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | 
| 1667 | 1667 | } | 
| 1668 | 1668 | |
| 1669 | -		if(($this->connection->$uuidAttr !== 'auto') && !$force) { | |
| 1669 | +		if (($this->connection->$uuidAttr !== 'auto') && !$force) { | |
| 1670 | 1670 | return true; | 
| 1671 | 1671 | } | 
| 1672 | 1672 | |
| @@ -1675,10 +1675,10 @@ discard block | ||
| 1675 | 1675 | return true; | 
| 1676 | 1676 | } | 
| 1677 | 1677 | |
| 1678 | -		foreach(self::UUID_ATTRIBUTES as $attribute) { | |
| 1679 | -			if($ldapRecord !== null) { | |
| 1678 | +		foreach (self::UUID_ATTRIBUTES as $attribute) { | |
| 1679 | +			if ($ldapRecord !== null) { | |
| 1680 | 1680 | // we have the info from LDAP already, we don't need to talk to the server again | 
| 1681 | -				if(isset($ldapRecord[$attribute])) { | |
| 1681 | +				if (isset($ldapRecord[$attribute])) { | |
| 1682 | 1682 | $this->connection->$uuidAttr = $attribute; | 
| 1683 | 1683 | return true; | 
| 1684 | 1684 |  				} else { | 
| @@ -1687,7 +1687,7 @@ discard block | ||
| 1687 | 1687 | } | 
| 1688 | 1688 | |
| 1689 | 1689 | $value = $this->readAttribute($dn, $attribute); | 
| 1690 | -			if(is_array($value) && isset($value[0]) && !empty($value[0])) { | |
| 1690 | +			if (is_array($value) && isset($value[0]) && !empty($value[0])) { | |
| 1691 | 1691 | \OCP\Util::writeLog( | 
| 1692 | 1692 | 'user_ldap', | 
| 1693 | 1693 | 'Setting '.$attribute.' as '.$uuidAttr, | 
| @@ -1713,7 +1713,7 @@ discard block | ||
| 1713 | 1713 | * @return bool|string | 
| 1714 | 1714 | */ | 
| 1715 | 1715 |  	public function getUUID($dn, $isUser = true, $ldapRecord = null) { | 
| 1716 | -		if($isUser) { | |
| 1716 | +		if ($isUser) { | |
| 1717 | 1717 | $uuidAttr = 'ldapUuidUserAttribute'; | 
| 1718 | 1718 | $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | 
| 1719 | 1719 |  		} else { | 
| @@ -1722,10 +1722,10 @@ discard block | ||
| 1722 | 1722 | } | 
| 1723 | 1723 | |
| 1724 | 1724 | $uuid = false; | 
| 1725 | -		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { | |
| 1725 | +		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) { | |
| 1726 | 1726 | $attr = $this->connection->$uuidAttr; | 
| 1727 | 1727 | $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr); | 
| 1728 | - if( !is_array($uuid) | |
| 1728 | + if (!is_array($uuid) | |
| 1729 | 1729 | && $uuidOverride !== '' | 
| 1730 | 1730 | && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) | 
| 1731 | 1731 |  			{ | 
| @@ -1733,7 +1733,7 @@ discard block | ||
| 1733 | 1733 | ? $ldapRecord[$this->connection->$uuidAttr] | 
| 1734 | 1734 | : $this->readAttribute($dn, $this->connection->$uuidAttr); | 
| 1735 | 1735 | } | 
| 1736 | -			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { | |
| 1736 | +			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { | |
| 1737 | 1737 | $uuid = $uuid[0]; | 
| 1738 | 1738 | } | 
| 1739 | 1739 | } | 
| @@ -1750,19 +1750,19 @@ discard block | ||
| 1750 | 1750 |  	private function convertObjectGUID2Str($oguid) { | 
| 1751 | 1751 | $hex_guid = bin2hex($oguid); | 
| 1752 | 1752 | $hex_guid_to_guid_str = ''; | 
| 1753 | -		for($k = 1; $k <= 4; ++$k) { | |
| 1753 | +		for ($k = 1; $k <= 4; ++$k) { | |
| 1754 | 1754 | $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); | 
| 1755 | 1755 | } | 
| 1756 | 1756 | $hex_guid_to_guid_str .= '-'; | 
| 1757 | -		for($k = 1; $k <= 2; ++$k) { | |
| 1757 | +		for ($k = 1; $k <= 2; ++$k) { | |
| 1758 | 1758 | $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); | 
| 1759 | 1759 | } | 
| 1760 | 1760 | $hex_guid_to_guid_str .= '-'; | 
| 1761 | -		for($k = 1; $k <= 2; ++$k) { | |
| 1761 | +		for ($k = 1; $k <= 2; ++$k) { | |
| 1762 | 1762 | $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); | 
| 1763 | 1763 | } | 
| 1764 | - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); | |
| 1765 | - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20); | |
| 1764 | + $hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4); | |
| 1765 | + $hex_guid_to_guid_str .= '-'.substr($hex_guid, 20); | |
| 1766 | 1766 | |
| 1767 | 1767 | return strtoupper($hex_guid_to_guid_str); | 
| 1768 | 1768 | } | 
| @@ -1779,11 +1779,11 @@ discard block | ||
| 1779 | 1779 | * @return string | 
| 1780 | 1780 | */ | 
| 1781 | 1781 |  	public function formatGuid2ForFilterUser($guid) { | 
| 1782 | -		if(!is_string($guid)) { | |
| 1782 | +		if (!is_string($guid)) { | |
| 1783 | 1783 |  			throw new \InvalidArgumentException('String expected'); | 
| 1784 | 1784 | } | 
| 1785 | 1785 |  		$blocks = explode('-', $guid); | 
| 1786 | -		if(count($blocks) !== 5) { | |
| 1786 | +		if (count($blocks) !== 5) { | |
| 1787 | 1787 | /* | 
| 1788 | 1788 | * Why not throw an Exception instead? This method is a utility | 
| 1789 | 1789 | * called only when trying to figure out whether a "missing" known | 
| @@ -1796,20 +1796,20 @@ discard block | ||
| 1796 | 1796 | * user. Instead we write a log message. | 
| 1797 | 1797 | */ | 
| 1798 | 1798 | \OC::$server->getLogger()->info( | 
| 1799 | - 'Passed string does not resemble a valid GUID. Known UUID ' . | |
| 1799 | + 'Passed string does not resemble a valid GUID. Known UUID '. | |
| 1800 | 1800 |  				'({uuid}) probably does not match UUID configuration.', | 
| 1801 | - [ 'app' => 'user_ldap', 'uuid' => $guid ] | |
| 1801 | + ['app' => 'user_ldap', 'uuid' => $guid] | |
| 1802 | 1802 | ); | 
| 1803 | 1803 | return $guid; | 
| 1804 | 1804 | } | 
| 1805 | -		for($i=0; $i < 3; $i++) { | |
| 1805 | +		for ($i = 0; $i < 3; $i++) { | |
| 1806 | 1806 | $pairs = str_split($blocks[$i], 2); | 
| 1807 | 1807 | $pairs = array_reverse($pairs); | 
| 1808 | 1808 |  			$blocks[$i] = implode('', $pairs); | 
| 1809 | 1809 | } | 
| 1810 | -		for($i=0; $i < 5; $i++) { | |
| 1810 | +		for ($i = 0; $i < 5; $i++) { | |
| 1811 | 1811 | $pairs = str_split($blocks[$i], 2); | 
| 1812 | -			$blocks[$i] = '\\' . implode('\\', $pairs); | |
| 1812 | +			$blocks[$i] = '\\'.implode('\\', $pairs); | |
| 1813 | 1813 | } | 
| 1814 | 1814 |  		return implode('', $blocks); | 
| 1815 | 1815 | } | 
| @@ -1823,12 +1823,12 @@ discard block | ||
| 1823 | 1823 | $domainDN = $this->getDomainDNFromDN($dn); | 
| 1824 | 1824 | $cacheKey = 'getSID-'.$domainDN; | 
| 1825 | 1825 | $sid = $this->connection->getFromCache($cacheKey); | 
| 1826 | -		if(!is_null($sid)) { | |
| 1826 | +		if (!is_null($sid)) { | |
| 1827 | 1827 | return $sid; | 
| 1828 | 1828 | } | 
| 1829 | 1829 | |
| 1830 | 1830 | $objectSid = $this->readAttribute($domainDN, 'objectsid'); | 
| 1831 | -		if(!is_array($objectSid) || empty($objectSid)) { | |
| 1831 | +		if (!is_array($objectSid) || empty($objectSid)) { | |
| 1832 | 1832 | $this->connection->writeToCache($cacheKey, false); | 
| 1833 | 1833 | return false; | 
| 1834 | 1834 | } | 
| @@ -1886,12 +1886,12 @@ discard block | ||
| 1886 | 1886 | $belongsToBase = false; | 
| 1887 | 1887 | $bases = $this->helper->sanitizeDN($bases); | 
| 1888 | 1888 | |
| 1889 | -		foreach($bases as $base) { | |
| 1889 | +		foreach ($bases as $base) { | |
| 1890 | 1890 | $belongsToBase = true; | 
| 1891 | -			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { | |
| 1891 | +			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) { | |
| 1892 | 1892 | $belongsToBase = false; | 
| 1893 | 1893 | } | 
| 1894 | -			if($belongsToBase) { | |
| 1894 | +			if ($belongsToBase) { | |
| 1895 | 1895 | break; | 
| 1896 | 1896 | } | 
| 1897 | 1897 | } | 
| @@ -1920,16 +1920,16 @@ discard block | ||
| 1920 | 1920 | * @return string containing the key or empty if none is cached | 
| 1921 | 1921 | */ | 
| 1922 | 1922 |  	private function getPagedResultCookie($base, $filter, $limit, $offset) { | 
| 1923 | -		if($offset === 0) { | |
| 1923 | +		if ($offset === 0) { | |
| 1924 | 1924 | return ''; | 
| 1925 | 1925 | } | 
| 1926 | 1926 | $offset -= $limit; | 
| 1927 | 1927 | //we work with cache here | 
| 1928 | - $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; | |
| 1928 | + $cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset; | |
| 1929 | 1929 | $cookie = ''; | 
| 1930 | -		if(isset($this->cookies[$cacheKey])) { | |
| 1930 | +		if (isset($this->cookies[$cacheKey])) { | |
| 1931 | 1931 | $cookie = $this->cookies[$cacheKey]; | 
| 1932 | -			if(is_null($cookie)) { | |
| 1932 | +			if (is_null($cookie)) { | |
| 1933 | 1933 | $cookie = ''; | 
| 1934 | 1934 | } | 
| 1935 | 1935 | } | 
| @@ -1947,7 +1947,7 @@ discard block | ||
| 1947 | 1947 | * @return bool | 
| 1948 | 1948 | */ | 
| 1949 | 1949 |  	public function hasMoreResults() { | 
| 1950 | -		if(empty($this->lastCookie) && $this->lastCookie !== '0') { | |
| 1950 | +		if (empty($this->lastCookie) && $this->lastCookie !== '0') { | |
| 1951 | 1951 | // as in RFC 2696, when all results are returned, the cookie will | 
| 1952 | 1952 | // be empty. | 
| 1953 | 1953 | return false; | 
| @@ -1967,8 +1967,8 @@ discard block | ||
| 1967 | 1967 | */ | 
| 1968 | 1968 |  	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { | 
| 1969 | 1969 | // allow '0' for 389ds | 
| 1970 | -		if(!empty($cookie) || $cookie === '0') { | |
| 1971 | - $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset; | |
| 1970 | +		if (!empty($cookie) || $cookie === '0') { | |
| 1971 | + $cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset; | |
| 1972 | 1972 | $this->cookies[$cacheKey] = $cookie; | 
| 1973 | 1973 | $this->lastCookie = $cookie; | 
| 1974 | 1974 | } | 
| @@ -1996,16 +1996,16 @@ discard block | ||
| 1996 | 1996 |  	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) { | 
| 1997 | 1997 | $pagedSearchOK = false; | 
| 1998 | 1998 |  		if ($limit !== 0) { | 
| 1999 | - $offset = (int)$offset; //can be null | |
| 1999 | + $offset = (int) $offset; //can be null | |
| 2000 | 2000 |  			\OCP\Util::writeLog('user_ldap', | 
| 2001 | 2001 | 'initializing paged search for Filter '.$filter.' base '.print_r($bases, true) | 
| 2002 | - .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, | |
| 2002 | + .' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset, | |
| 2003 | 2003 | ILogger::DEBUG); | 
| 2004 | 2004 | //get the cookie from the search for the previous search, required by LDAP | 
| 2005 | -			foreach($bases as $base) { | |
| 2005 | +			foreach ($bases as $base) { | |
| 2006 | 2006 | |
| 2007 | 2007 | $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | 
| 2008 | -				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { | |
| 2008 | +				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) { | |
| 2009 | 2009 | // no cookie known from a potential previous search. We need | 
| 2010 | 2010 | // to start from 0 to come to the desired page. cookie value | 
| 2011 | 2011 | // of '0' is valid, because 389ds | 
| @@ -2015,17 +2015,17 @@ discard block | ||
| 2015 | 2015 | //still no cookie? obviously, the server does not like us. Let's skip paging efforts. | 
| 2016 | 2016 | // '0' is valid, because 389ds | 
| 2017 | 2017 | //TODO: remember this, probably does not change in the next request... | 
| 2018 | -					if(empty($cookie) && $cookie !== '0') { | |
| 2018 | +					if (empty($cookie) && $cookie !== '0') { | |
| 2019 | 2019 | $cookie = null; | 
| 2020 | 2020 | } | 
| 2021 | 2021 | } | 
| 2022 | -				if(!is_null($cookie)) { | |
| 2022 | +				if (!is_null($cookie)) { | |
| 2023 | 2023 | //since offset = 0, this is a new search. We abandon other searches that might be ongoing. | 
| 2024 | 2024 | $this->abandonPagedSearch(); | 
| 2025 | 2025 |  					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | 
| 2026 | 2026 | $this->connection->getConnectionResource(), $limit, | 
| 2027 | 2027 | false, $cookie); | 
| 2028 | -					if(!$pagedSearchOK) { | |
| 2028 | +					if (!$pagedSearchOK) { | |
| 2029 | 2029 | return false; | 
| 2030 | 2030 | } | 
| 2031 | 2031 |  					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG); | 
| @@ -2048,7 +2048,7 @@ discard block | ||
| 2048 | 2048 | $this->abandonPagedSearch(); | 
| 2049 | 2049 | // in case someone set it to 0 … use 500, otherwise no results will | 
| 2050 | 2050 | // be returned. | 
| 2051 | - $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500; | |
| 2051 | + $pageSize = (int) $this->connection->ldapPagingSize > 0 ? (int) $this->connection->ldapPagingSize : 500; | |
| 2052 | 2052 |  			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | 
| 2053 | 2053 | $this->connection->getConnectionResource(), | 
| 2054 | 2054 | $pageSize, false, ''); | 
| @@ -47,1204 +47,1204 @@ | ||
| 47 | 47 | use OCP\ILogger; | 
| 48 | 48 | |
| 49 | 49 |  class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend { | 
| 50 | - protected $enabled = false; | |
| 51 | - | |
| 52 | - /** | |
| 53 | - * @var string[] $cachedGroupMembers array of users with gid as key | |
| 54 | - */ | |
| 55 | - protected $cachedGroupMembers; | |
| 56 | - | |
| 57 | - /** | |
| 58 | - * @var string[] $cachedGroupsByMember array of groups with uid as key | |
| 59 | - */ | |
| 60 | - protected $cachedGroupsByMember; | |
| 61 | - | |
| 62 | - /** | |
| 63 | - * @var string[] $cachedNestedGroups array of groups with gid (DN) as key | |
| 64 | - */ | |
| 65 | - protected $cachedNestedGroups; | |
| 66 | - | |
| 67 | - /** @var GroupPluginManager */ | |
| 68 | - protected $groupPluginManager; | |
| 69 | - | |
| 70 | -	public function __construct(Access $access, GroupPluginManager $groupPluginManager) { | |
| 71 | - parent::__construct($access); | |
| 72 | - $filter = $this->access->connection->ldapGroupFilter; | |
| 73 | - $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; | |
| 74 | -		if(!empty($filter) && !empty($gassoc)) { | |
| 75 | - $this->enabled = true; | |
| 76 | - } | |
| 77 | - | |
| 78 | - $this->cachedGroupMembers = new CappedMemoryCache(); | |
| 79 | - $this->cachedGroupsByMember = new CappedMemoryCache(); | |
| 80 | - $this->cachedNestedGroups = new CappedMemoryCache(); | |
| 81 | - $this->groupPluginManager = $groupPluginManager; | |
| 82 | - } | |
| 83 | - | |
| 84 | - /** | |
| 85 | - * is user in group? | |
| 86 | - * @param string $uid uid of the user | |
| 87 | - * @param string $gid gid of the group | |
| 88 | - * @return bool | |
| 89 | - * | |
| 90 | - * Checks whether the user is member of a group or not. | |
| 91 | - */ | |
| 92 | -	public function inGroup($uid, $gid) { | |
| 93 | -		if(!$this->enabled) { | |
| 94 | - return false; | |
| 95 | - } | |
| 96 | - $cacheKey = 'inGroup'.$uid.':'.$gid; | |
| 97 | - $inGroup = $this->access->connection->getFromCache($cacheKey); | |
| 98 | -		if(!is_null($inGroup)) { | |
| 99 | - return (bool)$inGroup; | |
| 100 | - } | |
| 101 | - | |
| 102 | - $userDN = $this->access->username2dn($uid); | |
| 103 | - | |
| 104 | -		if(isset($this->cachedGroupMembers[$gid])) { | |
| 105 | - $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); | |
| 106 | - return $isInGroup; | |
| 107 | - } | |
| 108 | - | |
| 109 | - $cacheKeyMembers = 'inGroup-members:'.$gid; | |
| 110 | - $members = $this->access->connection->getFromCache($cacheKeyMembers); | |
| 111 | -		if(!is_null($members)) { | |
| 112 | - $this->cachedGroupMembers[$gid] = $members; | |
| 113 | - $isInGroup = in_array($userDN, $members); | |
| 114 | - $this->access->connection->writeToCache($cacheKey, $isInGroup); | |
| 115 | - return $isInGroup; | |
| 116 | - } | |
| 117 | - | |
| 118 | - $groupDN = $this->access->groupname2dn($gid); | |
| 119 | - // just in case | |
| 120 | -		if(!$groupDN || !$userDN) { | |
| 121 | - $this->access->connection->writeToCache($cacheKey, false); | |
| 122 | - return false; | |
| 123 | - } | |
| 124 | - | |
| 125 | - //check primary group first | |
| 126 | -		if($gid === $this->getUserPrimaryGroup($userDN)) { | |
| 127 | - $this->access->connection->writeToCache($cacheKey, true); | |
| 128 | - return true; | |
| 129 | - } | |
| 130 | - | |
| 131 | - //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. | |
| 132 | - $members = $this->_groupMembers($groupDN); | |
| 133 | - $members = array_keys($members); // uids are returned as keys | |
| 134 | -		if(!is_array($members) || count($members) === 0) { | |
| 135 | - $this->access->connection->writeToCache($cacheKey, false); | |
| 136 | - return false; | |
| 137 | - } | |
| 138 | - | |
| 139 | - //extra work if we don't get back user DNs | |
| 140 | -		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 141 | - $dns = array(); | |
| 142 | - $filterParts = array(); | |
| 143 | - $bytes = 0; | |
| 144 | -			foreach($members as $mid) { | |
| 145 | -				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); | |
| 146 | - $filterParts[] = $filter; | |
| 147 | - $bytes += strlen($filter); | |
| 148 | -				if($bytes >= 9000000) { | |
| 149 | - // AD has a default input buffer of 10 MB, we do not want | |
| 150 | - // to take even the chance to exceed it | |
| 151 | - $filter = $this->access->combineFilterWithOr($filterParts); | |
| 152 | - $bytes = 0; | |
| 153 | - $filterParts = array(); | |
| 154 | - $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); | |
| 155 | - $dns = array_merge($dns, $users); | |
| 156 | - } | |
| 157 | - } | |
| 158 | -			if(count($filterParts) > 0) { | |
| 159 | - $filter = $this->access->combineFilterWithOr($filterParts); | |
| 160 | - $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); | |
| 161 | - $dns = array_merge($dns, $users); | |
| 162 | - } | |
| 163 | - $members = $dns; | |
| 164 | - } | |
| 165 | - | |
| 166 | - $isInGroup = in_array($userDN, $members); | |
| 167 | - $this->access->connection->writeToCache($cacheKey, $isInGroup); | |
| 168 | - $this->access->connection->writeToCache($cacheKeyMembers, $members); | |
| 169 | - $this->cachedGroupMembers[$gid] = $members; | |
| 170 | - | |
| 171 | - return $isInGroup; | |
| 172 | - } | |
| 173 | - | |
| 174 | - /** | |
| 175 | - * @param string $dnGroup | |
| 176 | - * @return array | |
| 177 | - * | |
| 178 | - * For a group that has user membership defined by an LDAP search url attribute returns the users | |
| 179 | - * that match the search url otherwise returns an empty array. | |
| 180 | - */ | |
| 181 | -	public function getDynamicGroupMembers($dnGroup) { | |
| 182 | - $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); | |
| 183 | - | |
| 184 | -		if (empty($dynamicGroupMemberURL)) { | |
| 185 | - return array(); | |
| 186 | - } | |
| 187 | - | |
| 188 | - $dynamicMembers = array(); | |
| 189 | - $memberURLs = $this->access->readAttribute( | |
| 190 | - $dnGroup, | |
| 191 | - $dynamicGroupMemberURL, | |
| 192 | - $this->access->connection->ldapGroupFilter | |
| 193 | - ); | |
| 194 | -		if ($memberURLs !== false) { | |
| 195 | - // this group has the 'memberURL' attribute so this is a dynamic group | |
| 196 | - // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice) | |
| 197 | - // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500)) | |
| 198 | -			$pos = strpos($memberURLs[0], '('); | |
| 199 | -			if ($pos !== false) { | |
| 200 | - $memberUrlFilter = substr($memberURLs[0], $pos); | |
| 201 | - $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); | |
| 202 | - $dynamicMembers = array(); | |
| 203 | -				foreach($foundMembers as $value) { | |
| 204 | - $dynamicMembers[$value['dn'][0]] = 1; | |
| 205 | - } | |
| 206 | -			} else { | |
| 207 | -				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. | |
| 208 | - 'of group ' . $dnGroup, ILogger::DEBUG); | |
| 209 | - } | |
| 210 | - } | |
| 211 | - return $dynamicMembers; | |
| 212 | - } | |
| 213 | - | |
| 214 | - /** | |
| 215 | - * @param string $dnGroup | |
| 216 | - * @param array|null &$seen | |
| 217 | - * @return array|mixed|null | |
| 218 | - * @throws \OC\ServerNotAvailableException | |
| 219 | - */ | |
| 220 | -	private function _groupMembers($dnGroup, &$seen = null) { | |
| 221 | -		if ($seen === null) { | |
| 222 | - $seen = []; | |
| 223 | - } | |
| 224 | - $allMembers = []; | |
| 225 | -		if (array_key_exists($dnGroup, $seen)) { | |
| 226 | - // avoid loops | |
| 227 | - return []; | |
| 228 | - } | |
| 229 | - // used extensively in cron job, caching makes sense for nested groups | |
| 230 | - $cacheKey = '_groupMembers'.$dnGroup; | |
| 231 | - $groupMembers = $this->access->connection->getFromCache($cacheKey); | |
| 232 | -		if($groupMembers !== null) { | |
| 233 | - return $groupMembers; | |
| 234 | - } | |
| 235 | - $seen[$dnGroup] = 1; | |
| 236 | - $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr); | |
| 237 | -		if (is_array($members)) { | |
| 238 | -			$fetcher = function($memberDN, &$seen) { | |
| 239 | - return $this->_groupMembers($memberDN, $seen); | |
| 240 | - }; | |
| 241 | - $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members); | |
| 242 | - } | |
| 243 | - | |
| 244 | - $allMembers += $this->getDynamicGroupMembers($dnGroup); | |
| 245 | - | |
| 246 | - $this->access->connection->writeToCache($cacheKey, $allMembers); | |
| 247 | - return $allMembers; | |
| 248 | - } | |
| 249 | - | |
| 250 | - /** | |
| 251 | - * @param string $DN | |
| 252 | - * @param array|null &$seen | |
| 253 | - * @return array | |
| 254 | - * @throws \OC\ServerNotAvailableException | |
| 255 | - */ | |
| 256 | -	private function _getGroupDNsFromMemberOf($DN) { | |
| 257 | - $groups = $this->access->readAttribute($DN, 'memberOf'); | |
| 258 | -		if (!is_array($groups)) { | |
| 259 | - return []; | |
| 260 | - } | |
| 261 | - | |
| 262 | -		$fetcher = function($groupDN) { | |
| 263 | -			if (isset($this->cachedNestedGroups[$groupDN])) { | |
| 264 | - $nestedGroups = $this->cachedNestedGroups[$groupDN]; | |
| 265 | -			} else { | |
| 266 | - $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf'); | |
| 267 | -				if (!is_array($nestedGroups)) { | |
| 268 | - $nestedGroups = []; | |
| 269 | - } | |
| 270 | - $this->cachedNestedGroups[$groupDN] = $nestedGroups; | |
| 271 | - } | |
| 272 | - return $nestedGroups; | |
| 273 | - }; | |
| 274 | - | |
| 275 | - $groups = $this->walkNestedGroups($DN, $fetcher, $groups); | |
| 276 | - return $this->access->groupsMatchFilter($groups); | |
| 277 | - } | |
| 278 | - | |
| 279 | - /** | |
| 280 | - * @param string $dn | |
| 281 | - * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns | |
| 282 | - * @param array $list | |
| 283 | - * @return array | |
| 284 | - */ | |
| 285 | -	private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array { | |
| 286 | - $nesting = (int) $this->access->connection->ldapNestedGroups; | |
| 287 | - // depending on the input, we either have a list of DNs or a list of LDAP records | |
| 288 | - // also, the output expects either DNs or records. Testing the first element should suffice. | |
| 289 | - $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); | |
| 290 | - | |
| 291 | -		if ($nesting !== 1) { | |
| 292 | -			if($recordMode) { | |
| 293 | - // the keys are numeric, but should hold the DN | |
| 294 | -				return array_reduce($list, function ($transformed, $record) use ($dn) { | |
| 295 | -					if($record['dn'][0] != $dn) { | |
| 296 | - $transformed[$record['dn'][0]] = $record; | |
| 297 | - } | |
| 298 | - return $transformed; | |
| 299 | - }, []); | |
| 300 | - } | |
| 301 | - return $list; | |
| 302 | - } | |
| 303 | - | |
| 304 | - $seen = []; | |
| 305 | -		while ($record = array_pop($list)) { | |
| 306 | - $recordDN = $recordMode ? $record['dn'][0] : $record; | |
| 307 | -			if ($recordDN === $dn || array_key_exists($recordDN, $seen)) { | |
| 308 | - // Prevent loops | |
| 309 | - continue; | |
| 310 | - } | |
| 311 | - $fetched = $fetcher($record, $seen); | |
| 312 | - $list = array_merge($list, $fetched); | |
| 313 | - $seen[$recordDN] = $record; | |
| 314 | - } | |
| 315 | - | |
| 316 | - return $recordMode ? $seen : array_keys($seen); | |
| 317 | - } | |
| 318 | - | |
| 319 | - /** | |
| 320 | - * translates a gidNumber into an ownCloud internal name | |
| 321 | - * @param string $gid as given by gidNumber on POSIX LDAP | |
| 322 | - * @param string $dn a DN that belongs to the same domain as the group | |
| 323 | - * @return string|bool | |
| 324 | - */ | |
| 325 | -	public function gidNumber2Name($gid, $dn) { | |
| 326 | - $cacheKey = 'gidNumberToName' . $gid; | |
| 327 | - $groupName = $this->access->connection->getFromCache($cacheKey); | |
| 328 | -		if(!is_null($groupName) && isset($groupName)) { | |
| 329 | - return $groupName; | |
| 330 | - } | |
| 331 | - | |
| 332 | - //we need to get the DN from LDAP | |
| 333 | - $filter = $this->access->combineFilterWithAnd([ | |
| 334 | - $this->access->connection->ldapGroupFilter, | |
| 335 | - 'objectClass=posixGroup', | |
| 336 | - $this->access->connection->ldapGidNumber . '=' . $gid | |
| 337 | - ]); | |
| 338 | -		$result = $this->access->searchGroups($filter, array('dn'), 1); | |
| 339 | -		if(empty($result)) { | |
| 340 | - return false; | |
| 341 | - } | |
| 342 | - $dn = $result[0]['dn'][0]; | |
| 343 | - | |
| 344 | - //and now the group name | |
| 345 | - //NOTE once we have separate ownCloud group IDs and group names we can | |
| 346 | - //directly read the display name attribute instead of the DN | |
| 347 | - $name = $this->access->dn2groupname($dn); | |
| 348 | - | |
| 349 | - $this->access->connection->writeToCache($cacheKey, $name); | |
| 350 | - | |
| 351 | - return $name; | |
| 352 | - } | |
| 353 | - | |
| 354 | - /** | |
| 355 | - * returns the entry's gidNumber | |
| 356 | - * @param string $dn | |
| 357 | - * @param string $attribute | |
| 358 | - * @return string|bool | |
| 359 | - */ | |
| 360 | -	private function getEntryGidNumber($dn, $attribute) { | |
| 361 | - $value = $this->access->readAttribute($dn, $attribute); | |
| 362 | -		if(is_array($value) && !empty($value)) { | |
| 363 | - return $value[0]; | |
| 364 | - } | |
| 365 | - return false; | |
| 366 | - } | |
| 367 | - | |
| 368 | - /** | |
| 369 | - * returns the group's primary ID | |
| 370 | - * @param string $dn | |
| 371 | - * @return string|bool | |
| 372 | - */ | |
| 373 | -	public function getGroupGidNumber($dn) { | |
| 374 | - return $this->getEntryGidNumber($dn, 'gidNumber'); | |
| 375 | - } | |
| 376 | - | |
| 377 | - /** | |
| 378 | - * returns the user's gidNumber | |
| 379 | - * @param string $dn | |
| 380 | - * @return string|bool | |
| 381 | - */ | |
| 382 | -	public function getUserGidNumber($dn) { | |
| 383 | - $gidNumber = false; | |
| 384 | -		if($this->access->connection->hasGidNumber) { | |
| 385 | - $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); | |
| 386 | -			if($gidNumber === false) { | |
| 387 | - $this->access->connection->hasGidNumber = false; | |
| 388 | - } | |
| 389 | - } | |
| 390 | - return $gidNumber; | |
| 391 | - } | |
| 392 | - | |
| 393 | - /** | |
| 394 | - * returns a filter for a "users has specific gid" search or count operation | |
| 395 | - * | |
| 396 | - * @param string $groupDN | |
| 397 | - * @param string $search | |
| 398 | - * @return string | |
| 399 | - * @throws \Exception | |
| 400 | - */ | |
| 401 | -	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { | |
| 402 | - $groupID = $this->getGroupGidNumber($groupDN); | |
| 403 | -		if($groupID === false) { | |
| 404 | -			throw new \Exception('Not a valid group'); | |
| 405 | - } | |
| 406 | - | |
| 407 | - $filterParts = []; | |
| 408 | - $filterParts[] = $this->access->getFilterForUserCount(); | |
| 409 | -		if ($search !== '') { | |
| 410 | - $filterParts[] = $this->access->getFilterPartForUserSearch($search); | |
| 411 | - } | |
| 412 | - $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID; | |
| 413 | - | |
| 414 | - return $this->access->combineFilterWithAnd($filterParts); | |
| 415 | - } | |
| 416 | - | |
| 417 | - /** | |
| 418 | - * returns a list of users that have the given group as gid number | |
| 419 | - * | |
| 420 | - * @param string $groupDN | |
| 421 | - * @param string $search | |
| 422 | - * @param int $limit | |
| 423 | - * @param int $offset | |
| 424 | - * @return string[] | |
| 425 | - */ | |
| 426 | -	public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 427 | -		try { | |
| 428 | - $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); | |
| 429 | - $users = $this->access->fetchListOfUsers( | |
| 430 | - $filter, | |
| 431 | - [$this->access->connection->ldapUserDisplayName, 'dn'], | |
| 432 | - $limit, | |
| 433 | - $offset | |
| 434 | - ); | |
| 435 | - return $this->access->nextcloudUserNames($users); | |
| 436 | -		} catch (\Exception $e) { | |
| 437 | - return []; | |
| 438 | - } | |
| 439 | - } | |
| 440 | - | |
| 441 | - /** | |
| 442 | - * returns the number of users that have the given group as gid number | |
| 443 | - * | |
| 444 | - * @param string $groupDN | |
| 445 | - * @param string $search | |
| 446 | - * @param int $limit | |
| 447 | - * @param int $offset | |
| 448 | - * @return int | |
| 449 | - */ | |
| 450 | -	public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 451 | -		try { | |
| 452 | - $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); | |
| 453 | - $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); | |
| 454 | - return (int)$users; | |
| 455 | -		} catch (\Exception $e) { | |
| 456 | - return 0; | |
| 457 | - } | |
| 458 | - } | |
| 459 | - | |
| 460 | - /** | |
| 461 | - * gets the gidNumber of a user | |
| 462 | - * @param string $dn | |
| 463 | - * @return string | |
| 464 | - */ | |
| 465 | -	public function getUserGroupByGid($dn) { | |
| 466 | - $groupID = $this->getUserGidNumber($dn); | |
| 467 | -		if($groupID !== false) { | |
| 468 | - $groupName = $this->gidNumber2Name($groupID, $dn); | |
| 469 | -			if($groupName !== false) { | |
| 470 | - return $groupName; | |
| 471 | - } | |
| 472 | - } | |
| 473 | - | |
| 474 | - return false; | |
| 475 | - } | |
| 476 | - | |
| 477 | - /** | |
| 478 | - * translates a primary group ID into an Nextcloud internal name | |
| 479 | - * @param string $gid as given by primaryGroupID on AD | |
| 480 | - * @param string $dn a DN that belongs to the same domain as the group | |
| 481 | - * @return string|bool | |
| 482 | - */ | |
| 483 | -	public function primaryGroupID2Name($gid, $dn) { | |
| 484 | - $cacheKey = 'primaryGroupIDtoName'; | |
| 485 | - $groupNames = $this->access->connection->getFromCache($cacheKey); | |
| 486 | -		if(!is_null($groupNames) && isset($groupNames[$gid])) { | |
| 487 | - return $groupNames[$gid]; | |
| 488 | - } | |
| 489 | - | |
| 490 | - $domainObjectSid = $this->access->getSID($dn); | |
| 491 | -		if($domainObjectSid === false) { | |
| 492 | - return false; | |
| 493 | - } | |
| 494 | - | |
| 495 | - //we need to get the DN from LDAP | |
| 496 | - $filter = $this->access->combineFilterWithAnd(array( | |
| 497 | - $this->access->connection->ldapGroupFilter, | |
| 498 | - 'objectsid=' . $domainObjectSid . '-' . $gid | |
| 499 | - )); | |
| 500 | -		$result = $this->access->searchGroups($filter, array('dn'), 1); | |
| 501 | -		if(empty($result)) { | |
| 502 | - return false; | |
| 503 | - } | |
| 504 | - $dn = $result[0]['dn'][0]; | |
| 505 | - | |
| 506 | - //and now the group name | |
| 507 | - //NOTE once we have separate Nextcloud group IDs and group names we can | |
| 508 | - //directly read the display name attribute instead of the DN | |
| 509 | - $name = $this->access->dn2groupname($dn); | |
| 510 | - | |
| 511 | - $this->access->connection->writeToCache($cacheKey, $name); | |
| 512 | - | |
| 513 | - return $name; | |
| 514 | - } | |
| 515 | - | |
| 516 | - /** | |
| 517 | - * returns the entry's primary group ID | |
| 518 | - * @param string $dn | |
| 519 | - * @param string $attribute | |
| 520 | - * @return string|bool | |
| 521 | - */ | |
| 522 | -	private function getEntryGroupID($dn, $attribute) { | |
| 523 | - $value = $this->access->readAttribute($dn, $attribute); | |
| 524 | -		if(is_array($value) && !empty($value)) { | |
| 525 | - return $value[0]; | |
| 526 | - } | |
| 527 | - return false; | |
| 528 | - } | |
| 529 | - | |
| 530 | - /** | |
| 531 | - * returns the group's primary ID | |
| 532 | - * @param string $dn | |
| 533 | - * @return string|bool | |
| 534 | - */ | |
| 535 | -	public function getGroupPrimaryGroupID($dn) { | |
| 536 | - return $this->getEntryGroupID($dn, 'primaryGroupToken'); | |
| 537 | - } | |
| 538 | - | |
| 539 | - /** | |
| 540 | - * returns the user's primary group ID | |
| 541 | - * @param string $dn | |
| 542 | - * @return string|bool | |
| 543 | - */ | |
| 544 | -	public function getUserPrimaryGroupIDs($dn) { | |
| 545 | - $primaryGroupID = false; | |
| 546 | -		if($this->access->connection->hasPrimaryGroups) { | |
| 547 | - $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); | |
| 548 | -			if($primaryGroupID === false) { | |
| 549 | - $this->access->connection->hasPrimaryGroups = false; | |
| 550 | - } | |
| 551 | - } | |
| 552 | - return $primaryGroupID; | |
| 553 | - } | |
| 554 | - | |
| 555 | - /** | |
| 556 | - * returns a filter for a "users in primary group" search or count operation | |
| 557 | - * | |
| 558 | - * @param string $groupDN | |
| 559 | - * @param string $search | |
| 560 | - * @return string | |
| 561 | - * @throws \Exception | |
| 562 | - */ | |
| 563 | -	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { | |
| 564 | - $groupID = $this->getGroupPrimaryGroupID($groupDN); | |
| 565 | -		if($groupID === false) { | |
| 566 | -			throw new \Exception('Not a valid group'); | |
| 567 | - } | |
| 568 | - | |
| 569 | - $filterParts = []; | |
| 570 | - $filterParts[] = $this->access->getFilterForUserCount(); | |
| 571 | -		if ($search !== '') { | |
| 572 | - $filterParts[] = $this->access->getFilterPartForUserSearch($search); | |
| 573 | - } | |
| 574 | - $filterParts[] = 'primaryGroupID=' . $groupID; | |
| 575 | - | |
| 576 | - return $this->access->combineFilterWithAnd($filterParts); | |
| 577 | - } | |
| 578 | - | |
| 579 | - /** | |
| 580 | - * returns a list of users that have the given group as primary group | |
| 581 | - * | |
| 582 | - * @param string $groupDN | |
| 583 | - * @param string $search | |
| 584 | - * @param int $limit | |
| 585 | - * @param int $offset | |
| 586 | - * @return string[] | |
| 587 | - */ | |
| 588 | -	public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 589 | -		try { | |
| 590 | - $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); | |
| 591 | - $users = $this->access->fetchListOfUsers( | |
| 592 | - $filter, | |
| 593 | - array($this->access->connection->ldapUserDisplayName, 'dn'), | |
| 594 | - $limit, | |
| 595 | - $offset | |
| 596 | - ); | |
| 597 | - return $this->access->nextcloudUserNames($users); | |
| 598 | -		} catch (\Exception $e) { | |
| 599 | - return array(); | |
| 600 | - } | |
| 601 | - } | |
| 602 | - | |
| 603 | - /** | |
| 604 | - * returns the number of users that have the given group as primary group | |
| 605 | - * | |
| 606 | - * @param string $groupDN | |
| 607 | - * @param string $search | |
| 608 | - * @param int $limit | |
| 609 | - * @param int $offset | |
| 610 | - * @return int | |
| 611 | - */ | |
| 612 | -	public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 613 | -		try { | |
| 614 | - $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); | |
| 615 | -			$users = $this->access->countUsers($filter, array('dn'), $limit, $offset); | |
| 616 | - return (int)$users; | |
| 617 | -		} catch (\Exception $e) { | |
| 618 | - return 0; | |
| 619 | - } | |
| 620 | - } | |
| 621 | - | |
| 622 | - /** | |
| 623 | - * gets the primary group of a user | |
| 624 | - * @param string $dn | |
| 625 | - * @return string | |
| 626 | - */ | |
| 627 | -	public function getUserPrimaryGroup($dn) { | |
| 628 | - $groupID = $this->getUserPrimaryGroupIDs($dn); | |
| 629 | -		if($groupID !== false) { | |
| 630 | - $groupName = $this->primaryGroupID2Name($groupID, $dn); | |
| 631 | -			if($groupName !== false) { | |
| 632 | - return $groupName; | |
| 633 | - } | |
| 634 | - } | |
| 635 | - | |
| 636 | - return false; | |
| 637 | - } | |
| 638 | - | |
| 639 | - /** | |
| 640 | - * Get all groups a user belongs to | |
| 641 | - * @param string $uid Name of the user | |
| 642 | - * @return array with group names | |
| 643 | - * | |
| 644 | - * This function fetches all groups a user belongs to. It does not check | |
| 645 | - * if the user exists at all. | |
| 646 | - * | |
| 647 | - * This function includes groups based on dynamic group membership. | |
| 648 | - */ | |
| 649 | -	public function getUserGroups($uid) { | |
| 650 | -		if(!$this->enabled) { | |
| 651 | - return array(); | |
| 652 | - } | |
| 653 | - $cacheKey = 'getUserGroups'.$uid; | |
| 654 | - $userGroups = $this->access->connection->getFromCache($cacheKey); | |
| 655 | -		if(!is_null($userGroups)) { | |
| 656 | - return $userGroups; | |
| 657 | - } | |
| 658 | - $userDN = $this->access->username2dn($uid); | |
| 659 | -		if(!$userDN) { | |
| 660 | - $this->access->connection->writeToCache($cacheKey, array()); | |
| 661 | - return array(); | |
| 662 | - } | |
| 663 | - | |
| 664 | - $groups = []; | |
| 665 | - $primaryGroup = $this->getUserPrimaryGroup($userDN); | |
| 666 | - $gidGroupName = $this->getUserGroupByGid($userDN); | |
| 667 | - | |
| 668 | - $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); | |
| 669 | - | |
| 670 | -		if (!empty($dynamicGroupMemberURL)) { | |
| 671 | - // look through dynamic groups to add them to the result array if needed | |
| 672 | - $groupsToMatch = $this->access->fetchListOfGroups( | |
| 673 | -				$this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL)); | |
| 674 | -			foreach($groupsToMatch as $dynamicGroup) { | |
| 675 | -				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { | |
| 676 | - continue; | |
| 677 | - } | |
| 678 | -				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '('); | |
| 679 | -				if ($pos !== false) { | |
| 680 | - $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos); | |
| 681 | - // apply filter via ldap search to see if this user is in this | |
| 682 | - // dynamic group | |
| 683 | - $userMatch = $this->access->readAttribute( | |
| 684 | - $userDN, | |
| 685 | - $this->access->connection->ldapUserDisplayName, | |
| 686 | - $memberUrlFilter | |
| 687 | - ); | |
| 688 | -					if ($userMatch !== false) { | |
| 689 | - // match found so this user is in this group | |
| 690 | - $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); | |
| 691 | -						if(is_string($groupName)) { | |
| 692 | - // be sure to never return false if the dn could not be | |
| 693 | - // resolved to a name, for whatever reason. | |
| 694 | - $groups[] = $groupName; | |
| 695 | - } | |
| 696 | - } | |
| 697 | -				} else { | |
| 698 | -					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. | |
| 699 | - 'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG); | |
| 700 | - } | |
| 701 | - } | |
| 702 | - } | |
| 703 | - | |
| 704 | - // if possible, read out membership via memberOf. It's far faster than | |
| 705 | - // performing a search, which still is a fallback later. | |
| 706 | - // memberof doesn't support memberuid, so skip it here. | |
| 707 | - if((int)$this->access->connection->hasMemberOfFilterSupport === 1 | |
| 708 | - && (int)$this->access->connection->useMemberOfToDetectMembership === 1 | |
| 709 | - && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' | |
| 710 | -		    ) { | |
| 711 | - $groupDNs = $this->_getGroupDNsFromMemberOf($userDN); | |
| 712 | -			if (is_array($groupDNs)) { | |
| 713 | -				foreach ($groupDNs as $dn) { | |
| 714 | - $groupName = $this->access->dn2groupname($dn); | |
| 715 | -					if(is_string($groupName)) { | |
| 716 | - // be sure to never return false if the dn could not be | |
| 717 | - // resolved to a name, for whatever reason. | |
| 718 | - $groups[] = $groupName; | |
| 719 | - } | |
| 720 | - } | |
| 721 | - } | |
| 722 | - | |
| 723 | -			if($primaryGroup !== false) { | |
| 724 | - $groups[] = $primaryGroup; | |
| 725 | - } | |
| 726 | -			if($gidGroupName !== false) { | |
| 727 | - $groups[] = $gidGroupName; | |
| 728 | - } | |
| 729 | - $this->access->connection->writeToCache($cacheKey, $groups); | |
| 730 | - return $groups; | |
| 731 | - } | |
| 732 | - | |
| 733 | - //uniqueMember takes DN, memberuid the uid, so we need to distinguish | |
| 734 | - if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') | |
| 735 | - || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') | |
| 736 | -		) { | |
| 737 | - $uid = $userDN; | |
| 738 | -		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 739 | - $result = $this->access->readAttribute($userDN, 'uid'); | |
| 740 | -			if ($result === false) { | |
| 741 | -				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. | |
| 742 | - $this->access->connection->ldapHost, ILogger::DEBUG); | |
| 743 | - } | |
| 744 | - $uid = $result[0]; | |
| 745 | -		} else { | |
| 746 | - // just in case | |
| 747 | - $uid = $userDN; | |
| 748 | - } | |
| 749 | - | |
| 750 | -		if(isset($this->cachedGroupsByMember[$uid])) { | |
| 751 | - $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); | |
| 752 | -		} else { | |
| 753 | - $groupsByMember = array_values($this->getGroupsByMember($uid)); | |
| 754 | - $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember); | |
| 755 | - $this->cachedGroupsByMember[$uid] = $groupsByMember; | |
| 756 | - $groups = array_merge($groups, $groupsByMember); | |
| 757 | - } | |
| 758 | - | |
| 759 | -		if($primaryGroup !== false) { | |
| 760 | - $groups[] = $primaryGroup; | |
| 761 | - } | |
| 762 | -		if($gidGroupName !== false) { | |
| 763 | - $groups[] = $gidGroupName; | |
| 764 | - } | |
| 765 | - | |
| 766 | - $groups = array_unique($groups, SORT_LOCALE_STRING); | |
| 767 | - $this->access->connection->writeToCache($cacheKey, $groups); | |
| 768 | - | |
| 769 | - return $groups; | |
| 770 | - } | |
| 771 | - | |
| 772 | - /** | |
| 773 | - * @param string $dn | |
| 774 | - * @param array|null &$seen | |
| 775 | - * @return array | |
| 776 | - */ | |
| 777 | -	private function getGroupsByMember($dn, &$seen = null) { | |
| 778 | -		if ($seen === null) { | |
| 779 | - $seen = []; | |
| 780 | - } | |
| 781 | -		if (array_key_exists($dn, $seen)) { | |
| 782 | - // avoid loops | |
| 783 | - return []; | |
| 784 | - } | |
| 785 | - $allGroups = []; | |
| 786 | - $seen[$dn] = true; | |
| 787 | - $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn; | |
| 788 | - $groups = $this->access->fetchListOfGroups($filter, | |
| 789 | - [$this->access->connection->ldapGroupDisplayName, 'dn']); | |
| 790 | -		if (is_array($groups)) { | |
| 791 | -			$fetcher = function ($dn, &$seen) { | |
| 792 | -				if(is_array($dn) && isset($dn['dn'][0])) { | |
| 793 | - $dn = $dn['dn'][0]; | |
| 794 | - } | |
| 795 | - return $this->getGroupsByMember($dn, $seen); | |
| 796 | - }; | |
| 797 | - $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups); | |
| 798 | - } | |
| 799 | - $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups)); | |
| 800 | - return array_intersect_key($allGroups, array_flip($visibleGroups)); | |
| 801 | - } | |
| 802 | - | |
| 803 | - /** | |
| 804 | - * get a list of all users in a group | |
| 805 | - * | |
| 806 | - * @param string $gid | |
| 807 | - * @param string $search | |
| 808 | - * @param int $limit | |
| 809 | - * @param int $offset | |
| 810 | - * @return array with user ids | |
| 811 | - */ | |
| 812 | -	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { | |
| 813 | -		if(!$this->enabled) { | |
| 814 | - return array(); | |
| 815 | - } | |
| 816 | -		if(!$this->groupExists($gid)) { | |
| 817 | - return array(); | |
| 818 | - } | |
| 819 | - $search = $this->access->escapeFilterPart($search, true); | |
| 820 | - $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; | |
| 821 | - // check for cache of the exact query | |
| 822 | - $groupUsers = $this->access->connection->getFromCache($cacheKey); | |
| 823 | -		if(!is_null($groupUsers)) { | |
| 824 | - return $groupUsers; | |
| 825 | - } | |
| 826 | - | |
| 827 | - // check for cache of the query without limit and offset | |
| 828 | -		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); | |
| 829 | -		if(!is_null($groupUsers)) { | |
| 830 | - $groupUsers = array_slice($groupUsers, $offset, $limit); | |
| 831 | - $this->access->connection->writeToCache($cacheKey, $groupUsers); | |
| 832 | - return $groupUsers; | |
| 833 | - } | |
| 834 | - | |
| 835 | -		if($limit === -1) { | |
| 836 | - $limit = null; | |
| 837 | - } | |
| 838 | - $groupDN = $this->access->groupname2dn($gid); | |
| 839 | -		if(!$groupDN) { | |
| 840 | - // group couldn't be found, return empty resultset | |
| 841 | - $this->access->connection->writeToCache($cacheKey, array()); | |
| 842 | - return array(); | |
| 843 | - } | |
| 844 | - | |
| 845 | - $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); | |
| 846 | - $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); | |
| 847 | - $members = $this->_groupMembers($groupDN); | |
| 848 | -		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { | |
| 849 | - //in case users could not be retrieved, return empty result set | |
| 850 | - $this->access->connection->writeToCache($cacheKey, []); | |
| 851 | - return []; | |
| 852 | - } | |
| 853 | - | |
| 854 | - $groupUsers = array(); | |
| 855 | - $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); | |
| 856 | - $attrs = $this->access->userManager->getAttributes(true); | |
| 857 | -		foreach($members as $member) { | |
| 858 | -			if($isMemberUid) { | |
| 859 | - //we got uids, need to get their DNs to 'translate' them to user names | |
| 860 | - $filter = $this->access->combineFilterWithAnd(array( | |
| 861 | -					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), | |
| 862 | - $this->access->getFilterPartForUserSearch($search) | |
| 863 | - )); | |
| 864 | - $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); | |
| 865 | -				if(count($ldap_users) < 1) { | |
| 866 | - continue; | |
| 867 | - } | |
| 868 | - $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); | |
| 869 | -			} else { | |
| 870 | - //we got DNs, check if we need to filter by search or we can give back all of them | |
| 871 | -				if ($search !== '') { | |
| 872 | - if(!$this->access->readAttribute($member, | |
| 873 | - $this->access->connection->ldapUserDisplayName, | |
| 874 | -						$this->access->getFilterPartForUserSearch($search))) { | |
| 875 | - continue; | |
| 876 | - } | |
| 877 | - } | |
| 878 | - // dn2username will also check if the users belong to the allowed base | |
| 879 | -				if($ocname = $this->access->dn2username($member)) { | |
| 880 | - $groupUsers[] = $ocname; | |
| 881 | - } | |
| 882 | - } | |
| 883 | - } | |
| 884 | - | |
| 885 | - $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers)); | |
| 886 | - natsort($groupUsers); | |
| 887 | -		$this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers); | |
| 888 | - $groupUsers = array_slice($groupUsers, $offset, $limit); | |
| 889 | - | |
| 890 | - $this->access->connection->writeToCache($cacheKey, $groupUsers); | |
| 891 | - | |
| 892 | - return $groupUsers; | |
| 893 | - } | |
| 894 | - | |
| 895 | - /** | |
| 896 | - * returns the number of users in a group, who match the search term | |
| 897 | - * @param string $gid the internal group name | |
| 898 | - * @param string $search optional, a search string | |
| 899 | - * @return int|bool | |
| 900 | - */ | |
| 901 | -	public function countUsersInGroup($gid, $search = '') { | |
| 902 | -		if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) { | |
| 903 | - return $this->groupPluginManager->countUsersInGroup($gid, $search); | |
| 904 | - } | |
| 905 | - | |
| 906 | - $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; | |
| 907 | -		if(!$this->enabled || !$this->groupExists($gid)) { | |
| 908 | - return false; | |
| 909 | - } | |
| 910 | - $groupUsers = $this->access->connection->getFromCache($cacheKey); | |
| 911 | -		if(!is_null($groupUsers)) { | |
| 912 | - return $groupUsers; | |
| 913 | - } | |
| 914 | - | |
| 915 | - $groupDN = $this->access->groupname2dn($gid); | |
| 916 | -		if(!$groupDN) { | |
| 917 | - // group couldn't be found, return empty result set | |
| 918 | - $this->access->connection->writeToCache($cacheKey, false); | |
| 919 | - return false; | |
| 920 | - } | |
| 921 | - | |
| 922 | - $members = $this->_groupMembers($groupDN); | |
| 923 | - $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); | |
| 924 | -		if(!$members && $primaryUserCount === 0) { | |
| 925 | - //in case users could not be retrieved, return empty result set | |
| 926 | - $this->access->connection->writeToCache($cacheKey, false); | |
| 927 | - return false; | |
| 928 | - } | |
| 929 | - | |
| 930 | -		if ($search === '') { | |
| 931 | - $groupUsers = count($members) + $primaryUserCount; | |
| 932 | - $this->access->connection->writeToCache($cacheKey, $groupUsers); | |
| 933 | - return $groupUsers; | |
| 934 | - } | |
| 935 | - $search = $this->access->escapeFilterPart($search, true); | |
| 936 | - $isMemberUid = | |
| 937 | - (strtolower($this->access->connection->ldapGroupMemberAssocAttr) | |
| 938 | - === 'memberuid'); | |
| 939 | - | |
| 940 | - //we need to apply the search filter | |
| 941 | - //alternatives that need to be checked: | |
| 942 | - //a) get all users by search filter and array_intersect them | |
| 943 | - //b) a, but only when less than 1k 10k ?k users like it is | |
| 944 | - //c) put all DNs|uids in a LDAP filter, combine with the search string | |
| 945 | - // and let it count. | |
| 946 | - //For now this is not important, because the only use of this method | |
| 947 | - //does not supply a search string | |
| 948 | - $groupUsers = array(); | |
| 949 | -		foreach($members as $member) { | |
| 950 | -			if($isMemberUid) { | |
| 951 | - //we got uids, need to get their DNs to 'translate' them to user names | |
| 952 | - $filter = $this->access->combineFilterWithAnd(array( | |
| 953 | -					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), | |
| 954 | - $this->access->getFilterPartForUserSearch($search) | |
| 955 | - )); | |
| 956 | - $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); | |
| 957 | -				if(count($ldap_users) < 1) { | |
| 958 | - continue; | |
| 959 | - } | |
| 960 | - $groupUsers[] = $this->access->dn2username($ldap_users[0]); | |
| 961 | -			} else { | |
| 962 | - //we need to apply the search filter now | |
| 963 | - if(!$this->access->readAttribute($member, | |
| 964 | - $this->access->connection->ldapUserDisplayName, | |
| 965 | -					$this->access->getFilterPartForUserSearch($search))) { | |
| 966 | - continue; | |
| 967 | - } | |
| 968 | - // dn2username will also check if the users belong to the allowed base | |
| 969 | -				if($ocname = $this->access->dn2username($member)) { | |
| 970 | - $groupUsers[] = $ocname; | |
| 971 | - } | |
| 972 | - } | |
| 973 | - } | |
| 974 | - | |
| 975 | - //and get users that have the group as primary | |
| 976 | - $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search); | |
| 977 | - | |
| 978 | - return count($groupUsers) + $primaryUsers; | |
| 979 | - } | |
| 980 | - | |
| 981 | - /** | |
| 982 | - * get a list of all groups | |
| 983 | - * | |
| 984 | - * @param string $search | |
| 985 | - * @param $limit | |
| 986 | - * @param int $offset | |
| 987 | - * @return array with group names | |
| 988 | - * | |
| 989 | - * Returns a list with all groups (used by getGroups) | |
| 990 | - */ | |
| 991 | -	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { | |
| 992 | -		if(!$this->enabled) { | |
| 993 | - return array(); | |
| 994 | - } | |
| 995 | - $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; | |
| 996 | - | |
| 997 | - //Check cache before driving unnecessary searches | |
| 998 | -		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); | |
| 999 | - $ldap_groups = $this->access->connection->getFromCache($cacheKey); | |
| 1000 | -		if(!is_null($ldap_groups)) { | |
| 1001 | - return $ldap_groups; | |
| 1002 | - } | |
| 1003 | - | |
| 1004 | - // if we'd pass -1 to LDAP search, we'd end up in a Protocol | |
| 1005 | - // error. With a limit of 0, we get 0 results. So we pass null. | |
| 1006 | -		if($limit <= 0) { | |
| 1007 | - $limit = null; | |
| 1008 | - } | |
| 1009 | - $filter = $this->access->combineFilterWithAnd(array( | |
| 1010 | - $this->access->connection->ldapGroupFilter, | |
| 1011 | - $this->access->getFilterPartForGroupSearch($search) | |
| 1012 | - )); | |
| 1013 | -		\OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG); | |
| 1014 | - $ldap_groups = $this->access->fetchListOfGroups($filter, | |
| 1015 | - array($this->access->connection->ldapGroupDisplayName, 'dn'), | |
| 1016 | - $limit, | |
| 1017 | - $offset); | |
| 1018 | - $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups); | |
| 1019 | - | |
| 1020 | - $this->access->connection->writeToCache($cacheKey, $ldap_groups); | |
| 1021 | - return $ldap_groups; | |
| 1022 | - } | |
| 1023 | - | |
| 1024 | - /** | |
| 1025 | - * get a list of all groups using a paged search | |
| 1026 | - * | |
| 1027 | - * @param string $search | |
| 1028 | - * @param int $limit | |
| 1029 | - * @param int $offset | |
| 1030 | - * @return array with group names | |
| 1031 | - * | |
| 1032 | - * Returns a list with all groups | |
| 1033 | - * Uses a paged search if available to override a | |
| 1034 | - * server side search limit. | |
| 1035 | - * (active directory has a limit of 1000 by default) | |
| 1036 | - */ | |
| 1037 | -	public function getGroups($search = '', $limit = -1, $offset = 0) { | |
| 1038 | -		if(!$this->enabled) { | |
| 1039 | - return array(); | |
| 1040 | - } | |
| 1041 | - $search = $this->access->escapeFilterPart($search, true); | |
| 1042 | - $pagingSize = (int)$this->access->connection->ldapPagingSize; | |
| 1043 | -		if ($pagingSize <= 0) { | |
| 1044 | - return $this->getGroupsChunk($search, $limit, $offset); | |
| 1045 | - } | |
| 1046 | - $maxGroups = 100000; // limit max results (just for safety reasons) | |
| 1047 | -		if ($limit > -1) { | |
| 1048 | - $overallLimit = min($limit + $offset, $maxGroups); | |
| 1049 | -		} else { | |
| 1050 | - $overallLimit = $maxGroups; | |
| 1051 | - } | |
| 1052 | - $chunkOffset = $offset; | |
| 1053 | - $allGroups = array(); | |
| 1054 | -		while ($chunkOffset < $overallLimit) { | |
| 1055 | - $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset); | |
| 1056 | - $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset); | |
| 1057 | - $nread = count($ldapGroups); | |
| 1058 | -			\OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG); | |
| 1059 | -			if ($nread) { | |
| 1060 | - $allGroups = array_merge($allGroups, $ldapGroups); | |
| 1061 | - $chunkOffset += $nread; | |
| 1062 | - } | |
| 1063 | -			if ($nread < $chunkLimit) { | |
| 1064 | - break; | |
| 1065 | - } | |
| 1066 | - } | |
| 1067 | - return $allGroups; | |
| 1068 | - } | |
| 1069 | - | |
| 1070 | - /** | |
| 1071 | - * @param string $group | |
| 1072 | - * @return bool | |
| 1073 | - */ | |
| 1074 | -	public function groupMatchesFilter($group) { | |
| 1075 | - return (strripos($group, $this->groupSearch) !== false); | |
| 1076 | - } | |
| 1077 | - | |
| 1078 | - /** | |
| 1079 | - * check if a group exists | |
| 1080 | - * @param string $gid | |
| 1081 | - * @return bool | |
| 1082 | - */ | |
| 1083 | -	public function groupExists($gid) { | |
| 1084 | -		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid); | |
| 1085 | -		if(!is_null($groupExists)) { | |
| 1086 | - return (bool)$groupExists; | |
| 1087 | - } | |
| 1088 | - | |
| 1089 | - //getting dn, if false the group does not exist. If dn, it may be mapped | |
| 1090 | - //only, requires more checking. | |
| 1091 | - $dn = $this->access->groupname2dn($gid); | |
| 1092 | -		if(!$dn) { | |
| 1093 | -			$this->access->connection->writeToCache('groupExists'.$gid, false); | |
| 1094 | - return false; | |
| 1095 | - } | |
| 1096 | - | |
| 1097 | - //if group really still exists, we will be able to read its objectclass | |
| 1098 | -		if(!is_array($this->access->readAttribute($dn, ''))) { | |
| 1099 | -			$this->access->connection->writeToCache('groupExists'.$gid, false); | |
| 1100 | - return false; | |
| 1101 | - } | |
| 1102 | - | |
| 1103 | -		$this->access->connection->writeToCache('groupExists'.$gid, true); | |
| 1104 | - return true; | |
| 1105 | - } | |
| 1106 | - | |
| 1107 | - /** | |
| 1108 | - * Check if backend implements actions | |
| 1109 | - * @param int $actions bitwise-or'ed actions | |
| 1110 | - * @return boolean | |
| 1111 | - * | |
| 1112 | - * Returns the supported actions as int to be | |
| 1113 | - * compared with GroupInterface::CREATE_GROUP etc. | |
| 1114 | - */ | |
| 1115 | -	public function implementsActions($actions) { | |
| 1116 | - return (bool)((GroupInterface::COUNT_USERS | | |
| 1117 | - $this->groupPluginManager->getImplementedActions()) & $actions); | |
| 1118 | - } | |
| 1119 | - | |
| 1120 | - /** | |
| 1121 | - * Return access for LDAP interaction. | |
| 1122 | - * @return Access instance of Access for LDAP interaction | |
| 1123 | - */ | |
| 1124 | -	public function getLDAPAccess($gid) { | |
| 1125 | - return $this->access; | |
| 1126 | - } | |
| 1127 | - | |
| 1128 | - /** | |
| 1129 | - * create a group | |
| 1130 | - * @param string $gid | |
| 1131 | - * @return bool | |
| 1132 | - * @throws \Exception | |
| 1133 | - */ | |
| 1134 | -	public function createGroup($gid) { | |
| 1135 | -		if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) { | |
| 1136 | -			if ($dn = $this->groupPluginManager->createGroup($gid)) { | |
| 1137 | - //updates group mapping | |
| 1138 | - $this->access->dn2ocname($dn, $gid, false); | |
| 1139 | -				$this->access->connection->writeToCache("groupExists".$gid, true); | |
| 1140 | - } | |
| 1141 | - return $dn != null; | |
| 1142 | - } | |
| 1143 | -		throw new \Exception('Could not create group in LDAP backend.'); | |
| 1144 | - } | |
| 1145 | - | |
| 1146 | - /** | |
| 1147 | - * delete a group | |
| 1148 | - * @param string $gid gid of the group to delete | |
| 1149 | - * @return bool | |
| 1150 | - * @throws \Exception | |
| 1151 | - */ | |
| 1152 | -	public function deleteGroup($gid) { | |
| 1153 | -		if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) { | |
| 1154 | -			if ($ret = $this->groupPluginManager->deleteGroup($gid)) { | |
| 1155 | - #delete group in nextcloud internal db | |
| 1156 | - $this->access->getGroupMapper()->unmap($gid); | |
| 1157 | -				$this->access->connection->writeToCache("groupExists".$gid, false); | |
| 1158 | - } | |
| 1159 | - return $ret; | |
| 1160 | - } | |
| 1161 | -		throw new \Exception('Could not delete group in LDAP backend.'); | |
| 1162 | - } | |
| 1163 | - | |
| 1164 | - /** | |
| 1165 | - * Add a user to a group | |
| 1166 | - * @param string $uid Name of the user to add to group | |
| 1167 | - * @param string $gid Name of the group in which add the user | |
| 1168 | - * @return bool | |
| 1169 | - * @throws \Exception | |
| 1170 | - */ | |
| 1171 | -	public function addToGroup($uid, $gid) { | |
| 1172 | -		if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) { | |
| 1173 | -			if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) { | |
| 1174 | - $this->access->connection->clearCache(); | |
| 1175 | - unset($this->cachedGroupMembers[$gid]); | |
| 1176 | - } | |
| 1177 | - return $ret; | |
| 1178 | - } | |
| 1179 | -		throw new \Exception('Could not add user to group in LDAP backend.'); | |
| 1180 | - } | |
| 1181 | - | |
| 1182 | - /** | |
| 1183 | - * Removes a user from a group | |
| 1184 | - * @param string $uid Name of the user to remove from group | |
| 1185 | - * @param string $gid Name of the group from which remove the user | |
| 1186 | - * @return bool | |
| 1187 | - * @throws \Exception | |
| 1188 | - */ | |
| 1189 | -	public function removeFromGroup($uid, $gid) { | |
| 1190 | -		if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) { | |
| 1191 | -			if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) { | |
| 1192 | - $this->access->connection->clearCache(); | |
| 1193 | - unset($this->cachedGroupMembers[$gid]); | |
| 1194 | - } | |
| 1195 | - return $ret; | |
| 1196 | - } | |
| 1197 | -		throw new \Exception('Could not remove user from group in LDAP backend.'); | |
| 1198 | - } | |
| 1199 | - | |
| 1200 | - /** | |
| 1201 | - * Gets group details | |
| 1202 | - * @param string $gid Name of the group | |
| 1203 | - * @return array | false | |
| 1204 | - * @throws \Exception | |
| 1205 | - */ | |
| 1206 | -	public function getGroupDetails($gid) { | |
| 1207 | -		if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) { | |
| 1208 | - return $this->groupPluginManager->getGroupDetails($gid); | |
| 1209 | - } | |
| 1210 | -		throw new \Exception('Could not get group details in LDAP backend.'); | |
| 1211 | - } | |
| 1212 | - | |
| 1213 | - /** | |
| 1214 | - * Return LDAP connection resource from a cloned connection. | |
| 1215 | - * The cloned connection needs to be closed manually. | |
| 1216 | - * of the current access. | |
| 1217 | - * @param string $gid | |
| 1218 | - * @return resource of the LDAP connection | |
| 1219 | - */ | |
| 1220 | -	public function getNewLDAPConnection($gid) { | |
| 1221 | - $connection = clone $this->access->getConnection(); | |
| 1222 | - return $connection->getConnectionResource(); | |
| 1223 | - } | |
| 1224 | - | |
| 1225 | - /** | |
| 1226 | - * @throws \OC\ServerNotAvailableException | |
| 1227 | - */ | |
| 1228 | -	public function getDisplayName(string $gid): string { | |
| 1229 | -		if ($this->groupPluginManager instanceof IGetDisplayNameBackend) { | |
| 1230 | - return $this->groupPluginManager->getDisplayName($gid); | |
| 1231 | - } | |
| 1232 | - | |
| 1233 | - $cacheKey = 'group_getDisplayName' . $gid; | |
| 1234 | -		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { | |
| 1235 | - return $displayName; | |
| 1236 | - } | |
| 1237 | - | |
| 1238 | - $displayName = $this->access->readAttribute( | |
| 1239 | - $this->access->groupname2dn($gid), | |
| 1240 | - $this->access->connection->ldapGroupDisplayName); | |
| 1241 | - | |
| 1242 | -		if ($displayName && (count($displayName) > 0)) { | |
| 1243 | - $displayName = $displayName[0]; | |
| 1244 | - $this->access->connection->writeToCache($cacheKey, $displayName); | |
| 1245 | - return $displayName; | |
| 1246 | - } | |
| 1247 | - | |
| 1248 | - return ''; | |
| 1249 | - } | |
| 50 | + protected $enabled = false; | |
| 51 | + | |
| 52 | + /** | |
| 53 | + * @var string[] $cachedGroupMembers array of users with gid as key | |
| 54 | + */ | |
| 55 | + protected $cachedGroupMembers; | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * @var string[] $cachedGroupsByMember array of groups with uid as key | |
| 59 | + */ | |
| 60 | + protected $cachedGroupsByMember; | |
| 61 | + | |
| 62 | + /** | |
| 63 | + * @var string[] $cachedNestedGroups array of groups with gid (DN) as key | |
| 64 | + */ | |
| 65 | + protected $cachedNestedGroups; | |
| 66 | + | |
| 67 | + /** @var GroupPluginManager */ | |
| 68 | + protected $groupPluginManager; | |
| 69 | + | |
| 70 | +    public function __construct(Access $access, GroupPluginManager $groupPluginManager) { | |
| 71 | + parent::__construct($access); | |
| 72 | + $filter = $this->access->connection->ldapGroupFilter; | |
| 73 | + $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; | |
| 74 | +        if(!empty($filter) && !empty($gassoc)) { | |
| 75 | + $this->enabled = true; | |
| 76 | + } | |
| 77 | + | |
| 78 | + $this->cachedGroupMembers = new CappedMemoryCache(); | |
| 79 | + $this->cachedGroupsByMember = new CappedMemoryCache(); | |
| 80 | + $this->cachedNestedGroups = new CappedMemoryCache(); | |
| 81 | + $this->groupPluginManager = $groupPluginManager; | |
| 82 | + } | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * is user in group? | |
| 86 | + * @param string $uid uid of the user | |
| 87 | + * @param string $gid gid of the group | |
| 88 | + * @return bool | |
| 89 | + * | |
| 90 | + * Checks whether the user is member of a group or not. | |
| 91 | + */ | |
| 92 | +    public function inGroup($uid, $gid) { | |
| 93 | +        if(!$this->enabled) { | |
| 94 | + return false; | |
| 95 | + } | |
| 96 | + $cacheKey = 'inGroup'.$uid.':'.$gid; | |
| 97 | + $inGroup = $this->access->connection->getFromCache($cacheKey); | |
| 98 | +        if(!is_null($inGroup)) { | |
| 99 | + return (bool)$inGroup; | |
| 100 | + } | |
| 101 | + | |
| 102 | + $userDN = $this->access->username2dn($uid); | |
| 103 | + | |
| 104 | +        if(isset($this->cachedGroupMembers[$gid])) { | |
| 105 | + $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); | |
| 106 | + return $isInGroup; | |
| 107 | + } | |
| 108 | + | |
| 109 | + $cacheKeyMembers = 'inGroup-members:'.$gid; | |
| 110 | + $members = $this->access->connection->getFromCache($cacheKeyMembers); | |
| 111 | +        if(!is_null($members)) { | |
| 112 | + $this->cachedGroupMembers[$gid] = $members; | |
| 113 | + $isInGroup = in_array($userDN, $members); | |
| 114 | + $this->access->connection->writeToCache($cacheKey, $isInGroup); | |
| 115 | + return $isInGroup; | |
| 116 | + } | |
| 117 | + | |
| 118 | + $groupDN = $this->access->groupname2dn($gid); | |
| 119 | + // just in case | |
| 120 | +        if(!$groupDN || !$userDN) { | |
| 121 | + $this->access->connection->writeToCache($cacheKey, false); | |
| 122 | + return false; | |
| 123 | + } | |
| 124 | + | |
| 125 | + //check primary group first | |
| 126 | +        if($gid === $this->getUserPrimaryGroup($userDN)) { | |
| 127 | + $this->access->connection->writeToCache($cacheKey, true); | |
| 128 | + return true; | |
| 129 | + } | |
| 130 | + | |
| 131 | + //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. | |
| 132 | + $members = $this->_groupMembers($groupDN); | |
| 133 | + $members = array_keys($members); // uids are returned as keys | |
| 134 | +        if(!is_array($members) || count($members) === 0) { | |
| 135 | + $this->access->connection->writeToCache($cacheKey, false); | |
| 136 | + return false; | |
| 137 | + } | |
| 138 | + | |
| 139 | + //extra work if we don't get back user DNs | |
| 140 | +        if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 141 | + $dns = array(); | |
| 142 | + $filterParts = array(); | |
| 143 | + $bytes = 0; | |
| 144 | +            foreach($members as $mid) { | |
| 145 | +                $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); | |
| 146 | + $filterParts[] = $filter; | |
| 147 | + $bytes += strlen($filter); | |
| 148 | +                if($bytes >= 9000000) { | |
| 149 | + // AD has a default input buffer of 10 MB, we do not want | |
| 150 | + // to take even the chance to exceed it | |
| 151 | + $filter = $this->access->combineFilterWithOr($filterParts); | |
| 152 | + $bytes = 0; | |
| 153 | + $filterParts = array(); | |
| 154 | + $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); | |
| 155 | + $dns = array_merge($dns, $users); | |
| 156 | + } | |
| 157 | + } | |
| 158 | +            if(count($filterParts) > 0) { | |
| 159 | + $filter = $this->access->combineFilterWithOr($filterParts); | |
| 160 | + $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); | |
| 161 | + $dns = array_merge($dns, $users); | |
| 162 | + } | |
| 163 | + $members = $dns; | |
| 164 | + } | |
| 165 | + | |
| 166 | + $isInGroup = in_array($userDN, $members); | |
| 167 | + $this->access->connection->writeToCache($cacheKey, $isInGroup); | |
| 168 | + $this->access->connection->writeToCache($cacheKeyMembers, $members); | |
| 169 | + $this->cachedGroupMembers[$gid] = $members; | |
| 170 | + | |
| 171 | + return $isInGroup; | |
| 172 | + } | |
| 173 | + | |
| 174 | + /** | |
| 175 | + * @param string $dnGroup | |
| 176 | + * @return array | |
| 177 | + * | |
| 178 | + * For a group that has user membership defined by an LDAP search url attribute returns the users | |
| 179 | + * that match the search url otherwise returns an empty array. | |
| 180 | + */ | |
| 181 | +    public function getDynamicGroupMembers($dnGroup) { | |
| 182 | + $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); | |
| 183 | + | |
| 184 | +        if (empty($dynamicGroupMemberURL)) { | |
| 185 | + return array(); | |
| 186 | + } | |
| 187 | + | |
| 188 | + $dynamicMembers = array(); | |
| 189 | + $memberURLs = $this->access->readAttribute( | |
| 190 | + $dnGroup, | |
| 191 | + $dynamicGroupMemberURL, | |
| 192 | + $this->access->connection->ldapGroupFilter | |
| 193 | + ); | |
| 194 | +        if ($memberURLs !== false) { | |
| 195 | + // this group has the 'memberURL' attribute so this is a dynamic group | |
| 196 | + // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice) | |
| 197 | + // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500)) | |
| 198 | +            $pos = strpos($memberURLs[0], '('); | |
| 199 | +            if ($pos !== false) { | |
| 200 | + $memberUrlFilter = substr($memberURLs[0], $pos); | |
| 201 | + $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); | |
| 202 | + $dynamicMembers = array(); | |
| 203 | +                foreach($foundMembers as $value) { | |
| 204 | + $dynamicMembers[$value['dn'][0]] = 1; | |
| 205 | + } | |
| 206 | +            } else { | |
| 207 | +                \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. | |
| 208 | + 'of group ' . $dnGroup, ILogger::DEBUG); | |
| 209 | + } | |
| 210 | + } | |
| 211 | + return $dynamicMembers; | |
| 212 | + } | |
| 213 | + | |
| 214 | + /** | |
| 215 | + * @param string $dnGroup | |
| 216 | + * @param array|null &$seen | |
| 217 | + * @return array|mixed|null | |
| 218 | + * @throws \OC\ServerNotAvailableException | |
| 219 | + */ | |
| 220 | +    private function _groupMembers($dnGroup, &$seen = null) { | |
| 221 | +        if ($seen === null) { | |
| 222 | + $seen = []; | |
| 223 | + } | |
| 224 | + $allMembers = []; | |
| 225 | +        if (array_key_exists($dnGroup, $seen)) { | |
| 226 | + // avoid loops | |
| 227 | + return []; | |
| 228 | + } | |
| 229 | + // used extensively in cron job, caching makes sense for nested groups | |
| 230 | + $cacheKey = '_groupMembers'.$dnGroup; | |
| 231 | + $groupMembers = $this->access->connection->getFromCache($cacheKey); | |
| 232 | +        if($groupMembers !== null) { | |
| 233 | + return $groupMembers; | |
| 234 | + } | |
| 235 | + $seen[$dnGroup] = 1; | |
| 236 | + $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr); | |
| 237 | +        if (is_array($members)) { | |
| 238 | +            $fetcher = function($memberDN, &$seen) { | |
| 239 | + return $this->_groupMembers($memberDN, $seen); | |
| 240 | + }; | |
| 241 | + $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members); | |
| 242 | + } | |
| 243 | + | |
| 244 | + $allMembers += $this->getDynamicGroupMembers($dnGroup); | |
| 245 | + | |
| 246 | + $this->access->connection->writeToCache($cacheKey, $allMembers); | |
| 247 | + return $allMembers; | |
| 248 | + } | |
| 249 | + | |
| 250 | + /** | |
| 251 | + * @param string $DN | |
| 252 | + * @param array|null &$seen | |
| 253 | + * @return array | |
| 254 | + * @throws \OC\ServerNotAvailableException | |
| 255 | + */ | |
| 256 | +    private function _getGroupDNsFromMemberOf($DN) { | |
| 257 | + $groups = $this->access->readAttribute($DN, 'memberOf'); | |
| 258 | +        if (!is_array($groups)) { | |
| 259 | + return []; | |
| 260 | + } | |
| 261 | + | |
| 262 | +        $fetcher = function($groupDN) { | |
| 263 | +            if (isset($this->cachedNestedGroups[$groupDN])) { | |
| 264 | + $nestedGroups = $this->cachedNestedGroups[$groupDN]; | |
| 265 | +            } else { | |
| 266 | + $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf'); | |
| 267 | +                if (!is_array($nestedGroups)) { | |
| 268 | + $nestedGroups = []; | |
| 269 | + } | |
| 270 | + $this->cachedNestedGroups[$groupDN] = $nestedGroups; | |
| 271 | + } | |
| 272 | + return $nestedGroups; | |
| 273 | + }; | |
| 274 | + | |
| 275 | + $groups = $this->walkNestedGroups($DN, $fetcher, $groups); | |
| 276 | + return $this->access->groupsMatchFilter($groups); | |
| 277 | + } | |
| 278 | + | |
| 279 | + /** | |
| 280 | + * @param string $dn | |
| 281 | + * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns | |
| 282 | + * @param array $list | |
| 283 | + * @return array | |
| 284 | + */ | |
| 285 | +    private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array { | |
| 286 | + $nesting = (int) $this->access->connection->ldapNestedGroups; | |
| 287 | + // depending on the input, we either have a list of DNs or a list of LDAP records | |
| 288 | + // also, the output expects either DNs or records. Testing the first element should suffice. | |
| 289 | + $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); | |
| 290 | + | |
| 291 | +        if ($nesting !== 1) { | |
| 292 | +            if($recordMode) { | |
| 293 | + // the keys are numeric, but should hold the DN | |
| 294 | +                return array_reduce($list, function ($transformed, $record) use ($dn) { | |
| 295 | +                    if($record['dn'][0] != $dn) { | |
| 296 | + $transformed[$record['dn'][0]] = $record; | |
| 297 | + } | |
| 298 | + return $transformed; | |
| 299 | + }, []); | |
| 300 | + } | |
| 301 | + return $list; | |
| 302 | + } | |
| 303 | + | |
| 304 | + $seen = []; | |
| 305 | +        while ($record = array_pop($list)) { | |
| 306 | + $recordDN = $recordMode ? $record['dn'][0] : $record; | |
| 307 | +            if ($recordDN === $dn || array_key_exists($recordDN, $seen)) { | |
| 308 | + // Prevent loops | |
| 309 | + continue; | |
| 310 | + } | |
| 311 | + $fetched = $fetcher($record, $seen); | |
| 312 | + $list = array_merge($list, $fetched); | |
| 313 | + $seen[$recordDN] = $record; | |
| 314 | + } | |
| 315 | + | |
| 316 | + return $recordMode ? $seen : array_keys($seen); | |
| 317 | + } | |
| 318 | + | |
| 319 | + /** | |
| 320 | + * translates a gidNumber into an ownCloud internal name | |
| 321 | + * @param string $gid as given by gidNumber on POSIX LDAP | |
| 322 | + * @param string $dn a DN that belongs to the same domain as the group | |
| 323 | + * @return string|bool | |
| 324 | + */ | |
| 325 | +    public function gidNumber2Name($gid, $dn) { | |
| 326 | + $cacheKey = 'gidNumberToName' . $gid; | |
| 327 | + $groupName = $this->access->connection->getFromCache($cacheKey); | |
| 328 | +        if(!is_null($groupName) && isset($groupName)) { | |
| 329 | + return $groupName; | |
| 330 | + } | |
| 331 | + | |
| 332 | + //we need to get the DN from LDAP | |
| 333 | + $filter = $this->access->combineFilterWithAnd([ | |
| 334 | + $this->access->connection->ldapGroupFilter, | |
| 335 | + 'objectClass=posixGroup', | |
| 336 | + $this->access->connection->ldapGidNumber . '=' . $gid | |
| 337 | + ]); | |
| 338 | +        $result = $this->access->searchGroups($filter, array('dn'), 1); | |
| 339 | +        if(empty($result)) { | |
| 340 | + return false; | |
| 341 | + } | |
| 342 | + $dn = $result[0]['dn'][0]; | |
| 343 | + | |
| 344 | + //and now the group name | |
| 345 | + //NOTE once we have separate ownCloud group IDs and group names we can | |
| 346 | + //directly read the display name attribute instead of the DN | |
| 347 | + $name = $this->access->dn2groupname($dn); | |
| 348 | + | |
| 349 | + $this->access->connection->writeToCache($cacheKey, $name); | |
| 350 | + | |
| 351 | + return $name; | |
| 352 | + } | |
| 353 | + | |
| 354 | + /** | |
| 355 | + * returns the entry's gidNumber | |
| 356 | + * @param string $dn | |
| 357 | + * @param string $attribute | |
| 358 | + * @return string|bool | |
| 359 | + */ | |
| 360 | +    private function getEntryGidNumber($dn, $attribute) { | |
| 361 | + $value = $this->access->readAttribute($dn, $attribute); | |
| 362 | +        if(is_array($value) && !empty($value)) { | |
| 363 | + return $value[0]; | |
| 364 | + } | |
| 365 | + return false; | |
| 366 | + } | |
| 367 | + | |
| 368 | + /** | |
| 369 | + * returns the group's primary ID | |
| 370 | + * @param string $dn | |
| 371 | + * @return string|bool | |
| 372 | + */ | |
| 373 | +    public function getGroupGidNumber($dn) { | |
| 374 | + return $this->getEntryGidNumber($dn, 'gidNumber'); | |
| 375 | + } | |
| 376 | + | |
| 377 | + /** | |
| 378 | + * returns the user's gidNumber | |
| 379 | + * @param string $dn | |
| 380 | + * @return string|bool | |
| 381 | + */ | |
| 382 | +    public function getUserGidNumber($dn) { | |
| 383 | + $gidNumber = false; | |
| 384 | +        if($this->access->connection->hasGidNumber) { | |
| 385 | + $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); | |
| 386 | +            if($gidNumber === false) { | |
| 387 | + $this->access->connection->hasGidNumber = false; | |
| 388 | + } | |
| 389 | + } | |
| 390 | + return $gidNumber; | |
| 391 | + } | |
| 392 | + | |
| 393 | + /** | |
| 394 | + * returns a filter for a "users has specific gid" search or count operation | |
| 395 | + * | |
| 396 | + * @param string $groupDN | |
| 397 | + * @param string $search | |
| 398 | + * @return string | |
| 399 | + * @throws \Exception | |
| 400 | + */ | |
| 401 | +    private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { | |
| 402 | + $groupID = $this->getGroupGidNumber($groupDN); | |
| 403 | +        if($groupID === false) { | |
| 404 | +            throw new \Exception('Not a valid group'); | |
| 405 | + } | |
| 406 | + | |
| 407 | + $filterParts = []; | |
| 408 | + $filterParts[] = $this->access->getFilterForUserCount(); | |
| 409 | +        if ($search !== '') { | |
| 410 | + $filterParts[] = $this->access->getFilterPartForUserSearch($search); | |
| 411 | + } | |
| 412 | + $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID; | |
| 413 | + | |
| 414 | + return $this->access->combineFilterWithAnd($filterParts); | |
| 415 | + } | |
| 416 | + | |
| 417 | + /** | |
| 418 | + * returns a list of users that have the given group as gid number | |
| 419 | + * | |
| 420 | + * @param string $groupDN | |
| 421 | + * @param string $search | |
| 422 | + * @param int $limit | |
| 423 | + * @param int $offset | |
| 424 | + * @return string[] | |
| 425 | + */ | |
| 426 | +    public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 427 | +        try { | |
| 428 | + $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); | |
| 429 | + $users = $this->access->fetchListOfUsers( | |
| 430 | + $filter, | |
| 431 | + [$this->access->connection->ldapUserDisplayName, 'dn'], | |
| 432 | + $limit, | |
| 433 | + $offset | |
| 434 | + ); | |
| 435 | + return $this->access->nextcloudUserNames($users); | |
| 436 | +        } catch (\Exception $e) { | |
| 437 | + return []; | |
| 438 | + } | |
| 439 | + } | |
| 440 | + | |
| 441 | + /** | |
| 442 | + * returns the number of users that have the given group as gid number | |
| 443 | + * | |
| 444 | + * @param string $groupDN | |
| 445 | + * @param string $search | |
| 446 | + * @param int $limit | |
| 447 | + * @param int $offset | |
| 448 | + * @return int | |
| 449 | + */ | |
| 450 | +    public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 451 | +        try { | |
| 452 | + $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); | |
| 453 | + $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); | |
| 454 | + return (int)$users; | |
| 455 | +        } catch (\Exception $e) { | |
| 456 | + return 0; | |
| 457 | + } | |
| 458 | + } | |
| 459 | + | |
| 460 | + /** | |
| 461 | + * gets the gidNumber of a user | |
| 462 | + * @param string $dn | |
| 463 | + * @return string | |
| 464 | + */ | |
| 465 | +    public function getUserGroupByGid($dn) { | |
| 466 | + $groupID = $this->getUserGidNumber($dn); | |
| 467 | +        if($groupID !== false) { | |
| 468 | + $groupName = $this->gidNumber2Name($groupID, $dn); | |
| 469 | +            if($groupName !== false) { | |
| 470 | + return $groupName; | |
| 471 | + } | |
| 472 | + } | |
| 473 | + | |
| 474 | + return false; | |
| 475 | + } | |
| 476 | + | |
| 477 | + /** | |
| 478 | + * translates a primary group ID into an Nextcloud internal name | |
| 479 | + * @param string $gid as given by primaryGroupID on AD | |
| 480 | + * @param string $dn a DN that belongs to the same domain as the group | |
| 481 | + * @return string|bool | |
| 482 | + */ | |
| 483 | +    public function primaryGroupID2Name($gid, $dn) { | |
| 484 | + $cacheKey = 'primaryGroupIDtoName'; | |
| 485 | + $groupNames = $this->access->connection->getFromCache($cacheKey); | |
| 486 | +        if(!is_null($groupNames) && isset($groupNames[$gid])) { | |
| 487 | + return $groupNames[$gid]; | |
| 488 | + } | |
| 489 | + | |
| 490 | + $domainObjectSid = $this->access->getSID($dn); | |
| 491 | +        if($domainObjectSid === false) { | |
| 492 | + return false; | |
| 493 | + } | |
| 494 | + | |
| 495 | + //we need to get the DN from LDAP | |
| 496 | + $filter = $this->access->combineFilterWithAnd(array( | |
| 497 | + $this->access->connection->ldapGroupFilter, | |
| 498 | + 'objectsid=' . $domainObjectSid . '-' . $gid | |
| 499 | + )); | |
| 500 | +        $result = $this->access->searchGroups($filter, array('dn'), 1); | |
| 501 | +        if(empty($result)) { | |
| 502 | + return false; | |
| 503 | + } | |
| 504 | + $dn = $result[0]['dn'][0]; | |
| 505 | + | |
| 506 | + //and now the group name | |
| 507 | + //NOTE once we have separate Nextcloud group IDs and group names we can | |
| 508 | + //directly read the display name attribute instead of the DN | |
| 509 | + $name = $this->access->dn2groupname($dn); | |
| 510 | + | |
| 511 | + $this->access->connection->writeToCache($cacheKey, $name); | |
| 512 | + | |
| 513 | + return $name; | |
| 514 | + } | |
| 515 | + | |
| 516 | + /** | |
| 517 | + * returns the entry's primary group ID | |
| 518 | + * @param string $dn | |
| 519 | + * @param string $attribute | |
| 520 | + * @return string|bool | |
| 521 | + */ | |
| 522 | +    private function getEntryGroupID($dn, $attribute) { | |
| 523 | + $value = $this->access->readAttribute($dn, $attribute); | |
| 524 | +        if(is_array($value) && !empty($value)) { | |
| 525 | + return $value[0]; | |
| 526 | + } | |
| 527 | + return false; | |
| 528 | + } | |
| 529 | + | |
| 530 | + /** | |
| 531 | + * returns the group's primary ID | |
| 532 | + * @param string $dn | |
| 533 | + * @return string|bool | |
| 534 | + */ | |
| 535 | +    public function getGroupPrimaryGroupID($dn) { | |
| 536 | + return $this->getEntryGroupID($dn, 'primaryGroupToken'); | |
| 537 | + } | |
| 538 | + | |
| 539 | + /** | |
| 540 | + * returns the user's primary group ID | |
| 541 | + * @param string $dn | |
| 542 | + * @return string|bool | |
| 543 | + */ | |
| 544 | +    public function getUserPrimaryGroupIDs($dn) { | |
| 545 | + $primaryGroupID = false; | |
| 546 | +        if($this->access->connection->hasPrimaryGroups) { | |
| 547 | + $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); | |
| 548 | +            if($primaryGroupID === false) { | |
| 549 | + $this->access->connection->hasPrimaryGroups = false; | |
| 550 | + } | |
| 551 | + } | |
| 552 | + return $primaryGroupID; | |
| 553 | + } | |
| 554 | + | |
| 555 | + /** | |
| 556 | + * returns a filter for a "users in primary group" search or count operation | |
| 557 | + * | |
| 558 | + * @param string $groupDN | |
| 559 | + * @param string $search | |
| 560 | + * @return string | |
| 561 | + * @throws \Exception | |
| 562 | + */ | |
| 563 | +    private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { | |
| 564 | + $groupID = $this->getGroupPrimaryGroupID($groupDN); | |
| 565 | +        if($groupID === false) { | |
| 566 | +            throw new \Exception('Not a valid group'); | |
| 567 | + } | |
| 568 | + | |
| 569 | + $filterParts = []; | |
| 570 | + $filterParts[] = $this->access->getFilterForUserCount(); | |
| 571 | +        if ($search !== '') { | |
| 572 | + $filterParts[] = $this->access->getFilterPartForUserSearch($search); | |
| 573 | + } | |
| 574 | + $filterParts[] = 'primaryGroupID=' . $groupID; | |
| 575 | + | |
| 576 | + return $this->access->combineFilterWithAnd($filterParts); | |
| 577 | + } | |
| 578 | + | |
| 579 | + /** | |
| 580 | + * returns a list of users that have the given group as primary group | |
| 581 | + * | |
| 582 | + * @param string $groupDN | |
| 583 | + * @param string $search | |
| 584 | + * @param int $limit | |
| 585 | + * @param int $offset | |
| 586 | + * @return string[] | |
| 587 | + */ | |
| 588 | +    public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 589 | +        try { | |
| 590 | + $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); | |
| 591 | + $users = $this->access->fetchListOfUsers( | |
| 592 | + $filter, | |
| 593 | + array($this->access->connection->ldapUserDisplayName, 'dn'), | |
| 594 | + $limit, | |
| 595 | + $offset | |
| 596 | + ); | |
| 597 | + return $this->access->nextcloudUserNames($users); | |
| 598 | +        } catch (\Exception $e) { | |
| 599 | + return array(); | |
| 600 | + } | |
| 601 | + } | |
| 602 | + | |
| 603 | + /** | |
| 604 | + * returns the number of users that have the given group as primary group | |
| 605 | + * | |
| 606 | + * @param string $groupDN | |
| 607 | + * @param string $search | |
| 608 | + * @param int $limit | |
| 609 | + * @param int $offset | |
| 610 | + * @return int | |
| 611 | + */ | |
| 612 | +    public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) { | |
| 613 | +        try { | |
| 614 | + $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); | |
| 615 | +            $users = $this->access->countUsers($filter, array('dn'), $limit, $offset); | |
| 616 | + return (int)$users; | |
| 617 | +        } catch (\Exception $e) { | |
| 618 | + return 0; | |
| 619 | + } | |
| 620 | + } | |
| 621 | + | |
| 622 | + /** | |
| 623 | + * gets the primary group of a user | |
| 624 | + * @param string $dn | |
| 625 | + * @return string | |
| 626 | + */ | |
| 627 | +    public function getUserPrimaryGroup($dn) { | |
| 628 | + $groupID = $this->getUserPrimaryGroupIDs($dn); | |
| 629 | +        if($groupID !== false) { | |
| 630 | + $groupName = $this->primaryGroupID2Name($groupID, $dn); | |
| 631 | +            if($groupName !== false) { | |
| 632 | + return $groupName; | |
| 633 | + } | |
| 634 | + } | |
| 635 | + | |
| 636 | + return false; | |
| 637 | + } | |
| 638 | + | |
| 639 | + /** | |
| 640 | + * Get all groups a user belongs to | |
| 641 | + * @param string $uid Name of the user | |
| 642 | + * @return array with group names | |
| 643 | + * | |
| 644 | + * This function fetches all groups a user belongs to. It does not check | |
| 645 | + * if the user exists at all. | |
| 646 | + * | |
| 647 | + * This function includes groups based on dynamic group membership. | |
| 648 | + */ | |
| 649 | +    public function getUserGroups($uid) { | |
| 650 | +        if(!$this->enabled) { | |
| 651 | + return array(); | |
| 652 | + } | |
| 653 | + $cacheKey = 'getUserGroups'.$uid; | |
| 654 | + $userGroups = $this->access->connection->getFromCache($cacheKey); | |
| 655 | +        if(!is_null($userGroups)) { | |
| 656 | + return $userGroups; | |
| 657 | + } | |
| 658 | + $userDN = $this->access->username2dn($uid); | |
| 659 | +        if(!$userDN) { | |
| 660 | + $this->access->connection->writeToCache($cacheKey, array()); | |
| 661 | + return array(); | |
| 662 | + } | |
| 663 | + | |
| 664 | + $groups = []; | |
| 665 | + $primaryGroup = $this->getUserPrimaryGroup($userDN); | |
| 666 | + $gidGroupName = $this->getUserGroupByGid($userDN); | |
| 667 | + | |
| 668 | + $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL); | |
| 669 | + | |
| 670 | +        if (!empty($dynamicGroupMemberURL)) { | |
| 671 | + // look through dynamic groups to add them to the result array if needed | |
| 672 | + $groupsToMatch = $this->access->fetchListOfGroups( | |
| 673 | +                $this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL)); | |
| 674 | +            foreach($groupsToMatch as $dynamicGroup) { | |
| 675 | +                if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { | |
| 676 | + continue; | |
| 677 | + } | |
| 678 | +                $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '('); | |
| 679 | +                if ($pos !== false) { | |
| 680 | + $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos); | |
| 681 | + // apply filter via ldap search to see if this user is in this | |
| 682 | + // dynamic group | |
| 683 | + $userMatch = $this->access->readAttribute( | |
| 684 | + $userDN, | |
| 685 | + $this->access->connection->ldapUserDisplayName, | |
| 686 | + $memberUrlFilter | |
| 687 | + ); | |
| 688 | +                    if ($userMatch !== false) { | |
| 689 | + // match found so this user is in this group | |
| 690 | + $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); | |
| 691 | +                        if(is_string($groupName)) { | |
| 692 | + // be sure to never return false if the dn could not be | |
| 693 | + // resolved to a name, for whatever reason. | |
| 694 | + $groups[] = $groupName; | |
| 695 | + } | |
| 696 | + } | |
| 697 | +                } else { | |
| 698 | +                    \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. | |
| 699 | + 'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG); | |
| 700 | + } | |
| 701 | + } | |
| 702 | + } | |
| 703 | + | |
| 704 | + // if possible, read out membership via memberOf. It's far faster than | |
| 705 | + // performing a search, which still is a fallback later. | |
| 706 | + // memberof doesn't support memberuid, so skip it here. | |
| 707 | + if((int)$this->access->connection->hasMemberOfFilterSupport === 1 | |
| 708 | + && (int)$this->access->connection->useMemberOfToDetectMembership === 1 | |
| 709 | + && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' | |
| 710 | +            ) { | |
| 711 | + $groupDNs = $this->_getGroupDNsFromMemberOf($userDN); | |
| 712 | +            if (is_array($groupDNs)) { | |
| 713 | +                foreach ($groupDNs as $dn) { | |
| 714 | + $groupName = $this->access->dn2groupname($dn); | |
| 715 | +                    if(is_string($groupName)) { | |
| 716 | + // be sure to never return false if the dn could not be | |
| 717 | + // resolved to a name, for whatever reason. | |
| 718 | + $groups[] = $groupName; | |
| 719 | + } | |
| 720 | + } | |
| 721 | + } | |
| 722 | + | |
| 723 | +            if($primaryGroup !== false) { | |
| 724 | + $groups[] = $primaryGroup; | |
| 725 | + } | |
| 726 | +            if($gidGroupName !== false) { | |
| 727 | + $groups[] = $gidGroupName; | |
| 728 | + } | |
| 729 | + $this->access->connection->writeToCache($cacheKey, $groups); | |
| 730 | + return $groups; | |
| 731 | + } | |
| 732 | + | |
| 733 | + //uniqueMember takes DN, memberuid the uid, so we need to distinguish | |
| 734 | + if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') | |
| 735 | + || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') | |
| 736 | +        ) { | |
| 737 | + $uid = $userDN; | |
| 738 | +        } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 739 | + $result = $this->access->readAttribute($userDN, 'uid'); | |
| 740 | +            if ($result === false) { | |
| 741 | +                \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. | |
| 742 | + $this->access->connection->ldapHost, ILogger::DEBUG); | |
| 743 | + } | |
| 744 | + $uid = $result[0]; | |
| 745 | +        } else { | |
| 746 | + // just in case | |
| 747 | + $uid = $userDN; | |
| 748 | + } | |
| 749 | + | |
| 750 | +        if(isset($this->cachedGroupsByMember[$uid])) { | |
| 751 | + $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); | |
| 752 | +        } else { | |
| 753 | + $groupsByMember = array_values($this->getGroupsByMember($uid)); | |
| 754 | + $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember); | |
| 755 | + $this->cachedGroupsByMember[$uid] = $groupsByMember; | |
| 756 | + $groups = array_merge($groups, $groupsByMember); | |
| 757 | + } | |
| 758 | + | |
| 759 | +        if($primaryGroup !== false) { | |
| 760 | + $groups[] = $primaryGroup; | |
| 761 | + } | |
| 762 | +        if($gidGroupName !== false) { | |
| 763 | + $groups[] = $gidGroupName; | |
| 764 | + } | |
| 765 | + | |
| 766 | + $groups = array_unique($groups, SORT_LOCALE_STRING); | |
| 767 | + $this->access->connection->writeToCache($cacheKey, $groups); | |
| 768 | + | |
| 769 | + return $groups; | |
| 770 | + } | |
| 771 | + | |
| 772 | + /** | |
| 773 | + * @param string $dn | |
| 774 | + * @param array|null &$seen | |
| 775 | + * @return array | |
| 776 | + */ | |
| 777 | +    private function getGroupsByMember($dn, &$seen = null) { | |
| 778 | +        if ($seen === null) { | |
| 779 | + $seen = []; | |
| 780 | + } | |
| 781 | +        if (array_key_exists($dn, $seen)) { | |
| 782 | + // avoid loops | |
| 783 | + return []; | |
| 784 | + } | |
| 785 | + $allGroups = []; | |
| 786 | + $seen[$dn] = true; | |
| 787 | + $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn; | |
| 788 | + $groups = $this->access->fetchListOfGroups($filter, | |
| 789 | + [$this->access->connection->ldapGroupDisplayName, 'dn']); | |
| 790 | +        if (is_array($groups)) { | |
| 791 | +            $fetcher = function ($dn, &$seen) { | |
| 792 | +                if(is_array($dn) && isset($dn['dn'][0])) { | |
| 793 | + $dn = $dn['dn'][0]; | |
| 794 | + } | |
| 795 | + return $this->getGroupsByMember($dn, $seen); | |
| 796 | + }; | |
| 797 | + $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups); | |
| 798 | + } | |
| 799 | + $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups)); | |
| 800 | + return array_intersect_key($allGroups, array_flip($visibleGroups)); | |
| 801 | + } | |
| 802 | + | |
| 803 | + /** | |
| 804 | + * get a list of all users in a group | |
| 805 | + * | |
| 806 | + * @param string $gid | |
| 807 | + * @param string $search | |
| 808 | + * @param int $limit | |
| 809 | + * @param int $offset | |
| 810 | + * @return array with user ids | |
| 811 | + */ | |
| 812 | +    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { | |
| 813 | +        if(!$this->enabled) { | |
| 814 | + return array(); | |
| 815 | + } | |
| 816 | +        if(!$this->groupExists($gid)) { | |
| 817 | + return array(); | |
| 818 | + } | |
| 819 | + $search = $this->access->escapeFilterPart($search, true); | |
| 820 | + $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; | |
| 821 | + // check for cache of the exact query | |
| 822 | + $groupUsers = $this->access->connection->getFromCache($cacheKey); | |
| 823 | +        if(!is_null($groupUsers)) { | |
| 824 | + return $groupUsers; | |
| 825 | + } | |
| 826 | + | |
| 827 | + // check for cache of the query without limit and offset | |
| 828 | +        $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); | |
| 829 | +        if(!is_null($groupUsers)) { | |
| 830 | + $groupUsers = array_slice($groupUsers, $offset, $limit); | |
| 831 | + $this->access->connection->writeToCache($cacheKey, $groupUsers); | |
| 832 | + return $groupUsers; | |
| 833 | + } | |
| 834 | + | |
| 835 | +        if($limit === -1) { | |
| 836 | + $limit = null; | |
| 837 | + } | |
| 838 | + $groupDN = $this->access->groupname2dn($gid); | |
| 839 | +        if(!$groupDN) { | |
| 840 | + // group couldn't be found, return empty resultset | |
| 841 | + $this->access->connection->writeToCache($cacheKey, array()); | |
| 842 | + return array(); | |
| 843 | + } | |
| 844 | + | |
| 845 | + $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); | |
| 846 | + $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); | |
| 847 | + $members = $this->_groupMembers($groupDN); | |
| 848 | +        if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { | |
| 849 | + //in case users could not be retrieved, return empty result set | |
| 850 | + $this->access->connection->writeToCache($cacheKey, []); | |
| 851 | + return []; | |
| 852 | + } | |
| 853 | + | |
| 854 | + $groupUsers = array(); | |
| 855 | + $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); | |
| 856 | + $attrs = $this->access->userManager->getAttributes(true); | |
| 857 | +        foreach($members as $member) { | |
| 858 | +            if($isMemberUid) { | |
| 859 | + //we got uids, need to get their DNs to 'translate' them to user names | |
| 860 | + $filter = $this->access->combineFilterWithAnd(array( | |
| 861 | +                    str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), | |
| 862 | + $this->access->getFilterPartForUserSearch($search) | |
| 863 | + )); | |
| 864 | + $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); | |
| 865 | +                if(count($ldap_users) < 1) { | |
| 866 | + continue; | |
| 867 | + } | |
| 868 | + $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); | |
| 869 | +            } else { | |
| 870 | + //we got DNs, check if we need to filter by search or we can give back all of them | |
| 871 | +                if ($search !== '') { | |
| 872 | + if(!$this->access->readAttribute($member, | |
| 873 | + $this->access->connection->ldapUserDisplayName, | |
| 874 | +                        $this->access->getFilterPartForUserSearch($search))) { | |
| 875 | + continue; | |
| 876 | + } | |
| 877 | + } | |
| 878 | + // dn2username will also check if the users belong to the allowed base | |
| 879 | +                if($ocname = $this->access->dn2username($member)) { | |
| 880 | + $groupUsers[] = $ocname; | |
| 881 | + } | |
| 882 | + } | |
| 883 | + } | |
| 884 | + | |
| 885 | + $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers)); | |
| 886 | + natsort($groupUsers); | |
| 887 | +        $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers); | |
| 888 | + $groupUsers = array_slice($groupUsers, $offset, $limit); | |
| 889 | + | |
| 890 | + $this->access->connection->writeToCache($cacheKey, $groupUsers); | |
| 891 | + | |
| 892 | + return $groupUsers; | |
| 893 | + } | |
| 894 | + | |
| 895 | + /** | |
| 896 | + * returns the number of users in a group, who match the search term | |
| 897 | + * @param string $gid the internal group name | |
| 898 | + * @param string $search optional, a search string | |
| 899 | + * @return int|bool | |
| 900 | + */ | |
| 901 | +    public function countUsersInGroup($gid, $search = '') { | |
| 902 | +        if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) { | |
| 903 | + return $this->groupPluginManager->countUsersInGroup($gid, $search); | |
| 904 | + } | |
| 905 | + | |
| 906 | + $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; | |
| 907 | +        if(!$this->enabled || !$this->groupExists($gid)) { | |
| 908 | + return false; | |
| 909 | + } | |
| 910 | + $groupUsers = $this->access->connection->getFromCache($cacheKey); | |
| 911 | +        if(!is_null($groupUsers)) { | |
| 912 | + return $groupUsers; | |
| 913 | + } | |
| 914 | + | |
| 915 | + $groupDN = $this->access->groupname2dn($gid); | |
| 916 | +        if(!$groupDN) { | |
| 917 | + // group couldn't be found, return empty result set | |
| 918 | + $this->access->connection->writeToCache($cacheKey, false); | |
| 919 | + return false; | |
| 920 | + } | |
| 921 | + | |
| 922 | + $members = $this->_groupMembers($groupDN); | |
| 923 | + $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); | |
| 924 | +        if(!$members && $primaryUserCount === 0) { | |
| 925 | + //in case users could not be retrieved, return empty result set | |
| 926 | + $this->access->connection->writeToCache($cacheKey, false); | |
| 927 | + return false; | |
| 928 | + } | |
| 929 | + | |
| 930 | +        if ($search === '') { | |
| 931 | + $groupUsers = count($members) + $primaryUserCount; | |
| 932 | + $this->access->connection->writeToCache($cacheKey, $groupUsers); | |
| 933 | + return $groupUsers; | |
| 934 | + } | |
| 935 | + $search = $this->access->escapeFilterPart($search, true); | |
| 936 | + $isMemberUid = | |
| 937 | + (strtolower($this->access->connection->ldapGroupMemberAssocAttr) | |
| 938 | + === 'memberuid'); | |
| 939 | + | |
| 940 | + //we need to apply the search filter | |
| 941 | + //alternatives that need to be checked: | |
| 942 | + //a) get all users by search filter and array_intersect them | |
| 943 | + //b) a, but only when less than 1k 10k ?k users like it is | |
| 944 | + //c) put all DNs|uids in a LDAP filter, combine with the search string | |
| 945 | + // and let it count. | |
| 946 | + //For now this is not important, because the only use of this method | |
| 947 | + //does not supply a search string | |
| 948 | + $groupUsers = array(); | |
| 949 | +        foreach($members as $member) { | |
| 950 | +            if($isMemberUid) { | |
| 951 | + //we got uids, need to get their DNs to 'translate' them to user names | |
| 952 | + $filter = $this->access->combineFilterWithAnd(array( | |
| 953 | +                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), | |
| 954 | + $this->access->getFilterPartForUserSearch($search) | |
| 955 | + )); | |
| 956 | + $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); | |
| 957 | +                if(count($ldap_users) < 1) { | |
| 958 | + continue; | |
| 959 | + } | |
| 960 | + $groupUsers[] = $this->access->dn2username($ldap_users[0]); | |
| 961 | +            } else { | |
| 962 | + //we need to apply the search filter now | |
| 963 | + if(!$this->access->readAttribute($member, | |
| 964 | + $this->access->connection->ldapUserDisplayName, | |
| 965 | +                    $this->access->getFilterPartForUserSearch($search))) { | |
| 966 | + continue; | |
| 967 | + } | |
| 968 | + // dn2username will also check if the users belong to the allowed base | |
| 969 | +                if($ocname = $this->access->dn2username($member)) { | |
| 970 | + $groupUsers[] = $ocname; | |
| 971 | + } | |
| 972 | + } | |
| 973 | + } | |
| 974 | + | |
| 975 | + //and get users that have the group as primary | |
| 976 | + $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search); | |
| 977 | + | |
| 978 | + return count($groupUsers) + $primaryUsers; | |
| 979 | + } | |
| 980 | + | |
| 981 | + /** | |
| 982 | + * get a list of all groups | |
| 983 | + * | |
| 984 | + * @param string $search | |
| 985 | + * @param $limit | |
| 986 | + * @param int $offset | |
| 987 | + * @return array with group names | |
| 988 | + * | |
| 989 | + * Returns a list with all groups (used by getGroups) | |
| 990 | + */ | |
| 991 | +    protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { | |
| 992 | +        if(!$this->enabled) { | |
| 993 | + return array(); | |
| 994 | + } | |
| 995 | + $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; | |
| 996 | + | |
| 997 | + //Check cache before driving unnecessary searches | |
| 998 | +        \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); | |
| 999 | + $ldap_groups = $this->access->connection->getFromCache($cacheKey); | |
| 1000 | +        if(!is_null($ldap_groups)) { | |
| 1001 | + return $ldap_groups; | |
| 1002 | + } | |
| 1003 | + | |
| 1004 | + // if we'd pass -1 to LDAP search, we'd end up in a Protocol | |
| 1005 | + // error. With a limit of 0, we get 0 results. So we pass null. | |
| 1006 | +        if($limit <= 0) { | |
| 1007 | + $limit = null; | |
| 1008 | + } | |
| 1009 | + $filter = $this->access->combineFilterWithAnd(array( | |
| 1010 | + $this->access->connection->ldapGroupFilter, | |
| 1011 | + $this->access->getFilterPartForGroupSearch($search) | |
| 1012 | + )); | |
| 1013 | +        \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG); | |
| 1014 | + $ldap_groups = $this->access->fetchListOfGroups($filter, | |
| 1015 | + array($this->access->connection->ldapGroupDisplayName, 'dn'), | |
| 1016 | + $limit, | |
| 1017 | + $offset); | |
| 1018 | + $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups); | |
| 1019 | + | |
| 1020 | + $this->access->connection->writeToCache($cacheKey, $ldap_groups); | |
| 1021 | + return $ldap_groups; | |
| 1022 | + } | |
| 1023 | + | |
| 1024 | + /** | |
| 1025 | + * get a list of all groups using a paged search | |
| 1026 | + * | |
| 1027 | + * @param string $search | |
| 1028 | + * @param int $limit | |
| 1029 | + * @param int $offset | |
| 1030 | + * @return array with group names | |
| 1031 | + * | |
| 1032 | + * Returns a list with all groups | |
| 1033 | + * Uses a paged search if available to override a | |
| 1034 | + * server side search limit. | |
| 1035 | + * (active directory has a limit of 1000 by default) | |
| 1036 | + */ | |
| 1037 | +    public function getGroups($search = '', $limit = -1, $offset = 0) { | |
| 1038 | +        if(!$this->enabled) { | |
| 1039 | + return array(); | |
| 1040 | + } | |
| 1041 | + $search = $this->access->escapeFilterPart($search, true); | |
| 1042 | + $pagingSize = (int)$this->access->connection->ldapPagingSize; | |
| 1043 | +        if ($pagingSize <= 0) { | |
| 1044 | + return $this->getGroupsChunk($search, $limit, $offset); | |
| 1045 | + } | |
| 1046 | + $maxGroups = 100000; // limit max results (just for safety reasons) | |
| 1047 | +        if ($limit > -1) { | |
| 1048 | + $overallLimit = min($limit + $offset, $maxGroups); | |
| 1049 | +        } else { | |
| 1050 | + $overallLimit = $maxGroups; | |
| 1051 | + } | |
| 1052 | + $chunkOffset = $offset; | |
| 1053 | + $allGroups = array(); | |
| 1054 | +        while ($chunkOffset < $overallLimit) { | |
| 1055 | + $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset); | |
| 1056 | + $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset); | |
| 1057 | + $nread = count($ldapGroups); | |
| 1058 | +            \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG); | |
| 1059 | +            if ($nread) { | |
| 1060 | + $allGroups = array_merge($allGroups, $ldapGroups); | |
| 1061 | + $chunkOffset += $nread; | |
| 1062 | + } | |
| 1063 | +            if ($nread < $chunkLimit) { | |
| 1064 | + break; | |
| 1065 | + } | |
| 1066 | + } | |
| 1067 | + return $allGroups; | |
| 1068 | + } | |
| 1069 | + | |
| 1070 | + /** | |
| 1071 | + * @param string $group | |
| 1072 | + * @return bool | |
| 1073 | + */ | |
| 1074 | +    public function groupMatchesFilter($group) { | |
| 1075 | + return (strripos($group, $this->groupSearch) !== false); | |
| 1076 | + } | |
| 1077 | + | |
| 1078 | + /** | |
| 1079 | + * check if a group exists | |
| 1080 | + * @param string $gid | |
| 1081 | + * @return bool | |
| 1082 | + */ | |
| 1083 | +    public function groupExists($gid) { | |
| 1084 | +        $groupExists = $this->access->connection->getFromCache('groupExists'.$gid); | |
| 1085 | +        if(!is_null($groupExists)) { | |
| 1086 | + return (bool)$groupExists; | |
| 1087 | + } | |
| 1088 | + | |
| 1089 | + //getting dn, if false the group does not exist. If dn, it may be mapped | |
| 1090 | + //only, requires more checking. | |
| 1091 | + $dn = $this->access->groupname2dn($gid); | |
| 1092 | +        if(!$dn) { | |
| 1093 | +            $this->access->connection->writeToCache('groupExists'.$gid, false); | |
| 1094 | + return false; | |
| 1095 | + } | |
| 1096 | + | |
| 1097 | + //if group really still exists, we will be able to read its objectclass | |
| 1098 | +        if(!is_array($this->access->readAttribute($dn, ''))) { | |
| 1099 | +            $this->access->connection->writeToCache('groupExists'.$gid, false); | |
| 1100 | + return false; | |
| 1101 | + } | |
| 1102 | + | |
| 1103 | +        $this->access->connection->writeToCache('groupExists'.$gid, true); | |
| 1104 | + return true; | |
| 1105 | + } | |
| 1106 | + | |
| 1107 | + /** | |
| 1108 | + * Check if backend implements actions | |
| 1109 | + * @param int $actions bitwise-or'ed actions | |
| 1110 | + * @return boolean | |
| 1111 | + * | |
| 1112 | + * Returns the supported actions as int to be | |
| 1113 | + * compared with GroupInterface::CREATE_GROUP etc. | |
| 1114 | + */ | |
| 1115 | +    public function implementsActions($actions) { | |
| 1116 | + return (bool)((GroupInterface::COUNT_USERS | | |
| 1117 | + $this->groupPluginManager->getImplementedActions()) & $actions); | |
| 1118 | + } | |
| 1119 | + | |
| 1120 | + /** | |
| 1121 | + * Return access for LDAP interaction. | |
| 1122 | + * @return Access instance of Access for LDAP interaction | |
| 1123 | + */ | |
| 1124 | +    public function getLDAPAccess($gid) { | |
| 1125 | + return $this->access; | |
| 1126 | + } | |
| 1127 | + | |
| 1128 | + /** | |
| 1129 | + * create a group | |
| 1130 | + * @param string $gid | |
| 1131 | + * @return bool | |
| 1132 | + * @throws \Exception | |
| 1133 | + */ | |
| 1134 | +    public function createGroup($gid) { | |
| 1135 | +        if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) { | |
| 1136 | +            if ($dn = $this->groupPluginManager->createGroup($gid)) { | |
| 1137 | + //updates group mapping | |
| 1138 | + $this->access->dn2ocname($dn, $gid, false); | |
| 1139 | +                $this->access->connection->writeToCache("groupExists".$gid, true); | |
| 1140 | + } | |
| 1141 | + return $dn != null; | |
| 1142 | + } | |
| 1143 | +        throw new \Exception('Could not create group in LDAP backend.'); | |
| 1144 | + } | |
| 1145 | + | |
| 1146 | + /** | |
| 1147 | + * delete a group | |
| 1148 | + * @param string $gid gid of the group to delete | |
| 1149 | + * @return bool | |
| 1150 | + * @throws \Exception | |
| 1151 | + */ | |
| 1152 | +    public function deleteGroup($gid) { | |
| 1153 | +        if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) { | |
| 1154 | +            if ($ret = $this->groupPluginManager->deleteGroup($gid)) { | |
| 1155 | + #delete group in nextcloud internal db | |
| 1156 | + $this->access->getGroupMapper()->unmap($gid); | |
| 1157 | +                $this->access->connection->writeToCache("groupExists".$gid, false); | |
| 1158 | + } | |
| 1159 | + return $ret; | |
| 1160 | + } | |
| 1161 | +        throw new \Exception('Could not delete group in LDAP backend.'); | |
| 1162 | + } | |
| 1163 | + | |
| 1164 | + /** | |
| 1165 | + * Add a user to a group | |
| 1166 | + * @param string $uid Name of the user to add to group | |
| 1167 | + * @param string $gid Name of the group in which add the user | |
| 1168 | + * @return bool | |
| 1169 | + * @throws \Exception | |
| 1170 | + */ | |
| 1171 | +    public function addToGroup($uid, $gid) { | |
| 1172 | +        if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) { | |
| 1173 | +            if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) { | |
| 1174 | + $this->access->connection->clearCache(); | |
| 1175 | + unset($this->cachedGroupMembers[$gid]); | |
| 1176 | + } | |
| 1177 | + return $ret; | |
| 1178 | + } | |
| 1179 | +        throw new \Exception('Could not add user to group in LDAP backend.'); | |
| 1180 | + } | |
| 1181 | + | |
| 1182 | + /** | |
| 1183 | + * Removes a user from a group | |
| 1184 | + * @param string $uid Name of the user to remove from group | |
| 1185 | + * @param string $gid Name of the group from which remove the user | |
| 1186 | + * @return bool | |
| 1187 | + * @throws \Exception | |
| 1188 | + */ | |
| 1189 | +    public function removeFromGroup($uid, $gid) { | |
| 1190 | +        if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) { | |
| 1191 | +            if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) { | |
| 1192 | + $this->access->connection->clearCache(); | |
| 1193 | + unset($this->cachedGroupMembers[$gid]); | |
| 1194 | + } | |
| 1195 | + return $ret; | |
| 1196 | + } | |
| 1197 | +        throw new \Exception('Could not remove user from group in LDAP backend.'); | |
| 1198 | + } | |
| 1199 | + | |
| 1200 | + /** | |
| 1201 | + * Gets group details | |
| 1202 | + * @param string $gid Name of the group | |
| 1203 | + * @return array | false | |
| 1204 | + * @throws \Exception | |
| 1205 | + */ | |
| 1206 | +    public function getGroupDetails($gid) { | |
| 1207 | +        if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) { | |
| 1208 | + return $this->groupPluginManager->getGroupDetails($gid); | |
| 1209 | + } | |
| 1210 | +        throw new \Exception('Could not get group details in LDAP backend.'); | |
| 1211 | + } | |
| 1212 | + | |
| 1213 | + /** | |
| 1214 | + * Return LDAP connection resource from a cloned connection. | |
| 1215 | + * The cloned connection needs to be closed manually. | |
| 1216 | + * of the current access. | |
| 1217 | + * @param string $gid | |
| 1218 | + * @return resource of the LDAP connection | |
| 1219 | + */ | |
| 1220 | +    public function getNewLDAPConnection($gid) { | |
| 1221 | + $connection = clone $this->access->getConnection(); | |
| 1222 | + return $connection->getConnectionResource(); | |
| 1223 | + } | |
| 1224 | + | |
| 1225 | + /** | |
| 1226 | + * @throws \OC\ServerNotAvailableException | |
| 1227 | + */ | |
| 1228 | +    public function getDisplayName(string $gid): string { | |
| 1229 | +        if ($this->groupPluginManager instanceof IGetDisplayNameBackend) { | |
| 1230 | + return $this->groupPluginManager->getDisplayName($gid); | |
| 1231 | + } | |
| 1232 | + | |
| 1233 | + $cacheKey = 'group_getDisplayName' . $gid; | |
| 1234 | +        if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { | |
| 1235 | + return $displayName; | |
| 1236 | + } | |
| 1237 | + | |
| 1238 | + $displayName = $this->access->readAttribute( | |
| 1239 | + $this->access->groupname2dn($gid), | |
| 1240 | + $this->access->connection->ldapGroupDisplayName); | |
| 1241 | + | |
| 1242 | +        if ($displayName && (count($displayName) > 0)) { | |
| 1243 | + $displayName = $displayName[0]; | |
| 1244 | + $this->access->connection->writeToCache($cacheKey, $displayName); | |
| 1245 | + return $displayName; | |
| 1246 | + } | |
| 1247 | + | |
| 1248 | + return ''; | |
| 1249 | + } | |
| 1250 | 1250 | } | 
| @@ -71,7 +71,7 @@ discard block | ||
| 71 | 71 | parent::__construct($access); | 
| 72 | 72 | $filter = $this->access->connection->ldapGroupFilter; | 
| 73 | 73 | $gassoc = $this->access->connection->ldapGroupMemberAssocAttr; | 
| 74 | -		if(!empty($filter) && !empty($gassoc)) { | |
| 74 | +		if (!empty($filter) && !empty($gassoc)) { | |
| 75 | 75 | $this->enabled = true; | 
| 76 | 76 | } | 
| 77 | 77 | |
| @@ -90,25 +90,25 @@ discard block | ||
| 90 | 90 | * Checks whether the user is member of a group or not. | 
| 91 | 91 | */ | 
| 92 | 92 |  	public function inGroup($uid, $gid) { | 
| 93 | -		if(!$this->enabled) { | |
| 93 | +		if (!$this->enabled) { | |
| 94 | 94 | return false; | 
| 95 | 95 | } | 
| 96 | 96 | $cacheKey = 'inGroup'.$uid.':'.$gid; | 
| 97 | 97 | $inGroup = $this->access->connection->getFromCache($cacheKey); | 
| 98 | -		if(!is_null($inGroup)) { | |
| 99 | - return (bool)$inGroup; | |
| 98 | +		if (!is_null($inGroup)) { | |
| 99 | + return (bool) $inGroup; | |
| 100 | 100 | } | 
| 101 | 101 | |
| 102 | 102 | $userDN = $this->access->username2dn($uid); | 
| 103 | 103 | |
| 104 | -		if(isset($this->cachedGroupMembers[$gid])) { | |
| 104 | +		if (isset($this->cachedGroupMembers[$gid])) { | |
| 105 | 105 | $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]); | 
| 106 | 106 | return $isInGroup; | 
| 107 | 107 | } | 
| 108 | 108 | |
| 109 | 109 | $cacheKeyMembers = 'inGroup-members:'.$gid; | 
| 110 | 110 | $members = $this->access->connection->getFromCache($cacheKeyMembers); | 
| 111 | -		if(!is_null($members)) { | |
| 111 | +		if (!is_null($members)) { | |
| 112 | 112 | $this->cachedGroupMembers[$gid] = $members; | 
| 113 | 113 | $isInGroup = in_array($userDN, $members); | 
| 114 | 114 | $this->access->connection->writeToCache($cacheKey, $isInGroup); | 
| @@ -117,13 +117,13 @@ discard block | ||
| 117 | 117 | |
| 118 | 118 | $groupDN = $this->access->groupname2dn($gid); | 
| 119 | 119 | // just in case | 
| 120 | -		if(!$groupDN || !$userDN) { | |
| 120 | +		if (!$groupDN || !$userDN) { | |
| 121 | 121 | $this->access->connection->writeToCache($cacheKey, false); | 
| 122 | 122 | return false; | 
| 123 | 123 | } | 
| 124 | 124 | |
| 125 | 125 | //check primary group first | 
| 126 | -		if($gid === $this->getUserPrimaryGroup($userDN)) { | |
| 126 | +		if ($gid === $this->getUserPrimaryGroup($userDN)) { | |
| 127 | 127 | $this->access->connection->writeToCache($cacheKey, true); | 
| 128 | 128 | return true; | 
| 129 | 129 | } | 
| @@ -131,21 +131,21 @@ discard block | ||
| 131 | 131 | //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course. | 
| 132 | 132 | $members = $this->_groupMembers($groupDN); | 
| 133 | 133 | $members = array_keys($members); // uids are returned as keys | 
| 134 | -		if(!is_array($members) || count($members) === 0) { | |
| 134 | +		if (!is_array($members) || count($members) === 0) { | |
| 135 | 135 | $this->access->connection->writeToCache($cacheKey, false); | 
| 136 | 136 | return false; | 
| 137 | 137 | } | 
| 138 | 138 | |
| 139 | 139 | //extra work if we don't get back user DNs | 
| 140 | -		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 140 | +		if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 141 | 141 | $dns = array(); | 
| 142 | 142 | $filterParts = array(); | 
| 143 | 143 | $bytes = 0; | 
| 144 | -			foreach($members as $mid) { | |
| 144 | +			foreach ($members as $mid) { | |
| 145 | 145 |  				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter); | 
| 146 | 146 | $filterParts[] = $filter; | 
| 147 | 147 | $bytes += strlen($filter); | 
| 148 | -				if($bytes >= 9000000) { | |
| 148 | +				if ($bytes >= 9000000) { | |
| 149 | 149 | // AD has a default input buffer of 10 MB, we do not want | 
| 150 | 150 | // to take even the chance to exceed it | 
| 151 | 151 | $filter = $this->access->combineFilterWithOr($filterParts); | 
| @@ -155,7 +155,7 @@ discard block | ||
| 155 | 155 | $dns = array_merge($dns, $users); | 
| 156 | 156 | } | 
| 157 | 157 | } | 
| 158 | -			if(count($filterParts) > 0) { | |
| 158 | +			if (count($filterParts) > 0) { | |
| 159 | 159 | $filter = $this->access->combineFilterWithOr($filterParts); | 
| 160 | 160 | $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts)); | 
| 161 | 161 | $dns = array_merge($dns, $users); | 
| @@ -198,14 +198,14 @@ discard block | ||
| 198 | 198 |  			$pos = strpos($memberURLs[0], '('); | 
| 199 | 199 |  			if ($pos !== false) { | 
| 200 | 200 | $memberUrlFilter = substr($memberURLs[0], $pos); | 
| 201 | - $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn'); | |
| 201 | + $foundMembers = $this->access->searchUsers($memberUrlFilter, 'dn'); | |
| 202 | 202 | $dynamicMembers = array(); | 
| 203 | -				foreach($foundMembers as $value) { | |
| 203 | +				foreach ($foundMembers as $value) { | |
| 204 | 204 | $dynamicMembers[$value['dn'][0]] = 1; | 
| 205 | 205 | } | 
| 206 | 206 |  			} else { | 
| 207 | 207 |  				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. | 
| 208 | - 'of group ' . $dnGroup, ILogger::DEBUG); | |
| 208 | + 'of group '.$dnGroup, ILogger::DEBUG); | |
| 209 | 209 | } | 
| 210 | 210 | } | 
| 211 | 211 | return $dynamicMembers; | 
| @@ -229,7 +229,7 @@ discard block | ||
| 229 | 229 | // used extensively in cron job, caching makes sense for nested groups | 
| 230 | 230 | $cacheKey = '_groupMembers'.$dnGroup; | 
| 231 | 231 | $groupMembers = $this->access->connection->getFromCache($cacheKey); | 
| 232 | -		if($groupMembers !== null) { | |
| 232 | +		if ($groupMembers !== null) { | |
| 233 | 233 | return $groupMembers; | 
| 234 | 234 | } | 
| 235 | 235 | $seen[$dnGroup] = 1; | 
| @@ -289,10 +289,10 @@ discard block | ||
| 289 | 289 | $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]); | 
| 290 | 290 | |
| 291 | 291 |  		if ($nesting !== 1) { | 
| 292 | -			if($recordMode) { | |
| 292 | +			if ($recordMode) { | |
| 293 | 293 | // the keys are numeric, but should hold the DN | 
| 294 | -				return array_reduce($list, function ($transformed, $record) use ($dn) { | |
| 295 | -					if($record['dn'][0] != $dn) { | |
| 294 | +				return array_reduce($list, function($transformed, $record) use ($dn) { | |
| 295 | +					if ($record['dn'][0] != $dn) { | |
| 296 | 296 | $transformed[$record['dn'][0]] = $record; | 
| 297 | 297 | } | 
| 298 | 298 | return $transformed; | 
| @@ -323,9 +323,9 @@ discard block | ||
| 323 | 323 | * @return string|bool | 
| 324 | 324 | */ | 
| 325 | 325 |  	public function gidNumber2Name($gid, $dn) { | 
| 326 | - $cacheKey = 'gidNumberToName' . $gid; | |
| 326 | + $cacheKey = 'gidNumberToName'.$gid; | |
| 327 | 327 | $groupName = $this->access->connection->getFromCache($cacheKey); | 
| 328 | -		if(!is_null($groupName) && isset($groupName)) { | |
| 328 | +		if (!is_null($groupName) && isset($groupName)) { | |
| 329 | 329 | return $groupName; | 
| 330 | 330 | } | 
| 331 | 331 | |
| @@ -333,10 +333,10 @@ discard block | ||
| 333 | 333 | $filter = $this->access->combineFilterWithAnd([ | 
| 334 | 334 | $this->access->connection->ldapGroupFilter, | 
| 335 | 335 | 'objectClass=posixGroup', | 
| 336 | - $this->access->connection->ldapGidNumber . '=' . $gid | |
| 336 | + $this->access->connection->ldapGidNumber.'='.$gid | |
| 337 | 337 | ]); | 
| 338 | 338 |  		$result = $this->access->searchGroups($filter, array('dn'), 1); | 
| 339 | -		if(empty($result)) { | |
| 339 | +		if (empty($result)) { | |
| 340 | 340 | return false; | 
| 341 | 341 | } | 
| 342 | 342 | $dn = $result[0]['dn'][0]; | 
| @@ -359,7 +359,7 @@ discard block | ||
| 359 | 359 | */ | 
| 360 | 360 |  	private function getEntryGidNumber($dn, $attribute) { | 
| 361 | 361 | $value = $this->access->readAttribute($dn, $attribute); | 
| 362 | -		if(is_array($value) && !empty($value)) { | |
| 362 | +		if (is_array($value) && !empty($value)) { | |
| 363 | 363 | return $value[0]; | 
| 364 | 364 | } | 
| 365 | 365 | return false; | 
| @@ -381,9 +381,9 @@ discard block | ||
| 381 | 381 | */ | 
| 382 | 382 |  	public function getUserGidNumber($dn) { | 
| 383 | 383 | $gidNumber = false; | 
| 384 | -		if($this->access->connection->hasGidNumber) { | |
| 384 | +		if ($this->access->connection->hasGidNumber) { | |
| 385 | 385 | $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber); | 
| 386 | -			if($gidNumber === false) { | |
| 386 | +			if ($gidNumber === false) { | |
| 387 | 387 | $this->access->connection->hasGidNumber = false; | 
| 388 | 388 | } | 
| 389 | 389 | } | 
| @@ -400,7 +400,7 @@ discard block | ||
| 400 | 400 | */ | 
| 401 | 401 |  	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') { | 
| 402 | 402 | $groupID = $this->getGroupGidNumber($groupDN); | 
| 403 | -		if($groupID === false) { | |
| 403 | +		if ($groupID === false) { | |
| 404 | 404 |  			throw new \Exception('Not a valid group'); | 
| 405 | 405 | } | 
| 406 | 406 | |
| @@ -409,7 +409,7 @@ discard block | ||
| 409 | 409 |  		if ($search !== '') { | 
| 410 | 410 | $filterParts[] = $this->access->getFilterPartForUserSearch($search); | 
| 411 | 411 | } | 
| 412 | - $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID; | |
| 412 | + $filterParts[] = $this->access->connection->ldapGidNumber.'='.$groupID; | |
| 413 | 413 | |
| 414 | 414 | return $this->access->combineFilterWithAnd($filterParts); | 
| 415 | 415 | } | 
| @@ -451,7 +451,7 @@ discard block | ||
| 451 | 451 |  		try { | 
| 452 | 452 | $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search); | 
| 453 | 453 | $users = $this->access->countUsers($filter, ['dn'], $limit, $offset); | 
| 454 | - return (int)$users; | |
| 454 | + return (int) $users; | |
| 455 | 455 |  		} catch (\Exception $e) { | 
| 456 | 456 | return 0; | 
| 457 | 457 | } | 
| @@ -464,9 +464,9 @@ discard block | ||
| 464 | 464 | */ | 
| 465 | 465 |  	public function getUserGroupByGid($dn) { | 
| 466 | 466 | $groupID = $this->getUserGidNumber($dn); | 
| 467 | -		if($groupID !== false) { | |
| 467 | +		if ($groupID !== false) { | |
| 468 | 468 | $groupName = $this->gidNumber2Name($groupID, $dn); | 
| 469 | -			if($groupName !== false) { | |
| 469 | +			if ($groupName !== false) { | |
| 470 | 470 | return $groupName; | 
| 471 | 471 | } | 
| 472 | 472 | } | 
| @@ -483,22 +483,22 @@ discard block | ||
| 483 | 483 |  	public function primaryGroupID2Name($gid, $dn) { | 
| 484 | 484 | $cacheKey = 'primaryGroupIDtoName'; | 
| 485 | 485 | $groupNames = $this->access->connection->getFromCache($cacheKey); | 
| 486 | -		if(!is_null($groupNames) && isset($groupNames[$gid])) { | |
| 486 | +		if (!is_null($groupNames) && isset($groupNames[$gid])) { | |
| 487 | 487 | return $groupNames[$gid]; | 
| 488 | 488 | } | 
| 489 | 489 | |
| 490 | 490 | $domainObjectSid = $this->access->getSID($dn); | 
| 491 | -		if($domainObjectSid === false) { | |
| 491 | +		if ($domainObjectSid === false) { | |
| 492 | 492 | return false; | 
| 493 | 493 | } | 
| 494 | 494 | |
| 495 | 495 | //we need to get the DN from LDAP | 
| 496 | 496 | $filter = $this->access->combineFilterWithAnd(array( | 
| 497 | 497 | $this->access->connection->ldapGroupFilter, | 
| 498 | - 'objectsid=' . $domainObjectSid . '-' . $gid | |
| 498 | + 'objectsid='.$domainObjectSid.'-'.$gid | |
| 499 | 499 | )); | 
| 500 | 500 |  		$result = $this->access->searchGroups($filter, array('dn'), 1); | 
| 501 | -		if(empty($result)) { | |
| 501 | +		if (empty($result)) { | |
| 502 | 502 | return false; | 
| 503 | 503 | } | 
| 504 | 504 | $dn = $result[0]['dn'][0]; | 
| @@ -521,7 +521,7 @@ discard block | ||
| 521 | 521 | */ | 
| 522 | 522 |  	private function getEntryGroupID($dn, $attribute) { | 
| 523 | 523 | $value = $this->access->readAttribute($dn, $attribute); | 
| 524 | -		if(is_array($value) && !empty($value)) { | |
| 524 | +		if (is_array($value) && !empty($value)) { | |
| 525 | 525 | return $value[0]; | 
| 526 | 526 | } | 
| 527 | 527 | return false; | 
| @@ -543,9 +543,9 @@ discard block | ||
| 543 | 543 | */ | 
| 544 | 544 |  	public function getUserPrimaryGroupIDs($dn) { | 
| 545 | 545 | $primaryGroupID = false; | 
| 546 | -		if($this->access->connection->hasPrimaryGroups) { | |
| 546 | +		if ($this->access->connection->hasPrimaryGroups) { | |
| 547 | 547 | $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID'); | 
| 548 | -			if($primaryGroupID === false) { | |
| 548 | +			if ($primaryGroupID === false) { | |
| 549 | 549 | $this->access->connection->hasPrimaryGroups = false; | 
| 550 | 550 | } | 
| 551 | 551 | } | 
| @@ -562,7 +562,7 @@ discard block | ||
| 562 | 562 | */ | 
| 563 | 563 |  	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') { | 
| 564 | 564 | $groupID = $this->getGroupPrimaryGroupID($groupDN); | 
| 565 | -		if($groupID === false) { | |
| 565 | +		if ($groupID === false) { | |
| 566 | 566 |  			throw new \Exception('Not a valid group'); | 
| 567 | 567 | } | 
| 568 | 568 | |
| @@ -571,7 +571,7 @@ discard block | ||
| 571 | 571 |  		if ($search !== '') { | 
| 572 | 572 | $filterParts[] = $this->access->getFilterPartForUserSearch($search); | 
| 573 | 573 | } | 
| 574 | - $filterParts[] = 'primaryGroupID=' . $groupID; | |
| 574 | + $filterParts[] = 'primaryGroupID='.$groupID; | |
| 575 | 575 | |
| 576 | 576 | return $this->access->combineFilterWithAnd($filterParts); | 
| 577 | 577 | } | 
| @@ -613,7 +613,7 @@ discard block | ||
| 613 | 613 |  		try { | 
| 614 | 614 | $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search); | 
| 615 | 615 |  			$users = $this->access->countUsers($filter, array('dn'), $limit, $offset); | 
| 616 | - return (int)$users; | |
| 616 | + return (int) $users; | |
| 617 | 617 |  		} catch (\Exception $e) { | 
| 618 | 618 | return 0; | 
| 619 | 619 | } | 
| @@ -626,9 +626,9 @@ discard block | ||
| 626 | 626 | */ | 
| 627 | 627 |  	public function getUserPrimaryGroup($dn) { | 
| 628 | 628 | $groupID = $this->getUserPrimaryGroupIDs($dn); | 
| 629 | -		if($groupID !== false) { | |
| 629 | +		if ($groupID !== false) { | |
| 630 | 630 | $groupName = $this->primaryGroupID2Name($groupID, $dn); | 
| 631 | -			if($groupName !== false) { | |
| 631 | +			if ($groupName !== false) { | |
| 632 | 632 | return $groupName; | 
| 633 | 633 | } | 
| 634 | 634 | } | 
| @@ -647,16 +647,16 @@ discard block | ||
| 647 | 647 | * This function includes groups based on dynamic group membership. | 
| 648 | 648 | */ | 
| 649 | 649 |  	public function getUserGroups($uid) { | 
| 650 | -		if(!$this->enabled) { | |
| 650 | +		if (!$this->enabled) { | |
| 651 | 651 | return array(); | 
| 652 | 652 | } | 
| 653 | 653 | $cacheKey = 'getUserGroups'.$uid; | 
| 654 | 654 | $userGroups = $this->access->connection->getFromCache($cacheKey); | 
| 655 | -		if(!is_null($userGroups)) { | |
| 655 | +		if (!is_null($userGroups)) { | |
| 656 | 656 | return $userGroups; | 
| 657 | 657 | } | 
| 658 | 658 | $userDN = $this->access->username2dn($uid); | 
| 659 | -		if(!$userDN) { | |
| 659 | +		if (!$userDN) { | |
| 660 | 660 | $this->access->connection->writeToCache($cacheKey, array()); | 
| 661 | 661 | return array(); | 
| 662 | 662 | } | 
| @@ -670,14 +670,14 @@ discard block | ||
| 670 | 670 |  		if (!empty($dynamicGroupMemberURL)) { | 
| 671 | 671 | // look through dynamic groups to add them to the result array if needed | 
| 672 | 672 | $groupsToMatch = $this->access->fetchListOfGroups( | 
| 673 | -				$this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL)); | |
| 674 | -			foreach($groupsToMatch as $dynamicGroup) { | |
| 673 | +				$this->access->connection->ldapGroupFilter, array('dn', $dynamicGroupMemberURL)); | |
| 674 | +			foreach ($groupsToMatch as $dynamicGroup) { | |
| 675 | 675 |  				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) { | 
| 676 | 676 | continue; | 
| 677 | 677 | } | 
| 678 | 678 |  				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '('); | 
| 679 | 679 |  				if ($pos !== false) { | 
| 680 | - $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos); | |
| 680 | + $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos); | |
| 681 | 681 | // apply filter via ldap search to see if this user is in this | 
| 682 | 682 | // dynamic group | 
| 683 | 683 | $userMatch = $this->access->readAttribute( | 
| @@ -688,7 +688,7 @@ discard block | ||
| 688 | 688 |  					if ($userMatch !== false) { | 
| 689 | 689 | // match found so this user is in this group | 
| 690 | 690 | $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]); | 
| 691 | -						if(is_string($groupName)) { | |
| 691 | +						if (is_string($groupName)) { | |
| 692 | 692 | // be sure to never return false if the dn could not be | 
| 693 | 693 | // resolved to a name, for whatever reason. | 
| 694 | 694 | $groups[] = $groupName; | 
| @@ -696,7 +696,7 @@ discard block | ||
| 696 | 696 | } | 
| 697 | 697 |  				} else { | 
| 698 | 698 |  					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '. | 
| 699 | - 'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG); | |
| 699 | + 'of group '.print_r($dynamicGroup, true), ILogger::DEBUG); | |
| 700 | 700 | } | 
| 701 | 701 | } | 
| 702 | 702 | } | 
| @@ -704,15 +704,15 @@ discard block | ||
| 704 | 704 | // if possible, read out membership via memberOf. It's far faster than | 
| 705 | 705 | // performing a search, which still is a fallback later. | 
| 706 | 706 | // memberof doesn't support memberuid, so skip it here. | 
| 707 | - if((int)$this->access->connection->hasMemberOfFilterSupport === 1 | |
| 708 | - && (int)$this->access->connection->useMemberOfToDetectMembership === 1 | |
| 707 | + if ((int) $this->access->connection->hasMemberOfFilterSupport === 1 | |
| 708 | + && (int) $this->access->connection->useMemberOfToDetectMembership === 1 | |
| 709 | 709 | && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid' | 
| 710 | 710 |  		    ) { | 
| 711 | 711 | $groupDNs = $this->_getGroupDNsFromMemberOf($userDN); | 
| 712 | 712 |  			if (is_array($groupDNs)) { | 
| 713 | 713 |  				foreach ($groupDNs as $dn) { | 
| 714 | 714 | $groupName = $this->access->dn2groupname($dn); | 
| 715 | -					if(is_string($groupName)) { | |
| 715 | +					if (is_string($groupName)) { | |
| 716 | 716 | // be sure to never return false if the dn could not be | 
| 717 | 717 | // resolved to a name, for whatever reason. | 
| 718 | 718 | $groups[] = $groupName; | 
| @@ -720,10 +720,10 @@ discard block | ||
| 720 | 720 | } | 
| 721 | 721 | } | 
| 722 | 722 | |
| 723 | -			if($primaryGroup !== false) { | |
| 723 | +			if ($primaryGroup !== false) { | |
| 724 | 724 | $groups[] = $primaryGroup; | 
| 725 | 725 | } | 
| 726 | -			if($gidGroupName !== false) { | |
| 726 | +			if ($gidGroupName !== false) { | |
| 727 | 727 | $groups[] = $gidGroupName; | 
| 728 | 728 | } | 
| 729 | 729 | $this->access->connection->writeToCache($cacheKey, $groups); | 
| @@ -731,14 +731,14 @@ discard block | ||
| 731 | 731 | } | 
| 732 | 732 | |
| 733 | 733 | //uniqueMember takes DN, memberuid the uid, so we need to distinguish | 
| 734 | - if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') | |
| 734 | + if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember') | |
| 735 | 735 | || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member') | 
| 736 | 736 |  		) { | 
| 737 | 737 | $uid = $userDN; | 
| 738 | -		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 738 | +		} else if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') { | |
| 739 | 739 | $result = $this->access->readAttribute($userDN, 'uid'); | 
| 740 | 740 |  			if ($result === false) { | 
| 741 | -				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '. | |
| 741 | +				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN '.$userDN.' on '. | |
| 742 | 742 | $this->access->connection->ldapHost, ILogger::DEBUG); | 
| 743 | 743 | } | 
| 744 | 744 | $uid = $result[0]; | 
| @@ -747,7 +747,7 @@ discard block | ||
| 747 | 747 | $uid = $userDN; | 
| 748 | 748 | } | 
| 749 | 749 | |
| 750 | -		if(isset($this->cachedGroupsByMember[$uid])) { | |
| 750 | +		if (isset($this->cachedGroupsByMember[$uid])) { | |
| 751 | 751 | $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]); | 
| 752 | 752 |  		} else { | 
| 753 | 753 | $groupsByMember = array_values($this->getGroupsByMember($uid)); | 
| @@ -756,10 +756,10 @@ discard block | ||
| 756 | 756 | $groups = array_merge($groups, $groupsByMember); | 
| 757 | 757 | } | 
| 758 | 758 | |
| 759 | -		if($primaryGroup !== false) { | |
| 759 | +		if ($primaryGroup !== false) { | |
| 760 | 760 | $groups[] = $primaryGroup; | 
| 761 | 761 | } | 
| 762 | -		if($gidGroupName !== false) { | |
| 762 | +		if ($gidGroupName !== false) { | |
| 763 | 763 | $groups[] = $gidGroupName; | 
| 764 | 764 | } | 
| 765 | 765 | |
| @@ -788,8 +788,8 @@ discard block | ||
| 788 | 788 | $groups = $this->access->fetchListOfGroups($filter, | 
| 789 | 789 | [$this->access->connection->ldapGroupDisplayName, 'dn']); | 
| 790 | 790 |  		if (is_array($groups)) { | 
| 791 | -			$fetcher = function ($dn, &$seen) { | |
| 792 | -				if(is_array($dn) && isset($dn['dn'][0])) { | |
| 791 | +			$fetcher = function($dn, &$seen) { | |
| 792 | +				if (is_array($dn) && isset($dn['dn'][0])) { | |
| 793 | 793 | $dn = $dn['dn'][0]; | 
| 794 | 794 | } | 
| 795 | 795 | return $this->getGroupsByMember($dn, $seen); | 
| @@ -810,33 +810,33 @@ discard block | ||
| 810 | 810 | * @return array with user ids | 
| 811 | 811 | */ | 
| 812 | 812 |  	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { | 
| 813 | -		if(!$this->enabled) { | |
| 813 | +		if (!$this->enabled) { | |
| 814 | 814 | return array(); | 
| 815 | 815 | } | 
| 816 | -		if(!$this->groupExists($gid)) { | |
| 816 | +		if (!$this->groupExists($gid)) { | |
| 817 | 817 | return array(); | 
| 818 | 818 | } | 
| 819 | 819 | $search = $this->access->escapeFilterPart($search, true); | 
| 820 | 820 | $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset; | 
| 821 | 821 | // check for cache of the exact query | 
| 822 | 822 | $groupUsers = $this->access->connection->getFromCache($cacheKey); | 
| 823 | -		if(!is_null($groupUsers)) { | |
| 823 | +		if (!is_null($groupUsers)) { | |
| 824 | 824 | return $groupUsers; | 
| 825 | 825 | } | 
| 826 | 826 | |
| 827 | 827 | // check for cache of the query without limit and offset | 
| 828 | 828 |  		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search); | 
| 829 | -		if(!is_null($groupUsers)) { | |
| 829 | +		if (!is_null($groupUsers)) { | |
| 830 | 830 | $groupUsers = array_slice($groupUsers, $offset, $limit); | 
| 831 | 831 | $this->access->connection->writeToCache($cacheKey, $groupUsers); | 
| 832 | 832 | return $groupUsers; | 
| 833 | 833 | } | 
| 834 | 834 | |
| 835 | -		if($limit === -1) { | |
| 835 | +		if ($limit === -1) { | |
| 836 | 836 | $limit = null; | 
| 837 | 837 | } | 
| 838 | 838 | $groupDN = $this->access->groupname2dn($gid); | 
| 839 | -		if(!$groupDN) { | |
| 839 | +		if (!$groupDN) { | |
| 840 | 840 | // group couldn't be found, return empty resultset | 
| 841 | 841 | $this->access->connection->writeToCache($cacheKey, array()); | 
| 842 | 842 | return array(); | 
| @@ -845,7 +845,7 @@ discard block | ||
| 845 | 845 | $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset); | 
| 846 | 846 | $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset); | 
| 847 | 847 | $members = $this->_groupMembers($groupDN); | 
| 848 | -		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) { | |
| 848 | +		if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) { | |
| 849 | 849 | //in case users could not be retrieved, return empty result set | 
| 850 | 850 | $this->access->connection->writeToCache($cacheKey, []); | 
| 851 | 851 | return []; | 
| @@ -854,29 +854,29 @@ discard block | ||
| 854 | 854 | $groupUsers = array(); | 
| 855 | 855 | $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid'); | 
| 856 | 856 | $attrs = $this->access->userManager->getAttributes(true); | 
| 857 | -		foreach($members as $member) { | |
| 858 | -			if($isMemberUid) { | |
| 857 | +		foreach ($members as $member) { | |
| 858 | +			if ($isMemberUid) { | |
| 859 | 859 | //we got uids, need to get their DNs to 'translate' them to user names | 
| 860 | 860 | $filter = $this->access->combineFilterWithAnd(array( | 
| 861 | 861 |  					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter), | 
| 862 | 862 | $this->access->getFilterPartForUserSearch($search) | 
| 863 | 863 | )); | 
| 864 | 864 | $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1); | 
| 865 | -				if(count($ldap_users) < 1) { | |
| 865 | +				if (count($ldap_users) < 1) { | |
| 866 | 866 | continue; | 
| 867 | 867 | } | 
| 868 | 868 | $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]); | 
| 869 | 869 |  			} else { | 
| 870 | 870 | //we got DNs, check if we need to filter by search or we can give back all of them | 
| 871 | 871 |  				if ($search !== '') { | 
| 872 | - if(!$this->access->readAttribute($member, | |
| 872 | + if (!$this->access->readAttribute($member, | |
| 873 | 873 | $this->access->connection->ldapUserDisplayName, | 
| 874 | 874 |  						$this->access->getFilterPartForUserSearch($search))) { | 
| 875 | 875 | continue; | 
| 876 | 876 | } | 
| 877 | 877 | } | 
| 878 | 878 | // dn2username will also check if the users belong to the allowed base | 
| 879 | -				if($ocname = $this->access->dn2username($member)) { | |
| 879 | +				if ($ocname = $this->access->dn2username($member)) { | |
| 880 | 880 | $groupUsers[] = $ocname; | 
| 881 | 881 | } | 
| 882 | 882 | } | 
| @@ -904,16 +904,16 @@ discard block | ||
| 904 | 904 | } | 
| 905 | 905 | |
| 906 | 906 | $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search; | 
| 907 | -		if(!$this->enabled || !$this->groupExists($gid)) { | |
| 907 | +		if (!$this->enabled || !$this->groupExists($gid)) { | |
| 908 | 908 | return false; | 
| 909 | 909 | } | 
| 910 | 910 | $groupUsers = $this->access->connection->getFromCache($cacheKey); | 
| 911 | -		if(!is_null($groupUsers)) { | |
| 911 | +		if (!is_null($groupUsers)) { | |
| 912 | 912 | return $groupUsers; | 
| 913 | 913 | } | 
| 914 | 914 | |
| 915 | 915 | $groupDN = $this->access->groupname2dn($gid); | 
| 916 | -		if(!$groupDN) { | |
| 916 | +		if (!$groupDN) { | |
| 917 | 917 | // group couldn't be found, return empty result set | 
| 918 | 918 | $this->access->connection->writeToCache($cacheKey, false); | 
| 919 | 919 | return false; | 
| @@ -921,7 +921,7 @@ discard block | ||
| 921 | 921 | |
| 922 | 922 | $members = $this->_groupMembers($groupDN); | 
| 923 | 923 | $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, ''); | 
| 924 | -		if(!$members && $primaryUserCount === 0) { | |
| 924 | +		if (!$members && $primaryUserCount === 0) { | |
| 925 | 925 | //in case users could not be retrieved, return empty result set | 
| 926 | 926 | $this->access->connection->writeToCache($cacheKey, false); | 
| 927 | 927 | return false; | 
| @@ -946,27 +946,27 @@ discard block | ||
| 946 | 946 | //For now this is not important, because the only use of this method | 
| 947 | 947 | //does not supply a search string | 
| 948 | 948 | $groupUsers = array(); | 
| 949 | -		foreach($members as $member) { | |
| 950 | -			if($isMemberUid) { | |
| 949 | +		foreach ($members as $member) { | |
| 950 | +			if ($isMemberUid) { | |
| 951 | 951 | //we got uids, need to get their DNs to 'translate' them to user names | 
| 952 | 952 | $filter = $this->access->combineFilterWithAnd(array( | 
| 953 | 953 |  					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter), | 
| 954 | 954 | $this->access->getFilterPartForUserSearch($search) | 
| 955 | 955 | )); | 
| 956 | 956 | $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1); | 
| 957 | -				if(count($ldap_users) < 1) { | |
| 957 | +				if (count($ldap_users) < 1) { | |
| 958 | 958 | continue; | 
| 959 | 959 | } | 
| 960 | 960 | $groupUsers[] = $this->access->dn2username($ldap_users[0]); | 
| 961 | 961 |  			} else { | 
| 962 | 962 | //we need to apply the search filter now | 
| 963 | - if(!$this->access->readAttribute($member, | |
| 963 | + if (!$this->access->readAttribute($member, | |
| 964 | 964 | $this->access->connection->ldapUserDisplayName, | 
| 965 | 965 |  					$this->access->getFilterPartForUserSearch($search))) { | 
| 966 | 966 | continue; | 
| 967 | 967 | } | 
| 968 | 968 | // dn2username will also check if the users belong to the allowed base | 
| 969 | -				if($ocname = $this->access->dn2username($member)) { | |
| 969 | +				if ($ocname = $this->access->dn2username($member)) { | |
| 970 | 970 | $groupUsers[] = $ocname; | 
| 971 | 971 | } | 
| 972 | 972 | } | 
| @@ -989,7 +989,7 @@ discard block | ||
| 989 | 989 | * Returns a list with all groups (used by getGroups) | 
| 990 | 990 | */ | 
| 991 | 991 |  	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) { | 
| 992 | -		if(!$this->enabled) { | |
| 992 | +		if (!$this->enabled) { | |
| 993 | 993 | return array(); | 
| 994 | 994 | } | 
| 995 | 995 | $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset; | 
| @@ -997,13 +997,13 @@ discard block | ||
| 997 | 997 | //Check cache before driving unnecessary searches | 
| 998 | 998 |  		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG); | 
| 999 | 999 | $ldap_groups = $this->access->connection->getFromCache($cacheKey); | 
| 1000 | -		if(!is_null($ldap_groups)) { | |
| 1000 | +		if (!is_null($ldap_groups)) { | |
| 1001 | 1001 | return $ldap_groups; | 
| 1002 | 1002 | } | 
| 1003 | 1003 | |
| 1004 | 1004 | // if we'd pass -1 to LDAP search, we'd end up in a Protocol | 
| 1005 | 1005 | // error. With a limit of 0, we get 0 results. So we pass null. | 
| 1006 | -		if($limit <= 0) { | |
| 1006 | +		if ($limit <= 0) { | |
| 1007 | 1007 | $limit = null; | 
| 1008 | 1008 | } | 
| 1009 | 1009 | $filter = $this->access->combineFilterWithAnd(array( | 
| @@ -1035,11 +1035,11 @@ discard block | ||
| 1035 | 1035 | * (active directory has a limit of 1000 by default) | 
| 1036 | 1036 | */ | 
| 1037 | 1037 |  	public function getGroups($search = '', $limit = -1, $offset = 0) { | 
| 1038 | -		if(!$this->enabled) { | |
| 1038 | +		if (!$this->enabled) { | |
| 1039 | 1039 | return array(); | 
| 1040 | 1040 | } | 
| 1041 | 1041 | $search = $this->access->escapeFilterPart($search, true); | 
| 1042 | - $pagingSize = (int)$this->access->connection->ldapPagingSize; | |
| 1042 | + $pagingSize = (int) $this->access->connection->ldapPagingSize; | |
| 1043 | 1043 |  		if ($pagingSize <= 0) { | 
| 1044 | 1044 | return $this->getGroupsChunk($search, $limit, $offset); | 
| 1045 | 1045 | } | 
| @@ -1082,20 +1082,20 @@ discard block | ||
| 1082 | 1082 | */ | 
| 1083 | 1083 |  	public function groupExists($gid) { | 
| 1084 | 1084 |  		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid); | 
| 1085 | -		if(!is_null($groupExists)) { | |
| 1086 | - return (bool)$groupExists; | |
| 1085 | +		if (!is_null($groupExists)) { | |
| 1086 | + return (bool) $groupExists; | |
| 1087 | 1087 | } | 
| 1088 | 1088 | |
| 1089 | 1089 | //getting dn, if false the group does not exist. If dn, it may be mapped | 
| 1090 | 1090 | //only, requires more checking. | 
| 1091 | 1091 | $dn = $this->access->groupname2dn($gid); | 
| 1092 | -		if(!$dn) { | |
| 1092 | +		if (!$dn) { | |
| 1093 | 1093 |  			$this->access->connection->writeToCache('groupExists'.$gid, false); | 
| 1094 | 1094 | return false; | 
| 1095 | 1095 | } | 
| 1096 | 1096 | |
| 1097 | 1097 | //if group really still exists, we will be able to read its objectclass | 
| 1098 | -		if(!is_array($this->access->readAttribute($dn, ''))) { | |
| 1098 | +		if (!is_array($this->access->readAttribute($dn, ''))) { | |
| 1099 | 1099 |  			$this->access->connection->writeToCache('groupExists'.$gid, false); | 
| 1100 | 1100 | return false; | 
| 1101 | 1101 | } | 
| @@ -1113,7 +1113,7 @@ discard block | ||
| 1113 | 1113 | * compared with GroupInterface::CREATE_GROUP etc. | 
| 1114 | 1114 | */ | 
| 1115 | 1115 |  	public function implementsActions($actions) { | 
| 1116 | - return (bool)((GroupInterface::COUNT_USERS | | |
| 1116 | + return (bool) ((GroupInterface::COUNT_USERS | | |
| 1117 | 1117 | $this->groupPluginManager->getImplementedActions()) & $actions); | 
| 1118 | 1118 | } | 
| 1119 | 1119 | |
| @@ -1230,7 +1230,7 @@ discard block | ||
| 1230 | 1230 | return $this->groupPluginManager->getDisplayName($gid); | 
| 1231 | 1231 | } | 
| 1232 | 1232 | |
| 1233 | - $cacheKey = 'group_getDisplayName' . $gid; | |
| 1233 | + $cacheKey = 'group_getDisplayName'.$gid; | |
| 1234 | 1234 |  		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) { | 
| 1235 | 1235 | return $displayName; | 
| 1236 | 1236 | } | 
| @@ -30,23 +30,23 @@ | ||
| 30 | 30 | $limit = null; | 
| 31 | 31 | $offset = null; | 
| 32 | 32 |  if (isset($_GET['pattern'])) { | 
| 33 | - $pattern = (string)$_GET['pattern']; | |
| 33 | + $pattern = (string)$_GET['pattern']; | |
| 34 | 34 | } | 
| 35 | 35 |  if (isset($_GET['limit'])) { | 
| 36 | - $limit = (int)$_GET['limit']; | |
| 36 | + $limit = (int)$_GET['limit']; | |
| 37 | 37 | } | 
| 38 | 38 |  if (isset($_GET['offset'])) { | 
| 39 | - $offset = (int)$_GET['offset']; | |
| 39 | + $offset = (int)$_GET['offset']; | |
| 40 | 40 | } | 
| 41 | 41 | |
| 42 | 42 | $groups = []; | 
| 43 | 43 |  foreach (\OC::$server->getGroupManager()->search($pattern, $limit, $offset) as $group) { | 
| 44 | - $groups[$group->getGID()] = $group->getDisplayName(); | |
| 44 | + $groups[$group->getGID()] = $group->getDisplayName(); | |
| 45 | 45 | } | 
| 46 | 46 | |
| 47 | 47 | $users = []; | 
| 48 | 48 |  foreach (\OC::$server->getUserManager()->searchDisplayName($pattern, $limit, $offset) as $user) { | 
| 49 | - $users[$user->getUID()] = $user->getDisplayName(); | |
| 49 | + $users[$user->getUID()] = $user->getDisplayName(); | |
| 50 | 50 | } | 
| 51 | 51 | |
| 52 | 52 |  $results = array('groups' => $groups, 'users' => $users); |