Passed
Push — master ( 72fda1...adc4f1 )
by Roeland
18:06 queued 05:03
created
apps/files_sharing/lib/SharedStorage.php 1 patch
Indentation   +464 added lines, -464 removed lines patch added patch discarded remove patch
@@ -50,468 +50,468 @@
 block discarded – undo
50 50
  */
51 51
 class SharedStorage extends \OC\Files\Storage\Wrapper\Jail implements ISharedStorage, IDisableEncryptionStorage {
52 52
 
53
-	/** @var \OCP\Share\IShare */
54
-	private $superShare;
55
-
56
-	/** @var \OCP\Share\IShare[] */
57
-	private $groupedShares;
58
-
59
-	/**
60
-	 * @var \OC\Files\View
61
-	 */
62
-	private $ownerView;
63
-
64
-	private $initialized = false;
65
-
66
-	/**
67
-	 * @var ICacheEntry
68
-	 */
69
-	private $sourceRootInfo;
70
-
71
-	/** @var string */
72
-	private $user;
73
-
74
-	/**
75
-	 * @var \OCP\ILogger
76
-	 */
77
-	private $logger;
78
-
79
-	/** @var  IStorage */
80
-	private $nonMaskedStorage;
81
-
82
-	private $options;
83
-
84
-	/** @var boolean */
85
-	private $sharingDisabledForUser;
86
-
87
-	public function __construct($arguments) {
88
-		$this->ownerView = $arguments['ownerView'];
89
-		$this->logger = \OC::$server->getLogger();
90
-
91
-		$this->superShare = $arguments['superShare'];
92
-		$this->groupedShares = $arguments['groupedShares'];
93
-
94
-		$this->user = $arguments['user'];
95
-		if (isset($arguments['sharingDisabledForUser'])) {
96
-			$this->sharingDisabledForUser = $arguments['sharingDisabledForUser'];
97
-		} else {
98
-			$this->sharingDisabledForUser = false;
99
-		}
100
-
101
-		parent::__construct([
102
-			'storage' => null,
103
-			'root' => null,
104
-		]);
105
-	}
106
-
107
-	/**
108
-	 * @return ICacheEntry
109
-	 */
110
-	private function getSourceRootInfo() {
111
-		if (is_null($this->sourceRootInfo)) {
112
-			if (is_null($this->superShare->getNodeCacheEntry())) {
113
-				$this->init();
114
-				$this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
115
-			} else {
116
-				$this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
117
-			}
118
-		}
119
-		return $this->sourceRootInfo;
120
-	}
121
-
122
-	private function init() {
123
-		if ($this->initialized) {
124
-			return;
125
-		}
126
-		$this->initialized = true;
127
-		try {
128
-			Filesystem::initMountPoints($this->superShare->getShareOwner());
129
-			$storageId = $this->superShare->getNodeCacheEntry() ? $this->superShare->getNodeCacheEntry()->getStorageId() : null;
130
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId(), $storageId);
131
-			[$this->nonMaskedStorage, $this->rootPath] = $this->ownerView->resolvePath($sourcePath);
132
-			$this->storage = new PermissionsMask([
133
-				'storage' => $this->nonMaskedStorage,
134
-				'mask' => $this->superShare->getPermissions(),
135
-			]);
136
-		} catch (NotFoundException $e) {
137
-			// original file not accessible or deleted, set FailedStorage
138
-			$this->storage = new FailedStorage(['exception' => $e]);
139
-			$this->cache = new FailedCache();
140
-			$this->rootPath = '';
141
-		} catch (NoUserException $e) {
142
-			// sharer user deleted, set FailedStorage
143
-			$this->storage = new FailedStorage(['exception' => $e]);
144
-			$this->cache = new FailedCache();
145
-			$this->rootPath = '';
146
-		} catch (\Exception $e) {
147
-			$this->storage = new FailedStorage(['exception' => $e]);
148
-			$this->cache = new FailedCache();
149
-			$this->rootPath = '';
150
-			$this->logger->logException($e);
151
-		}
152
-
153
-		if (!$this->nonMaskedStorage) {
154
-			$this->nonMaskedStorage = $this->storage;
155
-		}
156
-	}
157
-
158
-	/**
159
-	 * @inheritdoc
160
-	 */
161
-	public function instanceOfStorage($class) {
162
-		if ($class === '\OC\Files\Storage\Common') {
163
-			return true;
164
-		}
165
-		if (in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage', '\OCP\Files\IHomeStorage'])) {
166
-			return false;
167
-		}
168
-		return parent::instanceOfStorage($class);
169
-	}
170
-
171
-	/**
172
-	 * @return string
173
-	 */
174
-	public function getShareId() {
175
-		return $this->superShare->getId();
176
-	}
177
-
178
-	private function isValid() {
179
-		return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
180
-	}
181
-
182
-	/**
183
-	 * get id of the mount point
184
-	 *
185
-	 * @return string
186
-	 */
187
-	public function getId() {
188
-		return 'shared::' . $this->getMountPoint();
189
-	}
190
-
191
-	/**
192
-	 * Get the permissions granted for a shared file
193
-	 *
194
-	 * @param string $target Shared target file path
195
-	 * @return int CRUDS permissions granted
196
-	 */
197
-	public function getPermissions($target = '') {
198
-		if (!$this->isValid()) {
199
-			return 0;
200
-		}
201
-		$permissions = parent::getPermissions($target) & $this->superShare->getPermissions();
202
-
203
-		// part files and the mount point always have delete permissions
204
-		if ($target === '' || pathinfo($target, PATHINFO_EXTENSION) === 'part') {
205
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
206
-		}
207
-
208
-		if ($this->sharingDisabledForUser) {
209
-			$permissions &= ~\OCP\Constants::PERMISSION_SHARE;
210
-		}
211
-
212
-		return $permissions;
213
-	}
214
-
215
-	public function isCreatable($path) {
216
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
217
-	}
218
-
219
-	public function isReadable($path) {
220
-		if (!$this->isValid()) {
221
-			return false;
222
-		}
223
-		if (!$this->file_exists($path)) {
224
-			return false;
225
-		}
226
-		/** @var IStorage $storage */
227
-		/** @var string $internalPath */
228
-		[$storage, $internalPath] = $this->resolvePath($path);
229
-		return $storage->isReadable($internalPath);
230
-	}
231
-
232
-	public function isUpdatable($path) {
233
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
234
-	}
235
-
236
-	public function isDeletable($path) {
237
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
238
-	}
239
-
240
-	public function isSharable($path) {
241
-		if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
242
-			return false;
243
-		}
244
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
245
-	}
246
-
247
-	public function fopen($path, $mode) {
248
-		$source = $this->getUnjailedPath($path);
249
-		switch ($mode) {
250
-			case 'r+':
251
-			case 'rb+':
252
-			case 'w+':
253
-			case 'wb+':
254
-			case 'x+':
255
-			case 'xb+':
256
-			case 'a+':
257
-			case 'ab+':
258
-			case 'w':
259
-			case 'wb':
260
-			case 'x':
261
-			case 'xb':
262
-			case 'a':
263
-			case 'ab':
264
-				$creatable = $this->isCreatable(dirname($path));
265
-				$updatable = $this->isUpdatable($path);
266
-				// if neither permissions given, no need to continue
267
-				if (!$creatable && !$updatable) {
268
-					if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
269
-						$updatable = $this->isUpdatable(dirname($path));
270
-					}
271
-
272
-					if (!$updatable) {
273
-						return false;
274
-					}
275
-				}
276
-
277
-				$exists = $this->file_exists($path);
278
-				// if a file exists, updatable permissions are required
279
-				if ($exists && !$updatable) {
280
-					return false;
281
-				}
282
-
283
-				// part file is allowed if !$creatable but the final file is $updatable
284
-				if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
285
-					if (!$exists && !$creatable) {
286
-						return false;
287
-					}
288
-				}
289
-		}
290
-		$info = [
291
-			'target' => $this->getMountPoint() . '/' . $path,
292
-			'source' => $source,
293
-			'mode' => $mode,
294
-		];
295
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
296
-		return $this->nonMaskedStorage->fopen($this->getUnjailedPath($path), $mode);
297
-	}
298
-
299
-	/**
300
-	 * see https://www.php.net/manual/en/function.rename.php
301
-	 *
302
-	 * @param string $path1
303
-	 * @param string $path2
304
-	 * @return bool
305
-	 */
306
-	public function rename($path1, $path2) {
307
-		$this->init();
308
-		$isPartFile = pathinfo($path1, PATHINFO_EXTENSION) === 'part';
309
-		$targetExists = $this->file_exists($path2);
310
-		$sameFolder = dirname($path1) === dirname($path2);
311
-
312
-		if ($targetExists || ($sameFolder && !$isPartFile)) {
313
-			if (!$this->isUpdatable('')) {
314
-				return false;
315
-			}
316
-		} else {
317
-			if (!$this->isCreatable('')) {
318
-				return false;
319
-			}
320
-		}
321
-
322
-		return $this->nonMaskedStorage->rename($this->getUnjailedPath($path1), $this->getUnjailedPath($path2));
323
-	}
324
-
325
-	/**
326
-	 * return mount point of share, relative to data/user/files
327
-	 *
328
-	 * @return string
329
-	 */
330
-	public function getMountPoint() {
331
-		return $this->superShare->getTarget();
332
-	}
333
-
334
-	/**
335
-	 * @param string $path
336
-	 */
337
-	public function setMountPoint($path) {
338
-		$this->superShare->setTarget($path);
339
-
340
-		foreach ($this->groupedShares as $share) {
341
-			$share->setTarget($path);
342
-		}
343
-	}
344
-
345
-	/**
346
-	 * get the user who shared the file
347
-	 *
348
-	 * @return string
349
-	 */
350
-	public function getSharedFrom() {
351
-		return $this->superShare->getShareOwner();
352
-	}
353
-
354
-	/**
355
-	 * @return \OCP\Share\IShare
356
-	 */
357
-	public function getShare() {
358
-		return $this->superShare;
359
-	}
360
-
361
-	/**
362
-	 * return share type, can be "file" or "folder"
363
-	 *
364
-	 * @return string
365
-	 */
366
-	public function getItemType() {
367
-		return $this->superShare->getNodeType();
368
-	}
369
-
370
-	/**
371
-	 * @param string $path
372
-	 * @param null $storage
373
-	 * @return Cache
374
-	 */
375
-	public function getCache($path = '', $storage = null) {
376
-		if ($this->cache) {
377
-			return $this->cache;
378
-		}
379
-		if (!$storage) {
380
-			$storage = $this;
381
-		}
382
-		$sourceRoot = $this->getSourceRootInfo();
383
-		if ($this->storage instanceof FailedStorage) {
384
-			return new FailedCache();
385
-		}
386
-
387
-		$this->cache = new \OCA\Files_Sharing\Cache($storage, $sourceRoot, $this->superShare);
388
-		return $this->cache;
389
-	}
390
-
391
-	public function getScanner($path = '', $storage = null) {
392
-		if (!$storage) {
393
-			$storage = $this;
394
-		}
395
-		return new \OCA\Files_Sharing\Scanner($storage);
396
-	}
397
-
398
-	public function getOwner($path) {
399
-		return $this->superShare->getShareOwner();
400
-	}
401
-
402
-	public function getWatcher($path = '', $storage = null) {
403
-		// cache updating is handled by the share source
404
-		return new NullWatcher();
405
-	}
406
-
407
-	/**
408
-	 * unshare complete storage, also the grouped shares
409
-	 *
410
-	 * @return bool
411
-	 */
412
-	public function unshareStorage() {
413
-		foreach ($this->groupedShares as $share) {
414
-			\OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
415
-		}
416
-		return true;
417
-	}
418
-
419
-	/**
420
-	 * @param string $path
421
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
422
-	 * @param \OCP\Lock\ILockingProvider $provider
423
-	 * @throws \OCP\Lock\LockedException
424
-	 */
425
-	public function acquireLock($path, $type, ILockingProvider $provider) {
426
-		/** @var \OCP\Files\Storage $targetStorage */
427
-		[$targetStorage, $targetInternalPath] = $this->resolvePath($path);
428
-		$targetStorage->acquireLock($targetInternalPath, $type, $provider);
429
-		// lock the parent folders of the owner when locking the share as recipient
430
-		if ($path === '') {
431
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
432
-			$this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
433
-		}
434
-	}
435
-
436
-	/**
437
-	 * @param string $path
438
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
439
-	 * @param \OCP\Lock\ILockingProvider $provider
440
-	 */
441
-	public function releaseLock($path, $type, ILockingProvider $provider) {
442
-		/** @var \OCP\Files\Storage $targetStorage */
443
-		[$targetStorage, $targetInternalPath] = $this->resolvePath($path);
444
-		$targetStorage->releaseLock($targetInternalPath, $type, $provider);
445
-		// unlock the parent folders of the owner when unlocking the share as recipient
446
-		if ($path === '') {
447
-			$sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
448
-			$this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
449
-		}
450
-	}
451
-
452
-	/**
453
-	 * @param string $path
454
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
455
-	 * @param \OCP\Lock\ILockingProvider $provider
456
-	 */
457
-	public function changeLock($path, $type, ILockingProvider $provider) {
458
-		/** @var \OCP\Files\Storage $targetStorage */
459
-		[$targetStorage, $targetInternalPath] = $this->resolvePath($path);
460
-		$targetStorage->changeLock($targetInternalPath, $type, $provider);
461
-	}
462
-
463
-	/**
464
-	 * @return array [ available, last_checked ]
465
-	 */
466
-	public function getAvailability() {
467
-		// shares do not participate in availability logic
468
-		return [
469
-			'available' => true,
470
-			'last_checked' => 0,
471
-		];
472
-	}
473
-
474
-	/**
475
-	 * @param bool $available
476
-	 */
477
-	public function setAvailability($available) {
478
-		// shares do not participate in availability logic
479
-	}
480
-
481
-	public function getSourceStorage() {
482
-		$this->init();
483
-		return $this->nonMaskedStorage;
484
-	}
485
-
486
-	public function getWrapperStorage() {
487
-		$this->init();
488
-		return $this->storage;
489
-	}
490
-
491
-	public function file_get_contents($path) {
492
-		$info = [
493
-			'target' => $this->getMountPoint() . '/' . $path,
494
-			'source' => $this->getUnjailedPath($path),
495
-		];
496
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
497
-		return parent::file_get_contents($path);
498
-	}
499
-
500
-	public function file_put_contents($path, $data) {
501
-		$info = [
502
-			'target' => $this->getMountPoint() . '/' . $path,
503
-			'source' => $this->getUnjailedPath($path),
504
-		];
505
-		\OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
506
-		return parent::file_put_contents($path, $data);
507
-	}
508
-
509
-	public function setMountOptions(array $options) {
510
-		$this->mountOptions = $options;
511
-	}
512
-
513
-	public function getUnjailedPath($path) {
514
-		$this->init();
515
-		return parent::getUnjailedPath($path);
516
-	}
53
+    /** @var \OCP\Share\IShare */
54
+    private $superShare;
55
+
56
+    /** @var \OCP\Share\IShare[] */
57
+    private $groupedShares;
58
+
59
+    /**
60
+     * @var \OC\Files\View
61
+     */
62
+    private $ownerView;
63
+
64
+    private $initialized = false;
65
+
66
+    /**
67
+     * @var ICacheEntry
68
+     */
69
+    private $sourceRootInfo;
70
+
71
+    /** @var string */
72
+    private $user;
73
+
74
+    /**
75
+     * @var \OCP\ILogger
76
+     */
77
+    private $logger;
78
+
79
+    /** @var  IStorage */
80
+    private $nonMaskedStorage;
81
+
82
+    private $options;
83
+
84
+    /** @var boolean */
85
+    private $sharingDisabledForUser;
86
+
87
+    public function __construct($arguments) {
88
+        $this->ownerView = $arguments['ownerView'];
89
+        $this->logger = \OC::$server->getLogger();
90
+
91
+        $this->superShare = $arguments['superShare'];
92
+        $this->groupedShares = $arguments['groupedShares'];
93
+
94
+        $this->user = $arguments['user'];
95
+        if (isset($arguments['sharingDisabledForUser'])) {
96
+            $this->sharingDisabledForUser = $arguments['sharingDisabledForUser'];
97
+        } else {
98
+            $this->sharingDisabledForUser = false;
99
+        }
100
+
101
+        parent::__construct([
102
+            'storage' => null,
103
+            'root' => null,
104
+        ]);
105
+    }
106
+
107
+    /**
108
+     * @return ICacheEntry
109
+     */
110
+    private function getSourceRootInfo() {
111
+        if (is_null($this->sourceRootInfo)) {
112
+            if (is_null($this->superShare->getNodeCacheEntry())) {
113
+                $this->init();
114
+                $this->sourceRootInfo = $this->nonMaskedStorage->getCache()->get($this->rootPath);
115
+            } else {
116
+                $this->sourceRootInfo = $this->superShare->getNodeCacheEntry();
117
+            }
118
+        }
119
+        return $this->sourceRootInfo;
120
+    }
121
+
122
+    private function init() {
123
+        if ($this->initialized) {
124
+            return;
125
+        }
126
+        $this->initialized = true;
127
+        try {
128
+            Filesystem::initMountPoints($this->superShare->getShareOwner());
129
+            $storageId = $this->superShare->getNodeCacheEntry() ? $this->superShare->getNodeCacheEntry()->getStorageId() : null;
130
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId(), $storageId);
131
+            [$this->nonMaskedStorage, $this->rootPath] = $this->ownerView->resolvePath($sourcePath);
132
+            $this->storage = new PermissionsMask([
133
+                'storage' => $this->nonMaskedStorage,
134
+                'mask' => $this->superShare->getPermissions(),
135
+            ]);
136
+        } catch (NotFoundException $e) {
137
+            // original file not accessible or deleted, set FailedStorage
138
+            $this->storage = new FailedStorage(['exception' => $e]);
139
+            $this->cache = new FailedCache();
140
+            $this->rootPath = '';
141
+        } catch (NoUserException $e) {
142
+            // sharer user deleted, set FailedStorage
143
+            $this->storage = new FailedStorage(['exception' => $e]);
144
+            $this->cache = new FailedCache();
145
+            $this->rootPath = '';
146
+        } catch (\Exception $e) {
147
+            $this->storage = new FailedStorage(['exception' => $e]);
148
+            $this->cache = new FailedCache();
149
+            $this->rootPath = '';
150
+            $this->logger->logException($e);
151
+        }
152
+
153
+        if (!$this->nonMaskedStorage) {
154
+            $this->nonMaskedStorage = $this->storage;
155
+        }
156
+    }
157
+
158
+    /**
159
+     * @inheritdoc
160
+     */
161
+    public function instanceOfStorage($class) {
162
+        if ($class === '\OC\Files\Storage\Common') {
163
+            return true;
164
+        }
165
+        if (in_array($class, ['\OC\Files\Storage\Home', '\OC\Files\ObjectStore\HomeObjectStoreStorage', '\OCP\Files\IHomeStorage'])) {
166
+            return false;
167
+        }
168
+        return parent::instanceOfStorage($class);
169
+    }
170
+
171
+    /**
172
+     * @return string
173
+     */
174
+    public function getShareId() {
175
+        return $this->superShare->getId();
176
+    }
177
+
178
+    private function isValid() {
179
+        return $this->getSourceRootInfo() && ($this->getSourceRootInfo()->getPermissions() & Constants::PERMISSION_SHARE) === Constants::PERMISSION_SHARE;
180
+    }
181
+
182
+    /**
183
+     * get id of the mount point
184
+     *
185
+     * @return string
186
+     */
187
+    public function getId() {
188
+        return 'shared::' . $this->getMountPoint();
189
+    }
190
+
191
+    /**
192
+     * Get the permissions granted for a shared file
193
+     *
194
+     * @param string $target Shared target file path
195
+     * @return int CRUDS permissions granted
196
+     */
197
+    public function getPermissions($target = '') {
198
+        if (!$this->isValid()) {
199
+            return 0;
200
+        }
201
+        $permissions = parent::getPermissions($target) & $this->superShare->getPermissions();
202
+
203
+        // part files and the mount point always have delete permissions
204
+        if ($target === '' || pathinfo($target, PATHINFO_EXTENSION) === 'part') {
205
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
206
+        }
207
+
208
+        if ($this->sharingDisabledForUser) {
209
+            $permissions &= ~\OCP\Constants::PERMISSION_SHARE;
210
+        }
211
+
212
+        return $permissions;
213
+    }
214
+
215
+    public function isCreatable($path) {
216
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_CREATE);
217
+    }
218
+
219
+    public function isReadable($path) {
220
+        if (!$this->isValid()) {
221
+            return false;
222
+        }
223
+        if (!$this->file_exists($path)) {
224
+            return false;
225
+        }
226
+        /** @var IStorage $storage */
227
+        /** @var string $internalPath */
228
+        [$storage, $internalPath] = $this->resolvePath($path);
229
+        return $storage->isReadable($internalPath);
230
+    }
231
+
232
+    public function isUpdatable($path) {
233
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_UPDATE);
234
+    }
235
+
236
+    public function isDeletable($path) {
237
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_DELETE);
238
+    }
239
+
240
+    public function isSharable($path) {
241
+        if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
242
+            return false;
243
+        }
244
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
245
+    }
246
+
247
+    public function fopen($path, $mode) {
248
+        $source = $this->getUnjailedPath($path);
249
+        switch ($mode) {
250
+            case 'r+':
251
+            case 'rb+':
252
+            case 'w+':
253
+            case 'wb+':
254
+            case 'x+':
255
+            case 'xb+':
256
+            case 'a+':
257
+            case 'ab+':
258
+            case 'w':
259
+            case 'wb':
260
+            case 'x':
261
+            case 'xb':
262
+            case 'a':
263
+            case 'ab':
264
+                $creatable = $this->isCreatable(dirname($path));
265
+                $updatable = $this->isUpdatable($path);
266
+                // if neither permissions given, no need to continue
267
+                if (!$creatable && !$updatable) {
268
+                    if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
269
+                        $updatable = $this->isUpdatable(dirname($path));
270
+                    }
271
+
272
+                    if (!$updatable) {
273
+                        return false;
274
+                    }
275
+                }
276
+
277
+                $exists = $this->file_exists($path);
278
+                // if a file exists, updatable permissions are required
279
+                if ($exists && !$updatable) {
280
+                    return false;
281
+                }
282
+
283
+                // part file is allowed if !$creatable but the final file is $updatable
284
+                if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') {
285
+                    if (!$exists && !$creatable) {
286
+                        return false;
287
+                    }
288
+                }
289
+        }
290
+        $info = [
291
+            'target' => $this->getMountPoint() . '/' . $path,
292
+            'source' => $source,
293
+            'mode' => $mode,
294
+        ];
295
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'fopen', $info);
296
+        return $this->nonMaskedStorage->fopen($this->getUnjailedPath($path), $mode);
297
+    }
298
+
299
+    /**
300
+     * see https://www.php.net/manual/en/function.rename.php
301
+     *
302
+     * @param string $path1
303
+     * @param string $path2
304
+     * @return bool
305
+     */
306
+    public function rename($path1, $path2) {
307
+        $this->init();
308
+        $isPartFile = pathinfo($path1, PATHINFO_EXTENSION) === 'part';
309
+        $targetExists = $this->file_exists($path2);
310
+        $sameFolder = dirname($path1) === dirname($path2);
311
+
312
+        if ($targetExists || ($sameFolder && !$isPartFile)) {
313
+            if (!$this->isUpdatable('')) {
314
+                return false;
315
+            }
316
+        } else {
317
+            if (!$this->isCreatable('')) {
318
+                return false;
319
+            }
320
+        }
321
+
322
+        return $this->nonMaskedStorage->rename($this->getUnjailedPath($path1), $this->getUnjailedPath($path2));
323
+    }
324
+
325
+    /**
326
+     * return mount point of share, relative to data/user/files
327
+     *
328
+     * @return string
329
+     */
330
+    public function getMountPoint() {
331
+        return $this->superShare->getTarget();
332
+    }
333
+
334
+    /**
335
+     * @param string $path
336
+     */
337
+    public function setMountPoint($path) {
338
+        $this->superShare->setTarget($path);
339
+
340
+        foreach ($this->groupedShares as $share) {
341
+            $share->setTarget($path);
342
+        }
343
+    }
344
+
345
+    /**
346
+     * get the user who shared the file
347
+     *
348
+     * @return string
349
+     */
350
+    public function getSharedFrom() {
351
+        return $this->superShare->getShareOwner();
352
+    }
353
+
354
+    /**
355
+     * @return \OCP\Share\IShare
356
+     */
357
+    public function getShare() {
358
+        return $this->superShare;
359
+    }
360
+
361
+    /**
362
+     * return share type, can be "file" or "folder"
363
+     *
364
+     * @return string
365
+     */
366
+    public function getItemType() {
367
+        return $this->superShare->getNodeType();
368
+    }
369
+
370
+    /**
371
+     * @param string $path
372
+     * @param null $storage
373
+     * @return Cache
374
+     */
375
+    public function getCache($path = '', $storage = null) {
376
+        if ($this->cache) {
377
+            return $this->cache;
378
+        }
379
+        if (!$storage) {
380
+            $storage = $this;
381
+        }
382
+        $sourceRoot = $this->getSourceRootInfo();
383
+        if ($this->storage instanceof FailedStorage) {
384
+            return new FailedCache();
385
+        }
386
+
387
+        $this->cache = new \OCA\Files_Sharing\Cache($storage, $sourceRoot, $this->superShare);
388
+        return $this->cache;
389
+    }
390
+
391
+    public function getScanner($path = '', $storage = null) {
392
+        if (!$storage) {
393
+            $storage = $this;
394
+        }
395
+        return new \OCA\Files_Sharing\Scanner($storage);
396
+    }
397
+
398
+    public function getOwner($path) {
399
+        return $this->superShare->getShareOwner();
400
+    }
401
+
402
+    public function getWatcher($path = '', $storage = null) {
403
+        // cache updating is handled by the share source
404
+        return new NullWatcher();
405
+    }
406
+
407
+    /**
408
+     * unshare complete storage, also the grouped shares
409
+     *
410
+     * @return bool
411
+     */
412
+    public function unshareStorage() {
413
+        foreach ($this->groupedShares as $share) {
414
+            \OC::$server->getShareManager()->deleteFromSelf($share, $this->user);
415
+        }
416
+        return true;
417
+    }
418
+
419
+    /**
420
+     * @param string $path
421
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
422
+     * @param \OCP\Lock\ILockingProvider $provider
423
+     * @throws \OCP\Lock\LockedException
424
+     */
425
+    public function acquireLock($path, $type, ILockingProvider $provider) {
426
+        /** @var \OCP\Files\Storage $targetStorage */
427
+        [$targetStorage, $targetInternalPath] = $this->resolvePath($path);
428
+        $targetStorage->acquireLock($targetInternalPath, $type, $provider);
429
+        // lock the parent folders of the owner when locking the share as recipient
430
+        if ($path === '') {
431
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
432
+            $this->ownerView->lockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
433
+        }
434
+    }
435
+
436
+    /**
437
+     * @param string $path
438
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
439
+     * @param \OCP\Lock\ILockingProvider $provider
440
+     */
441
+    public function releaseLock($path, $type, ILockingProvider $provider) {
442
+        /** @var \OCP\Files\Storage $targetStorage */
443
+        [$targetStorage, $targetInternalPath] = $this->resolvePath($path);
444
+        $targetStorage->releaseLock($targetInternalPath, $type, $provider);
445
+        // unlock the parent folders of the owner when unlocking the share as recipient
446
+        if ($path === '') {
447
+            $sourcePath = $this->ownerView->getPath($this->superShare->getNodeId());
448
+            $this->ownerView->unlockFile(dirname($sourcePath), ILockingProvider::LOCK_SHARED, true);
449
+        }
450
+    }
451
+
452
+    /**
453
+     * @param string $path
454
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
455
+     * @param \OCP\Lock\ILockingProvider $provider
456
+     */
457
+    public function changeLock($path, $type, ILockingProvider $provider) {
458
+        /** @var \OCP\Files\Storage $targetStorage */
459
+        [$targetStorage, $targetInternalPath] = $this->resolvePath($path);
460
+        $targetStorage->changeLock($targetInternalPath, $type, $provider);
461
+    }
462
+
463
+    /**
464
+     * @return array [ available, last_checked ]
465
+     */
466
+    public function getAvailability() {
467
+        // shares do not participate in availability logic
468
+        return [
469
+            'available' => true,
470
+            'last_checked' => 0,
471
+        ];
472
+    }
473
+
474
+    /**
475
+     * @param bool $available
476
+     */
477
+    public function setAvailability($available) {
478
+        // shares do not participate in availability logic
479
+    }
480
+
481
+    public function getSourceStorage() {
482
+        $this->init();
483
+        return $this->nonMaskedStorage;
484
+    }
485
+
486
+    public function getWrapperStorage() {
487
+        $this->init();
488
+        return $this->storage;
489
+    }
490
+
491
+    public function file_get_contents($path) {
492
+        $info = [
493
+            'target' => $this->getMountPoint() . '/' . $path,
494
+            'source' => $this->getUnjailedPath($path),
495
+        ];
496
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_get_contents', $info);
497
+        return parent::file_get_contents($path);
498
+    }
499
+
500
+    public function file_put_contents($path, $data) {
501
+        $info = [
502
+            'target' => $this->getMountPoint() . '/' . $path,
503
+            'source' => $this->getUnjailedPath($path),
504
+        ];
505
+        \OCP\Util::emitHook('\OC\Files\Storage\Shared', 'file_put_contents', $info);
506
+        return parent::file_put_contents($path, $data);
507
+    }
508
+
509
+    public function setMountOptions(array $options) {
510
+        $this->mountOptions = $options;
511
+    }
512
+
513
+    public function getUnjailedPath($path) {
514
+        $this->init();
515
+        return parent::getUnjailedPath($path);
516
+    }
517 517
 }
Please login to merge, or discard this patch.
apps/files/lib/Command/ScanAppData.php 1 patch
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -45,243 +45,243 @@
 block discarded – undo
45 45
 
46 46
 class ScanAppData extends Base {
47 47
 
48
-	/** @var IRootFolder */
49
-	protected $root;
50
-	/** @var IConfig */
51
-	protected $config;
52
-	/** @var float */
53
-	protected $execTime = 0;
54
-	/** @var int */
55
-	protected $foldersCounter = 0;
56
-	/** @var int */
57
-	protected $filesCounter = 0;
58
-
59
-	public function __construct(IRootFolder $rootFolder, IConfig $config) {
60
-		parent::__construct();
61
-
62
-		$this->root = $rootFolder;
63
-		$this->config = $config;
64
-	}
65
-
66
-	protected function configure() {
67
-		parent::configure();
68
-
69
-		$this
70
-			->setName('files:scan-app-data')
71
-			->setDescription('rescan the AppData folder');
72
-
73
-		$this->addArgument('folder', InputArgument::OPTIONAL, 'The appdata subfolder to scan', '');
74
-	}
75
-
76
-	public function checkScanWarning($fullPath, OutputInterface $output) {
77
-		$normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
78
-		$path = basename($fullPath);
79
-
80
-		if ($normalizedPath !== $path) {
81
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
82
-		}
83
-	}
84
-
85
-	protected function scanFiles(OutputInterface $output, string $folder): int {
86
-		try {
87
-			$appData = $this->getAppDataFolder();
88
-		} catch (NotFoundException $e) {
89
-			$output->writeln('<error>NoAppData folder found</error>');
90
-			return 1;
91
-		}
92
-
93
-		if ($folder !== '') {
94
-			try {
95
-				$appData = $appData->get($folder);
96
-			} catch (NotFoundException $e) {
97
-				$output->writeln('<error>Could not find folder: ' . $folder . '</error>');
98
-				return 1;
99
-			}
100
-		}
101
-
102
-		$connection = $this->reconnectToDatabase($output);
103
-		$scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
104
-
105
-		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
106
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
107
-			$output->writeln("\tFile   <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
108
-			++$this->filesCounter;
109
-			$this->abortIfInterrupted();
110
-		});
111
-
112
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
113
-			$output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
114
-			++$this->foldersCounter;
115
-			$this->abortIfInterrupted();
116
-		});
117
-
118
-		$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
119
-			$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
120
-		});
121
-
122
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
123
-			$this->checkScanWarning($path, $output);
124
-		});
125
-
126
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
127
-			$this->checkScanWarning($path, $output);
128
-		});
129
-
130
-		try {
131
-			$scanner->scan($appData->getPath());
132
-		} catch (ForbiddenException $e) {
133
-			$output->writeln('<error>Storage not writable</error>');
134
-			$output->writeln('<info>Make sure you\'re running the scan command only as the user the web server runs as</info>');
135
-			return 1;
136
-		} catch (InterruptedException $e) {
137
-			# exit the function if ctrl-c has been pressed
138
-			$output->writeln('<info>Interrupted by user</info>');
139
-			return 1;
140
-		} catch (NotFoundException $e) {
141
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
142
-			return 1;
143
-		} catch (\Exception $e) {
144
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
145
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
146
-			return 1;
147
-		}
148
-
149
-		return 0;
150
-	}
151
-
152
-
153
-	protected function execute(InputInterface $input, OutputInterface $output): int {
154
-		# restrict the verbosity level to VERBOSITY_VERBOSE
155
-		if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
156
-			$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
157
-		}
158
-
159
-		$output->writeln('Scanning AppData for files');
160
-		$output->writeln('');
161
-
162
-		$folder = $input->getArgument('folder');
163
-
164
-		$this->initTools();
165
-
166
-		$exitCode = $this->scanFiles($output, $folder);
167
-		if ($exitCode === 0) {
168
-			$this->presentStats($output);
169
-		}
170
-		return $exitCode;
171
-	}
172
-
173
-	/**
174
-	 * Initialises some useful tools for the Command
175
-	 */
176
-	protected function initTools() {
177
-		// Start the timer
178
-		$this->execTime = -microtime(true);
179
-		// Convert PHP errors to exceptions
180
-		set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
181
-	}
182
-
183
-	/**
184
-	 * Processes PHP errors as exceptions in order to be able to keep track of problems
185
-	 *
186
-	 * @see https://www.php.net/manual/en/function.set-error-handler.php
187
-	 *
188
-	 * @param int $severity the level of the error raised
189
-	 * @param string $message
190
-	 * @param string $file the filename that the error was raised in
191
-	 * @param int $line the line number the error was raised
192
-	 *
193
-	 * @throws \ErrorException
194
-	 */
195
-	public function exceptionErrorHandler($severity, $message, $file, $line) {
196
-		if (!(error_reporting() & $severity)) {
197
-			// This error code is not included in error_reporting
198
-			return;
199
-		}
200
-		throw new \ErrorException($message, 0, $severity, $file, $line);
201
-	}
202
-
203
-	/**
204
-	 * @param OutputInterface $output
205
-	 */
206
-	protected function presentStats(OutputInterface $output) {
207
-		// Stop the timer
208
-		$this->execTime += microtime(true);
209
-
210
-		$headers = [
211
-			'Folders', 'Files', 'Elapsed time'
212
-		];
213
-
214
-		$this->showSummary($headers, null, $output);
215
-	}
216
-
217
-	/**
218
-	 * Shows a summary of operations
219
-	 *
220
-	 * @param string[] $headers
221
-	 * @param string[] $rows
222
-	 * @param OutputInterface $output
223
-	 */
224
-	protected function showSummary($headers, $rows, OutputInterface $output) {
225
-		$niceDate = $this->formatExecTime();
226
-		if (!$rows) {
227
-			$rows = [
228
-				$this->foldersCounter,
229
-				$this->filesCounter,
230
-				$niceDate,
231
-			];
232
-		}
233
-		$table = new Table($output);
234
-		$table
235
-			->setHeaders($headers)
236
-			->setRows([$rows]);
237
-		$table->render();
238
-	}
239
-
240
-
241
-	/**
242
-	 * Formats microtime into a human readable format
243
-	 *
244
-	 * @return string
245
-	 */
246
-	protected function formatExecTime() {
247
-		$secs = round($this->execTime);
248
-		# convert seconds into HH:MM:SS form
249
-		return sprintf('%02d:%02d:%02d', ($secs / 3600), ($secs / 60 % 60), $secs % 60);
250
-	}
251
-
252
-	/**
253
-	 * @return \OCP\IDBConnection
254
-	 */
255
-	protected function reconnectToDatabase(OutputInterface $output) {
256
-		/** @var Connection | IDBConnection $connection*/
257
-		$connection = \OC::$server->getDatabaseConnection();
258
-		try {
259
-			$connection->close();
260
-		} catch (\Exception $ex) {
261
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
262
-		}
263
-		while (!$connection->isConnected()) {
264
-			try {
265
-				$connection->connect();
266
-			} catch (\Exception $ex) {
267
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
268
-				sleep(60);
269
-			}
270
-		}
271
-		return $connection;
272
-	}
273
-
274
-	/**
275
-	 * @return \OCP\Files\Folder
276
-	 * @throws NotFoundException
277
-	 */
278
-	private function getAppDataFolder() {
279
-		$instanceId = $this->config->getSystemValue('instanceid', null);
280
-
281
-		if ($instanceId === null) {
282
-			throw new NotFoundException();
283
-		}
284
-
285
-		return $this->root->get('appdata_'.$instanceId);
286
-	}
48
+    /** @var IRootFolder */
49
+    protected $root;
50
+    /** @var IConfig */
51
+    protected $config;
52
+    /** @var float */
53
+    protected $execTime = 0;
54
+    /** @var int */
55
+    protected $foldersCounter = 0;
56
+    /** @var int */
57
+    protected $filesCounter = 0;
58
+
59
+    public function __construct(IRootFolder $rootFolder, IConfig $config) {
60
+        parent::__construct();
61
+
62
+        $this->root = $rootFolder;
63
+        $this->config = $config;
64
+    }
65
+
66
+    protected function configure() {
67
+        parent::configure();
68
+
69
+        $this
70
+            ->setName('files:scan-app-data')
71
+            ->setDescription('rescan the AppData folder');
72
+
73
+        $this->addArgument('folder', InputArgument::OPTIONAL, 'The appdata subfolder to scan', '');
74
+    }
75
+
76
+    public function checkScanWarning($fullPath, OutputInterface $output) {
77
+        $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
78
+        $path = basename($fullPath);
79
+
80
+        if ($normalizedPath !== $path) {
81
+            $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
82
+        }
83
+    }
84
+
85
+    protected function scanFiles(OutputInterface $output, string $folder): int {
86
+        try {
87
+            $appData = $this->getAppDataFolder();
88
+        } catch (NotFoundException $e) {
89
+            $output->writeln('<error>NoAppData folder found</error>');
90
+            return 1;
91
+        }
92
+
93
+        if ($folder !== '') {
94
+            try {
95
+                $appData = $appData->get($folder);
96
+            } catch (NotFoundException $e) {
97
+                $output->writeln('<error>Could not find folder: ' . $folder . '</error>');
98
+                return 1;
99
+            }
100
+        }
101
+
102
+        $connection = $this->reconnectToDatabase($output);
103
+        $scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
104
+
105
+        # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
106
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
107
+            $output->writeln("\tFile   <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
108
+            ++$this->filesCounter;
109
+            $this->abortIfInterrupted();
110
+        });
111
+
112
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
113
+            $output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
114
+            ++$this->foldersCounter;
115
+            $this->abortIfInterrupted();
116
+        });
117
+
118
+        $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
119
+            $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
120
+        });
121
+
122
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
123
+            $this->checkScanWarning($path, $output);
124
+        });
125
+
126
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
127
+            $this->checkScanWarning($path, $output);
128
+        });
129
+
130
+        try {
131
+            $scanner->scan($appData->getPath());
132
+        } catch (ForbiddenException $e) {
133
+            $output->writeln('<error>Storage not writable</error>');
134
+            $output->writeln('<info>Make sure you\'re running the scan command only as the user the web server runs as</info>');
135
+            return 1;
136
+        } catch (InterruptedException $e) {
137
+            # exit the function if ctrl-c has been pressed
138
+            $output->writeln('<info>Interrupted by user</info>');
139
+            return 1;
140
+        } catch (NotFoundException $e) {
141
+            $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
142
+            return 1;
143
+        } catch (\Exception $e) {
144
+            $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
145
+            $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
146
+            return 1;
147
+        }
148
+
149
+        return 0;
150
+    }
151
+
152
+
153
+    protected function execute(InputInterface $input, OutputInterface $output): int {
154
+        # restrict the verbosity level to VERBOSITY_VERBOSE
155
+        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
156
+            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
157
+        }
158
+
159
+        $output->writeln('Scanning AppData for files');
160
+        $output->writeln('');
161
+
162
+        $folder = $input->getArgument('folder');
163
+
164
+        $this->initTools();
165
+
166
+        $exitCode = $this->scanFiles($output, $folder);
167
+        if ($exitCode === 0) {
168
+            $this->presentStats($output);
169
+        }
170
+        return $exitCode;
171
+    }
172
+
173
+    /**
174
+     * Initialises some useful tools for the Command
175
+     */
176
+    protected function initTools() {
177
+        // Start the timer
178
+        $this->execTime = -microtime(true);
179
+        // Convert PHP errors to exceptions
180
+        set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
181
+    }
182
+
183
+    /**
184
+     * Processes PHP errors as exceptions in order to be able to keep track of problems
185
+     *
186
+     * @see https://www.php.net/manual/en/function.set-error-handler.php
187
+     *
188
+     * @param int $severity the level of the error raised
189
+     * @param string $message
190
+     * @param string $file the filename that the error was raised in
191
+     * @param int $line the line number the error was raised
192
+     *
193
+     * @throws \ErrorException
194
+     */
195
+    public function exceptionErrorHandler($severity, $message, $file, $line) {
196
+        if (!(error_reporting() & $severity)) {
197
+            // This error code is not included in error_reporting
198
+            return;
199
+        }
200
+        throw new \ErrorException($message, 0, $severity, $file, $line);
201
+    }
202
+
203
+    /**
204
+     * @param OutputInterface $output
205
+     */
206
+    protected function presentStats(OutputInterface $output) {
207
+        // Stop the timer
208
+        $this->execTime += microtime(true);
209
+
210
+        $headers = [
211
+            'Folders', 'Files', 'Elapsed time'
212
+        ];
213
+
214
+        $this->showSummary($headers, null, $output);
215
+    }
216
+
217
+    /**
218
+     * Shows a summary of operations
219
+     *
220
+     * @param string[] $headers
221
+     * @param string[] $rows
222
+     * @param OutputInterface $output
223
+     */
224
+    protected function showSummary($headers, $rows, OutputInterface $output) {
225
+        $niceDate = $this->formatExecTime();
226
+        if (!$rows) {
227
+            $rows = [
228
+                $this->foldersCounter,
229
+                $this->filesCounter,
230
+                $niceDate,
231
+            ];
232
+        }
233
+        $table = new Table($output);
234
+        $table
235
+            ->setHeaders($headers)
236
+            ->setRows([$rows]);
237
+        $table->render();
238
+    }
239
+
240
+
241
+    /**
242
+     * Formats microtime into a human readable format
243
+     *
244
+     * @return string
245
+     */
246
+    protected function formatExecTime() {
247
+        $secs = round($this->execTime);
248
+        # convert seconds into HH:MM:SS form
249
+        return sprintf('%02d:%02d:%02d', ($secs / 3600), ($secs / 60 % 60), $secs % 60);
250
+    }
251
+
252
+    /**
253
+     * @return \OCP\IDBConnection
254
+     */
255
+    protected function reconnectToDatabase(OutputInterface $output) {
256
+        /** @var Connection | IDBConnection $connection*/
257
+        $connection = \OC::$server->getDatabaseConnection();
258
+        try {
259
+            $connection->close();
260
+        } catch (\Exception $ex) {
261
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
262
+        }
263
+        while (!$connection->isConnected()) {
264
+            try {
265
+                $connection->connect();
266
+            } catch (\Exception $ex) {
267
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
268
+                sleep(60);
269
+            }
270
+        }
271
+        return $connection;
272
+    }
273
+
274
+    /**
275
+     * @return \OCP\Files\Folder
276
+     * @throws NotFoundException
277
+     */
278
+    private function getAppDataFolder() {
279
+        $instanceId = $this->config->getSystemValue('instanceid', null);
280
+
281
+        if ($instanceId === null) {
282
+            throw new NotFoundException();
283
+        }
284
+
285
+        return $this->root->get('appdata_'.$instanceId);
286
+    }
287 287
 }
Please login to merge, or discard this patch.
apps/files/lib/Command/Scan.php 1 patch
Indentation   +271 added lines, -271 removed lines patch added patch discarded remove patch
@@ -52,275 +52,275 @@
 block discarded – undo
52 52
 
53 53
 class Scan extends Base {
54 54
 
55
-	/** @var IUserManager $userManager */
56
-	private $userManager;
57
-	/** @var float */
58
-	protected $execTime = 0;
59
-	/** @var int */
60
-	protected $foldersCounter = 0;
61
-	/** @var int */
62
-	protected $filesCounter = 0;
63
-
64
-	public function __construct(IUserManager $userManager) {
65
-		$this->userManager = $userManager;
66
-		parent::__construct();
67
-	}
68
-
69
-	protected function configure() {
70
-		parent::configure();
71
-
72
-		$this
73
-			->setName('files:scan')
74
-			->setDescription('rescan filesystem')
75
-			->addArgument(
76
-				'user_id',
77
-				InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
78
-				'will rescan all files of the given user(s)'
79
-			)
80
-			->addOption(
81
-				'path',
82
-				'p',
83
-				InputArgument::OPTIONAL,
84
-				'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
85
-			)
86
-			->addOption(
87
-				'all',
88
-				null,
89
-				InputOption::VALUE_NONE,
90
-				'will rescan all files of all known users'
91
-			)->addOption(
92
-				'unscanned',
93
-				null,
94
-				InputOption::VALUE_NONE,
95
-				'only scan files which are marked as not fully scanned'
96
-			)->addOption(
97
-				'shallow',
98
-				null,
99
-				InputOption::VALUE_NONE,
100
-				'do not scan folders recursively'
101
-			)->addOption(
102
-				'home-only',
103
-				null,
104
-				InputOption::VALUE_NONE,
105
-				'only scan the home storage, ignoring any mounted external storage or share'
106
-			);
107
-	}
108
-
109
-	public function checkScanWarning($fullPath, OutputInterface $output) {
110
-		$normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
111
-		$path = basename($fullPath);
112
-
113
-		if ($normalizedPath !== $path) {
114
-			$output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
115
-		}
116
-	}
117
-
118
-	protected function scanFiles($user, $path, OutputInterface $output, $backgroundScan = false, $recursive = true, $homeOnly = false) {
119
-		$connection = $this->reconnectToDatabase($output);
120
-		$scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
121
-
122
-		# check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
123
-
124
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
125
-			$output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
126
-			++$this->filesCounter;
127
-			$this->abortIfInterrupted();
128
-		});
129
-
130
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
131
-			$output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
132
-			++$this->foldersCounter;
133
-			$this->abortIfInterrupted();
134
-		});
135
-
136
-		$scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
137
-			$output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
138
-		});
139
-
140
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
141
-			$this->checkScanWarning($path, $output);
142
-		});
143
-
144
-		$scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
145
-			$this->checkScanWarning($path, $output);
146
-		});
147
-
148
-		try {
149
-			if ($backgroundScan) {
150
-				$scanner->backgroundScan($path);
151
-			} else {
152
-				$scanner->scan($path, $recursive, $homeOnly ? [$this, 'filterHomeMount'] : null);
153
-			}
154
-		} catch (ForbiddenException $e) {
155
-			$output->writeln("<error>Home storage for user $user not writable</error>");
156
-			$output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
157
-		} catch (InterruptedException $e) {
158
-			# exit the function if ctrl-c has been pressed
159
-			$output->writeln('Interrupted by user');
160
-		} catch (NotFoundException $e) {
161
-			$output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
162
-		} catch (\Exception $e) {
163
-			$output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
164
-			$output->writeln('<error>' . $e->getTraceAsString() . '</error>');
165
-		}
166
-	}
167
-
168
-	public function filterHomeMount(IMountPoint $mountPoint) {
169
-		// any mountpoint inside '/$user/files/'
170
-		return substr_count($mountPoint->getMountPoint(), '/') <= 3;
171
-	}
172
-
173
-	protected function execute(InputInterface $input, OutputInterface $output): int {
174
-		$inputPath = $input->getOption('path');
175
-		if ($inputPath) {
176
-			$inputPath = '/' . trim($inputPath, '/');
177
-			list(, $user,) = explode('/', $inputPath, 3);
178
-			$users = [$user];
179
-		} elseif ($input->getOption('all')) {
180
-			$users = $this->userManager->search('');
181
-		} else {
182
-			$users = $input->getArgument('user_id');
183
-		}
184
-
185
-		# restrict the verbosity level to VERBOSITY_VERBOSE
186
-		if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
187
-			$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
188
-		}
189
-
190
-		# check quantity of users to be process and show it on the command line
191
-		$users_total = count($users);
192
-		if ($users_total === 0) {
193
-			$output->writeln('<error>Please specify the user id to scan, --all to scan for all users or --path=...</error>');
194
-			return 1;
195
-		}
196
-
197
-		$this->initTools();
198
-
199
-		$user_count = 0;
200
-		foreach ($users as $user) {
201
-			if (is_object($user)) {
202
-				$user = $user->getUID();
203
-			}
204
-			$path = $inputPath ? $inputPath : '/' . $user;
205
-			++$user_count;
206
-			if ($this->userManager->userExists($user)) {
207
-				$output->writeln("Starting scan for user $user_count out of $users_total ($user)");
208
-				$this->scanFiles($user, $path, $output, $input->getOption('unscanned'), !$input->getOption('shallow'), $input->getOption('home-only'));
209
-				$output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
210
-			} else {
211
-				$output->writeln("<error>Unknown user $user_count $user</error>");
212
-				$output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
213
-			}
214
-
215
-			try {
216
-				$this->abortIfInterrupted();
217
-			} catch (InterruptedException $e) {
218
-				break;
219
-			}
220
-		}
221
-
222
-		$this->presentStats($output);
223
-		return 0;
224
-	}
225
-
226
-	/**
227
-	 * Initialises some useful tools for the Command
228
-	 */
229
-	protected function initTools() {
230
-		// Start the timer
231
-		$this->execTime = -microtime(true);
232
-		// Convert PHP errors to exceptions
233
-		set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
234
-	}
235
-
236
-	/**
237
-	 * Processes PHP errors as exceptions in order to be able to keep track of problems
238
-	 *
239
-	 * @see https://www.php.net/manual/en/function.set-error-handler.php
240
-	 *
241
-	 * @param int $severity the level of the error raised
242
-	 * @param string $message
243
-	 * @param string $file the filename that the error was raised in
244
-	 * @param int $line the line number the error was raised
245
-	 *
246
-	 * @throws \ErrorException
247
-	 */
248
-	public function exceptionErrorHandler($severity, $message, $file, $line) {
249
-		if (!(error_reporting() & $severity)) {
250
-			// This error code is not included in error_reporting
251
-			return;
252
-		}
253
-		throw new \ErrorException($message, 0, $severity, $file, $line);
254
-	}
255
-
256
-	/**
257
-	 * @param OutputInterface $output
258
-	 */
259
-	protected function presentStats(OutputInterface $output) {
260
-		// Stop the timer
261
-		$this->execTime += microtime(true);
262
-
263
-		$headers = [
264
-			'Folders', 'Files', 'Elapsed time'
265
-		];
266
-
267
-		$this->showSummary($headers, null, $output);
268
-	}
269
-
270
-	/**
271
-	 * Shows a summary of operations
272
-	 *
273
-	 * @param string[] $headers
274
-	 * @param string[] $rows
275
-	 * @param OutputInterface $output
276
-	 */
277
-	protected function showSummary($headers, $rows, OutputInterface $output) {
278
-		$niceDate = $this->formatExecTime();
279
-		if (!$rows) {
280
-			$rows = [
281
-				$this->foldersCounter,
282
-				$this->filesCounter,
283
-				$niceDate,
284
-			];
285
-		}
286
-		$table = new Table($output);
287
-		$table
288
-			->setHeaders($headers)
289
-			->setRows([$rows]);
290
-		$table->render();
291
-	}
292
-
293
-
294
-	/**
295
-	 * Formats microtime into a human readable format
296
-	 *
297
-	 * @return string
298
-	 */
299
-	protected function formatExecTime() {
300
-		$secs = round($this->execTime);
301
-		# convert seconds into HH:MM:SS form
302
-		return sprintf('%02d:%02d:%02d', ($secs / 3600), ($secs / 60 % 60), $secs % 60);
303
-	}
304
-
305
-	/**
306
-	 * @return \OCP\IDBConnection
307
-	 */
308
-	protected function reconnectToDatabase(OutputInterface $output) {
309
-		/** @var Connection | IDBConnection $connection */
310
-		$connection = \OC::$server->getDatabaseConnection();
311
-		try {
312
-			$connection->close();
313
-		} catch (\Exception $ex) {
314
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
315
-		}
316
-		while (!$connection->isConnected()) {
317
-			try {
318
-				$connection->connect();
319
-			} catch (\Exception $ex) {
320
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
321
-				sleep(60);
322
-			}
323
-		}
324
-		return $connection;
325
-	}
55
+    /** @var IUserManager $userManager */
56
+    private $userManager;
57
+    /** @var float */
58
+    protected $execTime = 0;
59
+    /** @var int */
60
+    protected $foldersCounter = 0;
61
+    /** @var int */
62
+    protected $filesCounter = 0;
63
+
64
+    public function __construct(IUserManager $userManager) {
65
+        $this->userManager = $userManager;
66
+        parent::__construct();
67
+    }
68
+
69
+    protected function configure() {
70
+        parent::configure();
71
+
72
+        $this
73
+            ->setName('files:scan')
74
+            ->setDescription('rescan filesystem')
75
+            ->addArgument(
76
+                'user_id',
77
+                InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
78
+                'will rescan all files of the given user(s)'
79
+            )
80
+            ->addOption(
81
+                'path',
82
+                'p',
83
+                InputArgument::OPTIONAL,
84
+                'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
85
+            )
86
+            ->addOption(
87
+                'all',
88
+                null,
89
+                InputOption::VALUE_NONE,
90
+                'will rescan all files of all known users'
91
+            )->addOption(
92
+                'unscanned',
93
+                null,
94
+                InputOption::VALUE_NONE,
95
+                'only scan files which are marked as not fully scanned'
96
+            )->addOption(
97
+                'shallow',
98
+                null,
99
+                InputOption::VALUE_NONE,
100
+                'do not scan folders recursively'
101
+            )->addOption(
102
+                'home-only',
103
+                null,
104
+                InputOption::VALUE_NONE,
105
+                'only scan the home storage, ignoring any mounted external storage or share'
106
+            );
107
+    }
108
+
109
+    public function checkScanWarning($fullPath, OutputInterface $output) {
110
+        $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
111
+        $path = basename($fullPath);
112
+
113
+        if ($normalizedPath !== $path) {
114
+            $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
115
+        }
116
+    }
117
+
118
+    protected function scanFiles($user, $path, OutputInterface $output, $backgroundScan = false, $recursive = true, $homeOnly = false) {
119
+        $connection = $this->reconnectToDatabase($output);
120
+        $scanner = new \OC\Files\Utils\Scanner($user, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
121
+
122
+        # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
123
+
124
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
125
+            $output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
126
+            ++$this->filesCounter;
127
+            $this->abortIfInterrupted();
128
+        });
129
+
130
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
131
+            $output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
132
+            ++$this->foldersCounter;
133
+            $this->abortIfInterrupted();
134
+        });
135
+
136
+        $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
137
+            $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
138
+        });
139
+
140
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
141
+            $this->checkScanWarning($path, $output);
142
+        });
143
+
144
+        $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
145
+            $this->checkScanWarning($path, $output);
146
+        });
147
+
148
+        try {
149
+            if ($backgroundScan) {
150
+                $scanner->backgroundScan($path);
151
+            } else {
152
+                $scanner->scan($path, $recursive, $homeOnly ? [$this, 'filterHomeMount'] : null);
153
+            }
154
+        } catch (ForbiddenException $e) {
155
+            $output->writeln("<error>Home storage for user $user not writable</error>");
156
+            $output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
157
+        } catch (InterruptedException $e) {
158
+            # exit the function if ctrl-c has been pressed
159
+            $output->writeln('Interrupted by user');
160
+        } catch (NotFoundException $e) {
161
+            $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
162
+        } catch (\Exception $e) {
163
+            $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
164
+            $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
165
+        }
166
+    }
167
+
168
+    public function filterHomeMount(IMountPoint $mountPoint) {
169
+        // any mountpoint inside '/$user/files/'
170
+        return substr_count($mountPoint->getMountPoint(), '/') <= 3;
171
+    }
172
+
173
+    protected function execute(InputInterface $input, OutputInterface $output): int {
174
+        $inputPath = $input->getOption('path');
175
+        if ($inputPath) {
176
+            $inputPath = '/' . trim($inputPath, '/');
177
+            list(, $user,) = explode('/', $inputPath, 3);
178
+            $users = [$user];
179
+        } elseif ($input->getOption('all')) {
180
+            $users = $this->userManager->search('');
181
+        } else {
182
+            $users = $input->getArgument('user_id');
183
+        }
184
+
185
+        # restrict the verbosity level to VERBOSITY_VERBOSE
186
+        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
187
+            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
188
+        }
189
+
190
+        # check quantity of users to be process and show it on the command line
191
+        $users_total = count($users);
192
+        if ($users_total === 0) {
193
+            $output->writeln('<error>Please specify the user id to scan, --all to scan for all users or --path=...</error>');
194
+            return 1;
195
+        }
196
+
197
+        $this->initTools();
198
+
199
+        $user_count = 0;
200
+        foreach ($users as $user) {
201
+            if (is_object($user)) {
202
+                $user = $user->getUID();
203
+            }
204
+            $path = $inputPath ? $inputPath : '/' . $user;
205
+            ++$user_count;
206
+            if ($this->userManager->userExists($user)) {
207
+                $output->writeln("Starting scan for user $user_count out of $users_total ($user)");
208
+                $this->scanFiles($user, $path, $output, $input->getOption('unscanned'), !$input->getOption('shallow'), $input->getOption('home-only'));
209
+                $output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
210
+            } else {
211
+                $output->writeln("<error>Unknown user $user_count $user</error>");
212
+                $output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
213
+            }
214
+
215
+            try {
216
+                $this->abortIfInterrupted();
217
+            } catch (InterruptedException $e) {
218
+                break;
219
+            }
220
+        }
221
+
222
+        $this->presentStats($output);
223
+        return 0;
224
+    }
225
+
226
+    /**
227
+     * Initialises some useful tools for the Command
228
+     */
229
+    protected function initTools() {
230
+        // Start the timer
231
+        $this->execTime = -microtime(true);
232
+        // Convert PHP errors to exceptions
233
+        set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
234
+    }
235
+
236
+    /**
237
+     * Processes PHP errors as exceptions in order to be able to keep track of problems
238
+     *
239
+     * @see https://www.php.net/manual/en/function.set-error-handler.php
240
+     *
241
+     * @param int $severity the level of the error raised
242
+     * @param string $message
243
+     * @param string $file the filename that the error was raised in
244
+     * @param int $line the line number the error was raised
245
+     *
246
+     * @throws \ErrorException
247
+     */
248
+    public function exceptionErrorHandler($severity, $message, $file, $line) {
249
+        if (!(error_reporting() & $severity)) {
250
+            // This error code is not included in error_reporting
251
+            return;
252
+        }
253
+        throw new \ErrorException($message, 0, $severity, $file, $line);
254
+    }
255
+
256
+    /**
257
+     * @param OutputInterface $output
258
+     */
259
+    protected function presentStats(OutputInterface $output) {
260
+        // Stop the timer
261
+        $this->execTime += microtime(true);
262
+
263
+        $headers = [
264
+            'Folders', 'Files', 'Elapsed time'
265
+        ];
266
+
267
+        $this->showSummary($headers, null, $output);
268
+    }
269
+
270
+    /**
271
+     * Shows a summary of operations
272
+     *
273
+     * @param string[] $headers
274
+     * @param string[] $rows
275
+     * @param OutputInterface $output
276
+     */
277
+    protected function showSummary($headers, $rows, OutputInterface $output) {
278
+        $niceDate = $this->formatExecTime();
279
+        if (!$rows) {
280
+            $rows = [
281
+                $this->foldersCounter,
282
+                $this->filesCounter,
283
+                $niceDate,
284
+            ];
285
+        }
286
+        $table = new Table($output);
287
+        $table
288
+            ->setHeaders($headers)
289
+            ->setRows([$rows]);
290
+        $table->render();
291
+    }
292
+
293
+
294
+    /**
295
+     * Formats microtime into a human readable format
296
+     *
297
+     * @return string
298
+     */
299
+    protected function formatExecTime() {
300
+        $secs = round($this->execTime);
301
+        # convert seconds into HH:MM:SS form
302
+        return sprintf('%02d:%02d:%02d', ($secs / 3600), ($secs / 60 % 60), $secs % 60);
303
+    }
304
+
305
+    /**
306
+     * @return \OCP\IDBConnection
307
+     */
308
+    protected function reconnectToDatabase(OutputInterface $output) {
309
+        /** @var Connection | IDBConnection $connection */
310
+        $connection = \OC::$server->getDatabaseConnection();
311
+        try {
312
+            $connection->close();
313
+        } catch (\Exception $ex) {
314
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
315
+        }
316
+        while (!$connection->isConnected()) {
317
+            try {
318
+                $connection->connect();
319
+            } catch (\Exception $ex) {
320
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
321
+                sleep(60);
322
+            }
323
+        }
324
+        return $connection;
325
+    }
326 326
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/ILDAPWrapper.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -31,185 +31,185 @@
 block discarded – undo
31 31
 
32 32
 interface ILDAPWrapper {
33 33
 
34
-	//LDAP functions in use
35
-
36
-	/**
37
-	 * Bind to LDAP directory
38
-	 * @param resource $link LDAP link resource
39
-	 * @param string $dn an RDN to log in with
40
-	 * @param string $password the password
41
-	 * @return bool true on success, false otherwise
42
-	 *
43
-	 * with $dn and $password as null a anonymous bind is attempted.
44
-	 */
45
-	public function bind($link, $dn, $password);
46
-
47
-	/**
48
-	 * connect to an LDAP server
49
-	 * @param string $host The host to connect to
50
-	 * @param string $port The port to connect to
51
-	 * @return mixed a link resource on success, otherwise false
52
-	 */
53
-	public function connect($host, $port);
54
-
55
-	/**
56
-	 * Send LDAP pagination control
57
-	 * @param resource $link LDAP link resource
58
-	 * @param int $pageSize number of results per page
59
-	 * @param bool $isCritical Indicates whether the pagination is critical of not.
60
-	 * @param string $cookie structure sent by LDAP server
61
-	 * @return bool true on success, false otherwise
62
-	 */
63
-	public function controlPagedResult($link, $pageSize, $isCritical);
64
-
65
-	/**
66
-	 * Retrieve the LDAP pagination cookie
67
-	 * @param resource $link LDAP link resource
68
-	 * @param resource $result LDAP result resource
69
-	 * @param string $cookie structure sent by LDAP server
70
-	 * @return bool true on success, false otherwise
71
-	 *
72
-	 * Corresponds to ldap_control_paged_result_response
73
-	 */
74
-	public function controlPagedResultResponse($link, $result, &$cookie);
75
-
76
-	/**
77
-	 * Count the number of entries in a search
78
-	 * @param resource $link LDAP link resource
79
-	 * @param resource $result LDAP result resource
80
-	 * @return int|false number of results on success, false otherwise
81
-	 */
82
-	public function countEntries($link, $result);
83
-
84
-	/**
85
-	 * Return the LDAP error number of the last LDAP command
86
-	 * @param resource $link LDAP link resource
87
-	 * @return int error code
88
-	 */
89
-	public function errno($link);
90
-
91
-	/**
92
-	 * Return the LDAP error message of the last LDAP command
93
-	 * @param resource $link LDAP link resource
94
-	 * @return string error message
95
-	 */
96
-	public function error($link);
97
-
98
-	/**
99
-	 * Splits DN into its component parts
100
-	 * @param string $dn
101
-	 * @param int @withAttrib
102
-	 * @return array|false
103
-	 * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
104
-	 */
105
-	public function explodeDN($dn, $withAttrib);
106
-
107
-	/**
108
-	 * Return first result id
109
-	 * @param resource $link LDAP link resource
110
-	 * @param resource $result LDAP result resource
111
-	 * @return Resource an LDAP search result resource
112
-	 * */
113
-	public function firstEntry($link, $result);
114
-
115
-	/**
116
-	 * Get attributes from a search result entry
117
-	 * @param resource $link LDAP link resource
118
-	 * @param resource $result LDAP result resource
119
-	 * @return array containing the results, false on error
120
-	 * */
121
-	public function getAttributes($link, $result);
122
-
123
-	/**
124
-	 * Get the DN of a result entry
125
-	 * @param resource $link LDAP link resource
126
-	 * @param resource $result LDAP result resource
127
-	 * @return string containing the DN, false on error
128
-	 */
129
-	public function getDN($link, $result);
130
-
131
-	/**
132
-	 * Get all result entries
133
-	 * @param resource $link LDAP link resource
134
-	 * @param resource $result LDAP result resource
135
-	 * @return array containing the results, false on error
136
-	 */
137
-	public function getEntries($link, $result);
138
-
139
-	/**
140
-	 * Return next result id
141
-	 * @param resource $link LDAP link resource
142
-	 * @param resource $result LDAP entry result resource
143
-	 * @return resource an LDAP search result resource
144
-	 * */
145
-	public function nextEntry($link, $result);
146
-
147
-	/**
148
-	 * Read an entry
149
-	 * @param resource $link LDAP link resource
150
-	 * @param array $baseDN The DN of the entry to read from
151
-	 * @param string $filter An LDAP filter
152
-	 * @param array $attr array of the attributes to read
153
-	 * @return resource an LDAP search result resource
154
-	 */
155
-	public function read($link, $baseDN, $filter, $attr);
156
-
157
-	/**
158
-	 * Search LDAP tree
159
-	 * @param resource $link LDAP link resource
160
-	 * @param string $baseDN The DN of the entry to read from
161
-	 * @param string $filter An LDAP filter
162
-	 * @param array $attr array of the attributes to read
163
-	 * @param int $attrsOnly optional, 1 if only attribute types shall be returned
164
-	 * @param int $limit optional, limits the result entries
165
-	 * @return resource|false an LDAP search result resource, false on error
166
-	 */
167
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0);
168
-
169
-	/**
170
-	 * Replace the value of a userPassword by $password
171
-	 * @param resource $link LDAP link resource
172
-	 * @param string $userDN the DN of the user whose password is to be replaced
173
-	 * @param string $password the new value for the userPassword
174
-	 * @return bool true on success, false otherwise
175
-	 */
176
-	public function modReplace($link, $userDN, $password);
177
-
178
-	/**
179
-	 * Sets the value of the specified option to be $value
180
-	 * @param resource $link LDAP link resource
181
-	 * @param string $option a defined LDAP Server option
182
-	 * @param int $value the new value for the option
183
-	 * @return bool true on success, false otherwise
184
-	 */
185
-	public function setOption($link, $option, $value);
186
-
187
-	/**
188
-	 * establish Start TLS
189
-	 * @param resource $link LDAP link resource
190
-	 * @return bool true on success, false otherwise
191
-	 */
192
-	public function startTls($link);
193
-
194
-	/**
195
-	 * Unbind from LDAP directory
196
-	 * @param resource $link LDAP link resource
197
-	 * @return bool true on success, false otherwise
198
-	 */
199
-	public function unbind($link);
200
-
201
-	//additional required methods in Nextcloud
202
-
203
-	/**
204
-	 * Checks whether the server supports LDAP
205
-	 * @return bool true if it the case, false otherwise
206
-	 * */
207
-	public function areLDAPFunctionsAvailable();
208
-
209
-	/**
210
-	 * Checks whether the submitted parameter is a resource
211
-	 * @param resource $resource the resource variable to check
212
-	 * @return bool true if it is a resource, false otherwise
213
-	 */
214
-	public function isResource($resource);
34
+    //LDAP functions in use
35
+
36
+    /**
37
+     * Bind to LDAP directory
38
+     * @param resource $link LDAP link resource
39
+     * @param string $dn an RDN to log in with
40
+     * @param string $password the password
41
+     * @return bool true on success, false otherwise
42
+     *
43
+     * with $dn and $password as null a anonymous bind is attempted.
44
+     */
45
+    public function bind($link, $dn, $password);
46
+
47
+    /**
48
+     * connect to an LDAP server
49
+     * @param string $host The host to connect to
50
+     * @param string $port The port to connect to
51
+     * @return mixed a link resource on success, otherwise false
52
+     */
53
+    public function connect($host, $port);
54
+
55
+    /**
56
+     * Send LDAP pagination control
57
+     * @param resource $link LDAP link resource
58
+     * @param int $pageSize number of results per page
59
+     * @param bool $isCritical Indicates whether the pagination is critical of not.
60
+     * @param string $cookie structure sent by LDAP server
61
+     * @return bool true on success, false otherwise
62
+     */
63
+    public function controlPagedResult($link, $pageSize, $isCritical);
64
+
65
+    /**
66
+     * Retrieve the LDAP pagination cookie
67
+     * @param resource $link LDAP link resource
68
+     * @param resource $result LDAP result resource
69
+     * @param string $cookie structure sent by LDAP server
70
+     * @return bool true on success, false otherwise
71
+     *
72
+     * Corresponds to ldap_control_paged_result_response
73
+     */
74
+    public function controlPagedResultResponse($link, $result, &$cookie);
75
+
76
+    /**
77
+     * Count the number of entries in a search
78
+     * @param resource $link LDAP link resource
79
+     * @param resource $result LDAP result resource
80
+     * @return int|false number of results on success, false otherwise
81
+     */
82
+    public function countEntries($link, $result);
83
+
84
+    /**
85
+     * Return the LDAP error number of the last LDAP command
86
+     * @param resource $link LDAP link resource
87
+     * @return int error code
88
+     */
89
+    public function errno($link);
90
+
91
+    /**
92
+     * Return the LDAP error message of the last LDAP command
93
+     * @param resource $link LDAP link resource
94
+     * @return string error message
95
+     */
96
+    public function error($link);
97
+
98
+    /**
99
+     * Splits DN into its component parts
100
+     * @param string $dn
101
+     * @param int @withAttrib
102
+     * @return array|false
103
+     * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
104
+     */
105
+    public function explodeDN($dn, $withAttrib);
106
+
107
+    /**
108
+     * Return first result id
109
+     * @param resource $link LDAP link resource
110
+     * @param resource $result LDAP result resource
111
+     * @return Resource an LDAP search result resource
112
+     * */
113
+    public function firstEntry($link, $result);
114
+
115
+    /**
116
+     * Get attributes from a search result entry
117
+     * @param resource $link LDAP link resource
118
+     * @param resource $result LDAP result resource
119
+     * @return array containing the results, false on error
120
+     * */
121
+    public function getAttributes($link, $result);
122
+
123
+    /**
124
+     * Get the DN of a result entry
125
+     * @param resource $link LDAP link resource
126
+     * @param resource $result LDAP result resource
127
+     * @return string containing the DN, false on error
128
+     */
129
+    public function getDN($link, $result);
130
+
131
+    /**
132
+     * Get all result entries
133
+     * @param resource $link LDAP link resource
134
+     * @param resource $result LDAP result resource
135
+     * @return array containing the results, false on error
136
+     */
137
+    public function getEntries($link, $result);
138
+
139
+    /**
140
+     * Return next result id
141
+     * @param resource $link LDAP link resource
142
+     * @param resource $result LDAP entry result resource
143
+     * @return resource an LDAP search result resource
144
+     * */
145
+    public function nextEntry($link, $result);
146
+
147
+    /**
148
+     * Read an entry
149
+     * @param resource $link LDAP link resource
150
+     * @param array $baseDN The DN of the entry to read from
151
+     * @param string $filter An LDAP filter
152
+     * @param array $attr array of the attributes to read
153
+     * @return resource an LDAP search result resource
154
+     */
155
+    public function read($link, $baseDN, $filter, $attr);
156
+
157
+    /**
158
+     * Search LDAP tree
159
+     * @param resource $link LDAP link resource
160
+     * @param string $baseDN The DN of the entry to read from
161
+     * @param string $filter An LDAP filter
162
+     * @param array $attr array of the attributes to read
163
+     * @param int $attrsOnly optional, 1 if only attribute types shall be returned
164
+     * @param int $limit optional, limits the result entries
165
+     * @return resource|false an LDAP search result resource, false on error
166
+     */
167
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0);
168
+
169
+    /**
170
+     * Replace the value of a userPassword by $password
171
+     * @param resource $link LDAP link resource
172
+     * @param string $userDN the DN of the user whose password is to be replaced
173
+     * @param string $password the new value for the userPassword
174
+     * @return bool true on success, false otherwise
175
+     */
176
+    public function modReplace($link, $userDN, $password);
177
+
178
+    /**
179
+     * Sets the value of the specified option to be $value
180
+     * @param resource $link LDAP link resource
181
+     * @param string $option a defined LDAP Server option
182
+     * @param int $value the new value for the option
183
+     * @return bool true on success, false otherwise
184
+     */
185
+    public function setOption($link, $option, $value);
186
+
187
+    /**
188
+     * establish Start TLS
189
+     * @param resource $link LDAP link resource
190
+     * @return bool true on success, false otherwise
191
+     */
192
+    public function startTls($link);
193
+
194
+    /**
195
+     * Unbind from LDAP directory
196
+     * @param resource $link LDAP link resource
197
+     * @return bool true on success, false otherwise
198
+     */
199
+    public function unbind($link);
200
+
201
+    //additional required methods in Nextcloud
202
+
203
+    /**
204
+     * Checks whether the server supports LDAP
205
+     * @return bool true if it the case, false otherwise
206
+     * */
207
+    public function areLDAPFunctionsAvailable();
208
+
209
+    /**
210
+     * Checks whether the submitted parameter is a resource
211
+     * @param resource $resource the resource variable to check
212
+     * @return bool true if it is a resource, false otherwise
213
+     */
214
+    public function isResource($resource);
215 215
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Access.php 1 patch
Indentation   +1975 added lines, -1975 removed lines patch added patch discarded remove patch
@@ -65,1762 +65,1762 @@  discard block
 block discarded – undo
65 65
  * @package OCA\User_LDAP
66 66
  */
67 67
 class Access extends LDAPUtility {
68
-	public const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
69
-
70
-	/** @var \OCA\User_LDAP\Connection */
71
-	public $connection;
72
-	/** @var Manager */
73
-	public $userManager;
74
-	//never ever check this var directly, always use getPagedSearchResultState
75
-	protected $pagedSearchedSuccessful;
76
-
77
-	/**
78
-	 * @var UserMapping $userMapper
79
-	 */
80
-	protected $userMapper;
81
-
82
-	/**
83
-	 * @var AbstractMapping $userMapper
84
-	 */
85
-	protected $groupMapper;
86
-
87
-	/**
88
-	 * @var \OCA\User_LDAP\Helper
89
-	 */
90
-	private $helper;
91
-	/** @var IConfig */
92
-	private $config;
93
-	/** @var IUserManager */
94
-	private $ncUserManager;
95
-	/** @var string */
96
-	private $lastCookie = '';
97
-
98
-	public function __construct(
99
-		Connection $connection,
100
-		ILDAPWrapper $ldap,
101
-		Manager $userManager,
102
-		Helper $helper,
103
-		IConfig $config,
104
-		IUserManager $ncUserManager
105
-	) {
106
-		parent::__construct($ldap);
107
-		$this->connection = $connection;
108
-		$this->userManager = $userManager;
109
-		$this->userManager->setLdapAccess($this);
110
-		$this->helper = $helper;
111
-		$this->config = $config;
112
-		$this->ncUserManager = $ncUserManager;
113
-	}
114
-
115
-	/**
116
-	 * sets the User Mapper
117
-	 *
118
-	 * @param AbstractMapping $mapper
119
-	 */
120
-	public function setUserMapper(AbstractMapping $mapper) {
121
-		$this->userMapper = $mapper;
122
-	}
123
-
124
-	/**
125
-	 * @throws \Exception
126
-	 */
127
-	public function getUserMapper(): UserMapping {
128
-		if (is_null($this->userMapper)) {
129
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
130
-		}
131
-		return $this->userMapper;
132
-	}
133
-
134
-	/**
135
-	 * sets the Group Mapper
136
-	 *
137
-	 * @param AbstractMapping $mapper
138
-	 */
139
-	public function setGroupMapper(AbstractMapping $mapper) {
140
-		$this->groupMapper = $mapper;
141
-	}
142
-
143
-	/**
144
-	 * returns the Group Mapper
145
-	 *
146
-	 * @return AbstractMapping
147
-	 * @throws \Exception
148
-	 */
149
-	public function getGroupMapper() {
150
-		if (is_null($this->groupMapper)) {
151
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
152
-		}
153
-		return $this->groupMapper;
154
-	}
155
-
156
-	/**
157
-	 * @return bool
158
-	 */
159
-	private function checkConnection() {
160
-		return ($this->connection instanceof Connection);
161
-	}
162
-
163
-	/**
164
-	 * returns the Connection instance
165
-	 *
166
-	 * @return \OCA\User_LDAP\Connection
167
-	 */
168
-	public function getConnection() {
169
-		return $this->connection;
170
-	}
171
-
172
-	/**
173
-	 * reads a given attribute for an LDAP record identified by a DN
174
-	 *
175
-	 * @param string $dn the record in question
176
-	 * @param string $attr the attribute that shall be retrieved
177
-	 *        if empty, just check the record's existence
178
-	 * @param string $filter
179
-	 * @return array|false an array of values on success or an empty
180
-	 *          array if $attr is empty, false otherwise
181
-	 * @throws ServerNotAvailableException
182
-	 */
183
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
184
-		if (!$this->checkConnection()) {
185
-			\OCP\Util::writeLog('user_ldap',
186
-				'No LDAP Connector assigned, access impossible for readAttribute.',
187
-				ILogger::WARN);
188
-			return false;
189
-		}
190
-		$cr = $this->connection->getConnectionResource();
191
-		if (!$this->ldap->isResource($cr)) {
192
-			//LDAP not available
193
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
194
-			return false;
195
-		}
196
-		//Cancel possibly running Paged Results operation, otherwise we run in
197
-		//LDAP protocol errors
198
-		$this->abandonPagedSearch();
199
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
200
-		// but does not hurt either.
201
-		$pagingSize = (int)$this->connection->ldapPagingSize;
202
-		// 0 won't result in replies, small numbers may leave out groups
203
-		// (cf. #12306), 500 is default for paging and should work everywhere.
204
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
205
-		$attr = mb_strtolower($attr, 'UTF-8');
206
-		// the actual read attribute later may contain parameters on a ranged
207
-		// request, e.g. member;range=99-199. Depends on server reply.
208
-		$attrToRead = $attr;
209
-
210
-		$values = [];
211
-		$isRangeRequest = false;
212
-		do {
213
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
214
-			if (is_bool($result)) {
215
-				// when an exists request was run and it was successful, an empty
216
-				// array must be returned
217
-				return $result ? [] : false;
218
-			}
219
-
220
-			if (!$isRangeRequest) {
221
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
222
-				if (!empty($values)) {
223
-					return $values;
224
-				}
225
-			}
226
-
227
-			$isRangeRequest = false;
228
-			$result = $this->extractRangeData($result, $attr);
229
-			if (!empty($result)) {
230
-				$normalizedResult = $this->extractAttributeValuesFromResult(
231
-					[$attr => $result['values']],
232
-					$attr
233
-				);
234
-				$values = array_merge($values, $normalizedResult);
235
-
236
-				if ($result['rangeHigh'] === '*') {
237
-					// when server replies with * as high range value, there are
238
-					// no more results left
239
-					return $values;
240
-				} else {
241
-					$low = $result['rangeHigh'] + 1;
242
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
243
-					$isRangeRequest = true;
244
-				}
245
-			}
246
-		} while ($isRangeRequest);
247
-
248
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, ILogger::DEBUG);
249
-		return false;
250
-	}
251
-
252
-	/**
253
-	 * Runs an read operation against LDAP
254
-	 *
255
-	 * @param resource $cr the LDAP connection
256
-	 * @param string $dn
257
-	 * @param string $attribute
258
-	 * @param string $filter
259
-	 * @param int $maxResults
260
-	 * @return array|bool false if there was any error, true if an exists check
261
-	 *                    was performed and the requested DN found, array with the
262
-	 *                    returned data on a successful usual operation
263
-	 * @throws ServerNotAvailableException
264
-	 */
265
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
266
-		$this->initPagedSearch($filter, $dn, [$attribute], $maxResults, 0);
267
-		$dn = $this->helper->DNasBaseParameter($dn);
268
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
269
-		if (!$this->ldap->isResource($rr)) {
270
-			if ($attribute !== '') {
271
-				//do not throw this message on userExists check, irritates
272
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
273
-			}
274
-			//in case an error occurs , e.g. object does not exist
275
-			return false;
276
-		}
277
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
278
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
279
-			return true;
280
-		}
281
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
282
-		if (!$this->ldap->isResource($er)) {
283
-			//did not match the filter, return false
284
-			return false;
285
-		}
286
-		//LDAP attributes are not case sensitive
287
-		$result = \OCP\Util::mb_array_change_key_case(
288
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
289
-
290
-		return $result;
291
-	}
292
-
293
-	/**
294
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
295
-	 * data if present.
296
-	 *
297
-	 * @param array $result from ILDAPWrapper::getAttributes()
298
-	 * @param string $attribute the attribute name that was read
299
-	 * @return string[]
300
-	 */
301
-	public function extractAttributeValuesFromResult($result, $attribute) {
302
-		$values = [];
303
-		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
304
-			$lowercaseAttribute = strtolower($attribute);
305
-			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
306
-				if ($this->resemblesDN($attribute)) {
307
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
308
-				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
309
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
310
-				} else {
311
-					$values[] = $result[$attribute][$i];
312
-				}
313
-			}
314
-		}
315
-		return $values;
316
-	}
317
-
318
-	/**
319
-	 * Attempts to find ranged data in a getAttribute results and extracts the
320
-	 * returned values as well as information on the range and full attribute
321
-	 * name for further processing.
322
-	 *
323
-	 * @param array $result from ILDAPWrapper::getAttributes()
324
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
325
-	 * @return array If a range was detected with keys 'values', 'attributeName',
326
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
327
-	 */
328
-	public function extractRangeData($result, $attribute) {
329
-		$keys = array_keys($result);
330
-		foreach ($keys as $key) {
331
-			if ($key !== $attribute && strpos($key, $attribute) === 0) {
332
-				$queryData = explode(';', $key);
333
-				if (strpos($queryData[1], 'range=') === 0) {
334
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
335
-					$data = [
336
-						'values' => $result[$key],
337
-						'attributeName' => $queryData[0],
338
-						'attributeFull' => $key,
339
-						'rangeHigh' => $high,
340
-					];
341
-					return $data;
342
-				}
343
-			}
344
-		}
345
-		return [];
346
-	}
347
-
348
-	/**
349
-	 * Set password for an LDAP user identified by a DN
350
-	 *
351
-	 * @param string $userDN the user in question
352
-	 * @param string $password the new password
353
-	 * @return bool
354
-	 * @throws HintException
355
-	 * @throws \Exception
356
-	 */
357
-	public function setPassword($userDN, $password) {
358
-		if ((int)$this->connection->turnOnPasswordChange !== 1) {
359
-			throw new \Exception('LDAP password changes are disabled.');
360
-		}
361
-		$cr = $this->connection->getConnectionResource();
362
-		if (!$this->ldap->isResource($cr)) {
363
-			//LDAP not available
364
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
365
-			return false;
366
-		}
367
-		try {
368
-			// try PASSWD extended operation first
369
-			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
370
-				@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
371
-		} catch (ConstraintViolationException $e) {
372
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ') . $e->getMessage(), $e->getCode());
373
-		}
374
-	}
375
-
376
-	/**
377
-	 * checks whether the given attributes value is probably a DN
378
-	 *
379
-	 * @param string $attr the attribute in question
380
-	 * @return boolean if so true, otherwise false
381
-	 */
382
-	private function resemblesDN($attr) {
383
-		$resemblingAttributes = [
384
-			'dn',
385
-			'uniquemember',
386
-			'member',
387
-			// memberOf is an "operational" attribute, without a definition in any RFC
388
-			'memberof'
389
-		];
390
-		return in_array($attr, $resemblingAttributes);
391
-	}
392
-
393
-	/**
394
-	 * checks whether the given string is probably a DN
395
-	 *
396
-	 * @param string $string
397
-	 * @return boolean
398
-	 */
399
-	public function stringResemblesDN($string) {
400
-		$r = $this->ldap->explodeDN($string, 0);
401
-		// if exploding a DN succeeds and does not end up in
402
-		// an empty array except for $r[count] being 0.
403
-		return (is_array($r) && count($r) > 1);
404
-	}
405
-
406
-	/**
407
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
408
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
409
-	 * becomes dc=foobar,dc=server,dc=org
410
-	 *
411
-	 * @param string $dn
412
-	 * @return string
413
-	 */
414
-	public function getDomainDNFromDN($dn) {
415
-		$allParts = $this->ldap->explodeDN($dn, 0);
416
-		if ($allParts === false) {
417
-			//not a valid DN
418
-			return '';
419
-		}
420
-		$domainParts = [];
421
-		$dcFound = false;
422
-		foreach ($allParts as $part) {
423
-			if (!$dcFound && strpos($part, 'dc=') === 0) {
424
-				$dcFound = true;
425
-			}
426
-			if ($dcFound) {
427
-				$domainParts[] = $part;
428
-			}
429
-		}
430
-		return implode(',', $domainParts);
431
-	}
432
-
433
-	/**
434
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
435
-	 *
436
-	 * @param string $name the Nextcloud name in question
437
-	 * @return string|false LDAP DN on success, otherwise false
438
-	 */
439
-	public function groupname2dn($name) {
440
-		return $this->groupMapper->getDNByName($name);
441
-	}
442
-
443
-	/**
444
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
445
-	 *
446
-	 * @param string $name the Nextcloud name in question
447
-	 * @return string|false with the LDAP DN on success, otherwise false
448
-	 */
449
-	public function username2dn($name) {
450
-		$fdn = $this->userMapper->getDNByName($name);
451
-
452
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
453
-		//server setups
454
-		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
455
-			return $fdn;
456
-		}
457
-
458
-		return false;
459
-	}
460
-
461
-	/**
462
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
463
-	 *
464
-	 * @param string $fdn the dn of the group object
465
-	 * @param string $ldapName optional, the display name of the object
466
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
467
-	 * @throws \Exception
468
-	 */
469
-	public function dn2groupname($fdn, $ldapName = null) {
470
-		//To avoid bypassing the base DN settings under certain circumstances
471
-		//with the group support, check whether the provided DN matches one of
472
-		//the given Bases
473
-		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
474
-			return false;
475
-		}
476
-
477
-		return $this->dn2ocname($fdn, $ldapName, false);
478
-	}
479
-
480
-	/**
481
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
482
-	 *
483
-	 * @param string $dn the dn of the user object
484
-	 * @param string $ldapName optional, the display name of the object
485
-	 * @return string|false with with the name to use in Nextcloud
486
-	 * @throws \Exception
487
-	 */
488
-	public function dn2username($fdn, $ldapName = null) {
489
-		//To avoid bypassing the base DN settings under certain circumstances
490
-		//with the group support, check whether the provided DN matches one of
491
-		//the given Bases
492
-		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
493
-			return false;
494
-		}
495
-
496
-		return $this->dn2ocname($fdn, $ldapName, true);
497
-	}
498
-
499
-	/**
500
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
501
-	 *
502
-	 * @param string $fdn the dn of the user object
503
-	 * @param string|null $ldapName optional, the display name of the object
504
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
505
-	 * @param bool|null $newlyMapped
506
-	 * @param array|null $record
507
-	 * @return false|string with with the name to use in Nextcloud
508
-	 * @throws \Exception
509
-	 */
510
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
511
-		$newlyMapped = false;
512
-		if ($isUser) {
513
-			$mapper = $this->getUserMapper();
514
-			$nameAttribute = $this->connection->ldapUserDisplayName;
515
-			$filter = $this->connection->ldapUserFilter;
516
-		} else {
517
-			$mapper = $this->getGroupMapper();
518
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
519
-			$filter = $this->connection->ldapGroupFilter;
520
-		}
521
-
522
-		//let's try to retrieve the Nextcloud name from the mappings table
523
-		$ncName = $mapper->getNameByDN($fdn);
524
-		if (is_string($ncName)) {
525
-			return $ncName;
526
-		}
527
-
528
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
529
-		$uuid = $this->getUUID($fdn, $isUser, $record);
530
-		if (is_string($uuid)) {
531
-			$ncName = $mapper->getNameByUUID($uuid);
532
-			if (is_string($ncName)) {
533
-				$mapper->setDNbyUUID($fdn, $uuid);
534
-				return $ncName;
535
-			}
536
-		} else {
537
-			//If the UUID can't be detected something is foul.
538
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for ' . $fdn . '. Skipping.', ILogger::INFO);
539
-			return false;
540
-		}
541
-
542
-		if (is_null($ldapName)) {
543
-			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
544
-			if (!isset($ldapName[0]) && empty($ldapName[0])) {
545
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for ' . $fdn . ' with filter ' . $filter . '.', ILogger::INFO);
546
-				return false;
547
-			}
548
-			$ldapName = $ldapName[0];
549
-		}
550
-
551
-		if ($isUser) {
552
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
553
-			if ($usernameAttribute !== '') {
554
-				$username = $this->readAttribute($fdn, $usernameAttribute);
555
-				$username = $username[0];
556
-			} else {
557
-				$username = $uuid;
558
-			}
559
-			try {
560
-				$intName = $this->sanitizeUsername($username);
561
-			} catch (\InvalidArgumentException $e) {
562
-				\OC::$server->getLogger()->logException($e, [
563
-					'app' => 'user_ldap',
564
-					'level' => ILogger::WARN,
565
-				]);
566
-				// we don't attempt to set a username here. We can go for
567
-				// for an alternative 4 digit random number as we would append
568
-				// otherwise, however it's likely not enough space in bigger
569
-				// setups, and most importantly: this is not intended.
570
-				return false;
571
-			}
572
-		} else {
573
-			$intName = $ldapName;
574
-		}
575
-
576
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
577
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
578
-		//NOTE: mind, disabling cache affects only this instance! Using it
579
-		// outside of core user management will still cache the user as non-existing.
580
-		$originalTTL = $this->connection->ldapCacheTTL;
581
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
582
-		if ($intName !== ''
583
-			&& (($isUser && !$this->ncUserManager->userExists($intName))
584
-				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
585
-			)
586
-		) {
587
-			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
588
-			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
589
-			if ($newlyMapped) {
590
-				return $intName;
591
-			}
592
-		}
593
-
594
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
595
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
596
-		if (is_string($altName)) {
597
-			if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
598
-				$newlyMapped = true;
599
-				return $altName;
600
-			}
601
-		}
602
-
603
-		//if everything else did not help..
604
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for ' . $fdn . '.', ILogger::INFO);
605
-		return false;
606
-	}
607
-
608
-	public function mapAndAnnounceIfApplicable(
609
-		AbstractMapping $mapper,
610
-		string $fdn,
611
-		string $name,
612
-		string $uuid,
613
-		bool $isUser
614
-	): bool {
615
-		if ($mapper->map($fdn, $name, $uuid)) {
616
-			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
617
-				$this->cacheUserExists($name);
618
-				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
619
-			} elseif (!$isUser) {
620
-				$this->cacheGroupExists($name);
621
-			}
622
-			return true;
623
-		}
624
-		return false;
625
-	}
626
-
627
-	/**
628
-	 * gives back the user names as they are used ownClod internally
629
-	 *
630
-	 * @param array $ldapUsers as returned by fetchList()
631
-	 * @return array an array with the user names to use in Nextcloud
632
-	 *
633
-	 * gives back the user names as they are used ownClod internally
634
-	 * @throws \Exception
635
-	 */
636
-	public function nextcloudUserNames($ldapUsers) {
637
-		return $this->ldap2NextcloudNames($ldapUsers, true);
638
-	}
639
-
640
-	/**
641
-	 * gives back the group names as they are used ownClod internally
642
-	 *
643
-	 * @param array $ldapGroups as returned by fetchList()
644
-	 * @return array an array with the group names to use in Nextcloud
645
-	 *
646
-	 * gives back the group names as they are used ownClod internally
647
-	 * @throws \Exception
648
-	 */
649
-	public function nextcloudGroupNames($ldapGroups) {
650
-		return $this->ldap2NextcloudNames($ldapGroups, false);
651
-	}
652
-
653
-	/**
654
-	 * @param array $ldapObjects as returned by fetchList()
655
-	 * @param bool $isUsers
656
-	 * @return array
657
-	 * @throws \Exception
658
-	 */
659
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
660
-		if ($isUsers) {
661
-			$nameAttribute = $this->connection->ldapUserDisplayName;
662
-			$sndAttribute = $this->connection->ldapUserDisplayName2;
663
-		} else {
664
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
665
-		}
666
-		$nextcloudNames = [];
667
-
668
-		foreach ($ldapObjects as $ldapObject) {
669
-			$nameByLDAP = null;
670
-			if (isset($ldapObject[$nameAttribute])
671
-				&& is_array($ldapObject[$nameAttribute])
672
-				&& isset($ldapObject[$nameAttribute][0])
673
-			) {
674
-				// might be set, but not necessarily. if so, we use it.
675
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
676
-			}
677
-
678
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
679
-			if ($ncName) {
680
-				$nextcloudNames[] = $ncName;
681
-				if ($isUsers) {
682
-					$this->updateUserState($ncName);
683
-					//cache the user names so it does not need to be retrieved
684
-					//again later (e.g. sharing dialogue).
685
-					if (is_null($nameByLDAP)) {
686
-						continue;
687
-					}
688
-					$sndName = isset($ldapObject[$sndAttribute][0])
689
-						? $ldapObject[$sndAttribute][0] : '';
690
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
691
-				} elseif ($nameByLDAP !== null) {
692
-					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
693
-				}
694
-			}
695
-		}
696
-		return $nextcloudNames;
697
-	}
698
-
699
-	/**
700
-	 * removes the deleted-flag of a user if it was set
701
-	 *
702
-	 * @param string $ncname
703
-	 * @throws \Exception
704
-	 */
705
-	public function updateUserState($ncname) {
706
-		$user = $this->userManager->get($ncname);
707
-		if ($user instanceof OfflineUser) {
708
-			$user->unmark();
709
-		}
710
-	}
711
-
712
-	/**
713
-	 * caches the user display name
714
-	 *
715
-	 * @param string $ocName the internal Nextcloud username
716
-	 * @param string|false $home the home directory path
717
-	 */
718
-	public function cacheUserHome($ocName, $home) {
719
-		$cacheKey = 'getHome' . $ocName;
720
-		$this->connection->writeToCache($cacheKey, $home);
721
-	}
722
-
723
-	/**
724
-	 * caches a user as existing
725
-	 *
726
-	 * @param string $ocName the internal Nextcloud username
727
-	 */
728
-	public function cacheUserExists($ocName) {
729
-		$this->connection->writeToCache('userExists' . $ocName, true);
730
-	}
731
-
732
-	/**
733
-	 * caches a group as existing
734
-	 */
735
-	public function cacheGroupExists(string $gid): void {
736
-		$this->connection->writeToCache('groupExists' . $gid, true);
737
-	}
738
-
739
-	/**
740
-	 * caches the user display name
741
-	 *
742
-	 * @param string $ocName the internal Nextcloud username
743
-	 * @param string $displayName the display name
744
-	 * @param string $displayName2 the second display name
745
-	 * @throws \Exception
746
-	 */
747
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
748
-		$user = $this->userManager->get($ocName);
749
-		if ($user === null) {
750
-			return;
751
-		}
752
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
753
-		$cacheKeyTrunk = 'getDisplayName';
754
-		$this->connection->writeToCache($cacheKeyTrunk . $ocName, $displayName);
755
-	}
756
-
757
-	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
758
-		$cacheKey = 'group_getDisplayName' . $ncName;
759
-		$this->connection->writeToCache($cacheKey, $displayName);
760
-	}
761
-
762
-	/**
763
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
764
-	 *
765
-	 * @param string $name the display name of the object
766
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
767
-	 *
768
-	 * Instead of using this method directly, call
769
-	 * createAltInternalOwnCloudName($name, true)
770
-	 */
771
-	private function _createAltInternalOwnCloudNameForUsers($name) {
772
-		$attempts = 0;
773
-		//while loop is just a precaution. If a name is not generated within
774
-		//20 attempts, something else is very wrong. Avoids infinite loop.
775
-		while ($attempts < 20) {
776
-			$altName = $name . '_' . rand(1000, 9999);
777
-			if (!$this->ncUserManager->userExists($altName)) {
778
-				return $altName;
779
-			}
780
-			$attempts++;
781
-		}
782
-		return false;
783
-	}
784
-
785
-	/**
786
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
787
-	 *
788
-	 * @param string $name the display name of the object
789
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
790
-	 *
791
-	 * Instead of using this method directly, call
792
-	 * createAltInternalOwnCloudName($name, false)
793
-	 *
794
-	 * Group names are also used as display names, so we do a sequential
795
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
796
-	 * "Developers"
797
-	 */
798
-	private function _createAltInternalOwnCloudNameForGroups($name) {
799
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
800
-		if (!$usedNames || count($usedNames) === 0) {
801
-			$lastNo = 1; //will become name_2
802
-		} else {
803
-			natsort($usedNames);
804
-			$lastName = array_pop($usedNames);
805
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
806
-		}
807
-		$altName = $name . '_' . (string)($lastNo + 1);
808
-		unset($usedNames);
809
-
810
-		$attempts = 1;
811
-		while ($attempts < 21) {
812
-			// Check to be really sure it is unique
813
-			// while loop is just a precaution. If a name is not generated within
814
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
815
-			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
816
-				return $altName;
817
-			}
818
-			$altName = $name . '_' . ($lastNo + $attempts);
819
-			$attempts++;
820
-		}
821
-		return false;
822
-	}
823
-
824
-	/**
825
-	 * creates a unique name for internal Nextcloud use.
826
-	 *
827
-	 * @param string $name the display name of the object
828
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
829
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
830
-	 */
831
-	private function createAltInternalOwnCloudName($name, $isUser) {
832
-		$originalTTL = $this->connection->ldapCacheTTL;
833
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
834
-		if ($isUser) {
835
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
836
-		} else {
837
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
838
-		}
839
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
840
-
841
-		return $altName;
842
-	}
843
-
844
-	/**
845
-	 * fetches a list of users according to a provided loginName and utilizing
846
-	 * the login filter.
847
-	 */
848
-	public function fetchUsersByLoginName(string $loginName, array $attributes = ['dn']): array {
849
-		$loginName = $this->escapeFilterPart($loginName);
850
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
851
-		return $this->fetchListOfUsers($filter, $attributes);
852
-	}
853
-
854
-	/**
855
-	 * counts the number of users according to a provided loginName and
856
-	 * utilizing the login filter.
857
-	 *
858
-	 * @param string $loginName
859
-	 * @return int
860
-	 */
861
-	public function countUsersByLoginName($loginName) {
862
-		$loginName = $this->escapeFilterPart($loginName);
863
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
864
-		return $this->countUsers($filter);
865
-	}
866
-
867
-	/**
868
-	 * @throws \Exception
869
-	 */
870
-	public function fetchListOfUsers(string $filter, array $attr, int $limit = null, int $offset = null, bool $forceApplyAttributes = false): array {
871
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
872
-		$recordsToUpdate = $ldapRecords;
873
-		if (!$forceApplyAttributes) {
874
-			$isBackgroundJobModeAjax = $this->config
875
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
876
-			$listOfDNs = array_reduce($ldapRecords, function ($listOfDNs, $entry) {
877
-				$listOfDNs[] = $entry['dn'][0];
878
-				return $listOfDNs;
879
-			}, []);
880
-			$idsByDn = $this->userMapper->getListOfIdsByDn($listOfDNs);
881
-			$recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax, $idsByDn) {
882
-				$newlyMapped = false;
883
-				$uid = $idsByDn[$record['dn'][0]] ?? null;
884
-				if ($uid === null) {
885
-					$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
886
-				}
887
-				if (is_string($uid)) {
888
-					$this->cacheUserExists($uid);
889
-				}
890
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
891
-			});
892
-		}
893
-		$this->batchApplyUserAttributes($recordsToUpdate);
894
-		return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
895
-	}
896
-
897
-	/**
898
-	 * provided with an array of LDAP user records the method will fetch the
899
-	 * user object and requests it to process the freshly fetched attributes and
900
-	 * and their values
901
-	 *
902
-	 * @param array $ldapRecords
903
-	 * @throws \Exception
904
-	 */
905
-	public function batchApplyUserAttributes(array $ldapRecords) {
906
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
907
-		foreach ($ldapRecords as $userRecord) {
908
-			if (!isset($userRecord[$displayNameAttribute])) {
909
-				// displayName is obligatory
910
-				continue;
911
-			}
912
-			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
913
-			if ($ocName === false) {
914
-				continue;
915
-			}
916
-			$this->updateUserState($ocName);
917
-			$user = $this->userManager->get($ocName);
918
-			if ($user !== null) {
919
-				$user->processAttributes($userRecord);
920
-			} else {
921
-				\OC::$server->getLogger()->debug(
922
-					"The ldap user manager returned null for $ocName",
923
-					['app' => 'user_ldap']
924
-				);
925
-			}
926
-		}
927
-	}
928
-
929
-	/**
930
-	 * @param string $filter
931
-	 * @param string|string[] $attr
932
-	 * @param int $limit
933
-	 * @param int $offset
934
-	 * @return array
935
-	 */
936
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
937
-		$groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
938
-
939
-		$listOfDNs = array_reduce($groupRecords, function ($listOfDNs, $entry) {
940
-			$listOfDNs[] = $entry['dn'][0];
941
-			return $listOfDNs;
942
-		}, []);
943
-		$idsByDn = $this->groupMapper->getListOfIdsByDn($listOfDNs);
944
-
945
-		array_walk($groupRecords, function ($record) use ($idsByDn) {
946
-			$newlyMapped = false;
947
-			$gid = $uidsByDn[$record['dn'][0]] ?? null;
948
-			if ($gid === null) {
949
-				$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
950
-			}
951
-			if (!$newlyMapped && is_string($gid)) {
952
-				$this->cacheGroupExists($gid);
953
-			}
954
-		});
955
-		return $this->fetchList($groupRecords, $this->manyAttributes($attr));
956
-	}
957
-
958
-	/**
959
-	 * @param array $list
960
-	 * @param bool $manyAttributes
961
-	 * @return array
962
-	 */
963
-	private function fetchList($list, $manyAttributes) {
964
-		if (is_array($list)) {
965
-			if ($manyAttributes) {
966
-				return $list;
967
-			} else {
968
-				$list = array_reduce($list, function ($carry, $item) {
969
-					$attribute = array_keys($item)[0];
970
-					$carry[] = $item[$attribute][0];
971
-					return $carry;
972
-				}, []);
973
-				return array_unique($list, SORT_LOCALE_STRING);
974
-			}
975
-		}
976
-
977
-		//error cause actually, maybe throw an exception in future.
978
-		return [];
979
-	}
980
-
981
-	/**
982
-	 * @throws ServerNotAvailableException
983
-	 */
984
-	public function searchUsers(string $filter, array $attr = null, int $limit = null, int $offset = null): array {
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
-	 * @throws ServerNotAvailableException
999
-	 */
1000
-	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1001
-		$result = false;
1002
-		foreach ($this->connection->ldapBaseUsers as $base) {
1003
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1004
-			$result = is_int($count) ? (int)$result + $count : $result;
1005
-		}
1006
-		return $result;
1007
-	}
1008
-
1009
-	/**
1010
-	 * executes an LDAP search, optimized for Groups
1011
-	 *
1012
-	 * @param string $filter the LDAP filter for the search
1013
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1014
-	 * @param integer $limit
1015
-	 * @param integer $offset
1016
-	 * @return array with the search result
1017
-	 *
1018
-	 * Executes an LDAP search
1019
-	 * @throws ServerNotAvailableException
1020
-	 */
1021
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1022
-		$result = [];
1023
-		foreach ($this->connection->ldapBaseGroups as $base) {
1024
-			$result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
1025
-		}
1026
-		return $result;
1027
-	}
1028
-
1029
-	/**
1030
-	 * returns the number of available groups
1031
-	 *
1032
-	 * @param string $filter the LDAP search filter
1033
-	 * @param string[] $attr optional
1034
-	 * @param int|null $limit
1035
-	 * @param int|null $offset
1036
-	 * @return int|bool
1037
-	 * @throws ServerNotAvailableException
1038
-	 */
1039
-	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1040
-		$result = false;
1041
-		foreach ($this->connection->ldapBaseGroups as $base) {
1042
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1043
-			$result = is_int($count) ? (int)$result + $count : $result;
1044
-		}
1045
-		return $result;
1046
-	}
1047
-
1048
-	/**
1049
-	 * returns the number of available objects on the base DN
1050
-	 *
1051
-	 * @param int|null $limit
1052
-	 * @param int|null $offset
1053
-	 * @return int|bool
1054
-	 * @throws ServerNotAvailableException
1055
-	 */
1056
-	public function countObjects($limit = null, $offset = null) {
1057
-		$result = false;
1058
-		foreach ($this->connection->ldapBase as $base) {
1059
-			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1060
-			$result = is_int($count) ? (int)$result + $count : $result;
1061
-		}
1062
-		return $result;
1063
-	}
1064
-
1065
-	/**
1066
-	 * Returns the LDAP handler
1067
-	 *
1068
-	 * @throws \OC\ServerNotAvailableException
1069
-	 */
1070
-
1071
-	/**
1072
-	 * @return mixed
1073
-	 * @throws \OC\ServerNotAvailableException
1074
-	 */
1075
-	private function invokeLDAPMethod() {
1076
-		$arguments = func_get_args();
1077
-		$command = array_shift($arguments);
1078
-		$cr = array_shift($arguments);
1079
-		if (!method_exists($this->ldap, $command)) {
1080
-			return null;
1081
-		}
1082
-		array_unshift($arguments, $cr);
1083
-		// php no longer supports call-time pass-by-reference
1084
-		// thus cannot support controlPagedResultResponse as the third argument
1085
-		// is a reference
1086
-		$doMethod = function () use ($command, &$arguments) {
1087
-			if ($command == 'controlPagedResultResponse') {
1088
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1089
-			} else {
1090
-				return call_user_func_array([$this->ldap, $command], $arguments);
1091
-			}
1092
-		};
1093
-		try {
1094
-			$ret = $doMethod();
1095
-		} catch (ServerNotAvailableException $e) {
1096
-			/* Server connection lost, attempt to reestablish it
68
+    public const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
69
+
70
+    /** @var \OCA\User_LDAP\Connection */
71
+    public $connection;
72
+    /** @var Manager */
73
+    public $userManager;
74
+    //never ever check this var directly, always use getPagedSearchResultState
75
+    protected $pagedSearchedSuccessful;
76
+
77
+    /**
78
+     * @var UserMapping $userMapper
79
+     */
80
+    protected $userMapper;
81
+
82
+    /**
83
+     * @var AbstractMapping $userMapper
84
+     */
85
+    protected $groupMapper;
86
+
87
+    /**
88
+     * @var \OCA\User_LDAP\Helper
89
+     */
90
+    private $helper;
91
+    /** @var IConfig */
92
+    private $config;
93
+    /** @var IUserManager */
94
+    private $ncUserManager;
95
+    /** @var string */
96
+    private $lastCookie = '';
97
+
98
+    public function __construct(
99
+        Connection $connection,
100
+        ILDAPWrapper $ldap,
101
+        Manager $userManager,
102
+        Helper $helper,
103
+        IConfig $config,
104
+        IUserManager $ncUserManager
105
+    ) {
106
+        parent::__construct($ldap);
107
+        $this->connection = $connection;
108
+        $this->userManager = $userManager;
109
+        $this->userManager->setLdapAccess($this);
110
+        $this->helper = $helper;
111
+        $this->config = $config;
112
+        $this->ncUserManager = $ncUserManager;
113
+    }
114
+
115
+    /**
116
+     * sets the User Mapper
117
+     *
118
+     * @param AbstractMapping $mapper
119
+     */
120
+    public function setUserMapper(AbstractMapping $mapper) {
121
+        $this->userMapper = $mapper;
122
+    }
123
+
124
+    /**
125
+     * @throws \Exception
126
+     */
127
+    public function getUserMapper(): UserMapping {
128
+        if (is_null($this->userMapper)) {
129
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
130
+        }
131
+        return $this->userMapper;
132
+    }
133
+
134
+    /**
135
+     * sets the Group Mapper
136
+     *
137
+     * @param AbstractMapping $mapper
138
+     */
139
+    public function setGroupMapper(AbstractMapping $mapper) {
140
+        $this->groupMapper = $mapper;
141
+    }
142
+
143
+    /**
144
+     * returns the Group Mapper
145
+     *
146
+     * @return AbstractMapping
147
+     * @throws \Exception
148
+     */
149
+    public function getGroupMapper() {
150
+        if (is_null($this->groupMapper)) {
151
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
152
+        }
153
+        return $this->groupMapper;
154
+    }
155
+
156
+    /**
157
+     * @return bool
158
+     */
159
+    private function checkConnection() {
160
+        return ($this->connection instanceof Connection);
161
+    }
162
+
163
+    /**
164
+     * returns the Connection instance
165
+     *
166
+     * @return \OCA\User_LDAP\Connection
167
+     */
168
+    public function getConnection() {
169
+        return $this->connection;
170
+    }
171
+
172
+    /**
173
+     * reads a given attribute for an LDAP record identified by a DN
174
+     *
175
+     * @param string $dn the record in question
176
+     * @param string $attr the attribute that shall be retrieved
177
+     *        if empty, just check the record's existence
178
+     * @param string $filter
179
+     * @return array|false an array of values on success or an empty
180
+     *          array if $attr is empty, false otherwise
181
+     * @throws ServerNotAvailableException
182
+     */
183
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
184
+        if (!$this->checkConnection()) {
185
+            \OCP\Util::writeLog('user_ldap',
186
+                'No LDAP Connector assigned, access impossible for readAttribute.',
187
+                ILogger::WARN);
188
+            return false;
189
+        }
190
+        $cr = $this->connection->getConnectionResource();
191
+        if (!$this->ldap->isResource($cr)) {
192
+            //LDAP not available
193
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
194
+            return false;
195
+        }
196
+        //Cancel possibly running Paged Results operation, otherwise we run in
197
+        //LDAP protocol errors
198
+        $this->abandonPagedSearch();
199
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
200
+        // but does not hurt either.
201
+        $pagingSize = (int)$this->connection->ldapPagingSize;
202
+        // 0 won't result in replies, small numbers may leave out groups
203
+        // (cf. #12306), 500 is default for paging and should work everywhere.
204
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
205
+        $attr = mb_strtolower($attr, 'UTF-8');
206
+        // the actual read attribute later may contain parameters on a ranged
207
+        // request, e.g. member;range=99-199. Depends on server reply.
208
+        $attrToRead = $attr;
209
+
210
+        $values = [];
211
+        $isRangeRequest = false;
212
+        do {
213
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
214
+            if (is_bool($result)) {
215
+                // when an exists request was run and it was successful, an empty
216
+                // array must be returned
217
+                return $result ? [] : false;
218
+            }
219
+
220
+            if (!$isRangeRequest) {
221
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
222
+                if (!empty($values)) {
223
+                    return $values;
224
+                }
225
+            }
226
+
227
+            $isRangeRequest = false;
228
+            $result = $this->extractRangeData($result, $attr);
229
+            if (!empty($result)) {
230
+                $normalizedResult = $this->extractAttributeValuesFromResult(
231
+                    [$attr => $result['values']],
232
+                    $attr
233
+                );
234
+                $values = array_merge($values, $normalizedResult);
235
+
236
+                if ($result['rangeHigh'] === '*') {
237
+                    // when server replies with * as high range value, there are
238
+                    // no more results left
239
+                    return $values;
240
+                } else {
241
+                    $low = $result['rangeHigh'] + 1;
242
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
243
+                    $isRangeRequest = true;
244
+                }
245
+            }
246
+        } while ($isRangeRequest);
247
+
248
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, ILogger::DEBUG);
249
+        return false;
250
+    }
251
+
252
+    /**
253
+     * Runs an read operation against LDAP
254
+     *
255
+     * @param resource $cr the LDAP connection
256
+     * @param string $dn
257
+     * @param string $attribute
258
+     * @param string $filter
259
+     * @param int $maxResults
260
+     * @return array|bool false if there was any error, true if an exists check
261
+     *                    was performed and the requested DN found, array with the
262
+     *                    returned data on a successful usual operation
263
+     * @throws ServerNotAvailableException
264
+     */
265
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
266
+        $this->initPagedSearch($filter, $dn, [$attribute], $maxResults, 0);
267
+        $dn = $this->helper->DNasBaseParameter($dn);
268
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
269
+        if (!$this->ldap->isResource($rr)) {
270
+            if ($attribute !== '') {
271
+                //do not throw this message on userExists check, irritates
272
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
273
+            }
274
+            //in case an error occurs , e.g. object does not exist
275
+            return false;
276
+        }
277
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
278
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
279
+            return true;
280
+        }
281
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
282
+        if (!$this->ldap->isResource($er)) {
283
+            //did not match the filter, return false
284
+            return false;
285
+        }
286
+        //LDAP attributes are not case sensitive
287
+        $result = \OCP\Util::mb_array_change_key_case(
288
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
289
+
290
+        return $result;
291
+    }
292
+
293
+    /**
294
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
295
+     * data if present.
296
+     *
297
+     * @param array $result from ILDAPWrapper::getAttributes()
298
+     * @param string $attribute the attribute name that was read
299
+     * @return string[]
300
+     */
301
+    public function extractAttributeValuesFromResult($result, $attribute) {
302
+        $values = [];
303
+        if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
304
+            $lowercaseAttribute = strtolower($attribute);
305
+            for ($i = 0; $i < $result[$attribute]['count']; $i++) {
306
+                if ($this->resemblesDN($attribute)) {
307
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
308
+                } elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
309
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
310
+                } else {
311
+                    $values[] = $result[$attribute][$i];
312
+                }
313
+            }
314
+        }
315
+        return $values;
316
+    }
317
+
318
+    /**
319
+     * Attempts to find ranged data in a getAttribute results and extracts the
320
+     * returned values as well as information on the range and full attribute
321
+     * name for further processing.
322
+     *
323
+     * @param array $result from ILDAPWrapper::getAttributes()
324
+     * @param string $attribute the attribute name that was read. Without ";range=…"
325
+     * @return array If a range was detected with keys 'values', 'attributeName',
326
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
327
+     */
328
+    public function extractRangeData($result, $attribute) {
329
+        $keys = array_keys($result);
330
+        foreach ($keys as $key) {
331
+            if ($key !== $attribute && strpos($key, $attribute) === 0) {
332
+                $queryData = explode(';', $key);
333
+                if (strpos($queryData[1], 'range=') === 0) {
334
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
335
+                    $data = [
336
+                        'values' => $result[$key],
337
+                        'attributeName' => $queryData[0],
338
+                        'attributeFull' => $key,
339
+                        'rangeHigh' => $high,
340
+                    ];
341
+                    return $data;
342
+                }
343
+            }
344
+        }
345
+        return [];
346
+    }
347
+
348
+    /**
349
+     * Set password for an LDAP user identified by a DN
350
+     *
351
+     * @param string $userDN the user in question
352
+     * @param string $password the new password
353
+     * @return bool
354
+     * @throws HintException
355
+     * @throws \Exception
356
+     */
357
+    public function setPassword($userDN, $password) {
358
+        if ((int)$this->connection->turnOnPasswordChange !== 1) {
359
+            throw new \Exception('LDAP password changes are disabled.');
360
+        }
361
+        $cr = $this->connection->getConnectionResource();
362
+        if (!$this->ldap->isResource($cr)) {
363
+            //LDAP not available
364
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
365
+            return false;
366
+        }
367
+        try {
368
+            // try PASSWD extended operation first
369
+            return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
370
+                @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
371
+        } catch (ConstraintViolationException $e) {
372
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ') . $e->getMessage(), $e->getCode());
373
+        }
374
+    }
375
+
376
+    /**
377
+     * checks whether the given attributes value is probably a DN
378
+     *
379
+     * @param string $attr the attribute in question
380
+     * @return boolean if so true, otherwise false
381
+     */
382
+    private function resemblesDN($attr) {
383
+        $resemblingAttributes = [
384
+            'dn',
385
+            'uniquemember',
386
+            'member',
387
+            // memberOf is an "operational" attribute, without a definition in any RFC
388
+            'memberof'
389
+        ];
390
+        return in_array($attr, $resemblingAttributes);
391
+    }
392
+
393
+    /**
394
+     * checks whether the given string is probably a DN
395
+     *
396
+     * @param string $string
397
+     * @return boolean
398
+     */
399
+    public function stringResemblesDN($string) {
400
+        $r = $this->ldap->explodeDN($string, 0);
401
+        // if exploding a DN succeeds and does not end up in
402
+        // an empty array except for $r[count] being 0.
403
+        return (is_array($r) && count($r) > 1);
404
+    }
405
+
406
+    /**
407
+     * returns a DN-string that is cleaned from not domain parts, e.g.
408
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
409
+     * becomes dc=foobar,dc=server,dc=org
410
+     *
411
+     * @param string $dn
412
+     * @return string
413
+     */
414
+    public function getDomainDNFromDN($dn) {
415
+        $allParts = $this->ldap->explodeDN($dn, 0);
416
+        if ($allParts === false) {
417
+            //not a valid DN
418
+            return '';
419
+        }
420
+        $domainParts = [];
421
+        $dcFound = false;
422
+        foreach ($allParts as $part) {
423
+            if (!$dcFound && strpos($part, 'dc=') === 0) {
424
+                $dcFound = true;
425
+            }
426
+            if ($dcFound) {
427
+                $domainParts[] = $part;
428
+            }
429
+        }
430
+        return implode(',', $domainParts);
431
+    }
432
+
433
+    /**
434
+     * returns the LDAP DN for the given internal Nextcloud name of the group
435
+     *
436
+     * @param string $name the Nextcloud name in question
437
+     * @return string|false LDAP DN on success, otherwise false
438
+     */
439
+    public function groupname2dn($name) {
440
+        return $this->groupMapper->getDNByName($name);
441
+    }
442
+
443
+    /**
444
+     * returns the LDAP DN for the given internal Nextcloud name of the user
445
+     *
446
+     * @param string $name the Nextcloud name in question
447
+     * @return string|false with the LDAP DN on success, otherwise false
448
+     */
449
+    public function username2dn($name) {
450
+        $fdn = $this->userMapper->getDNByName($name);
451
+
452
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
453
+        //server setups
454
+        if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
455
+            return $fdn;
456
+        }
457
+
458
+        return false;
459
+    }
460
+
461
+    /**
462
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
463
+     *
464
+     * @param string $fdn the dn of the group object
465
+     * @param string $ldapName optional, the display name of the object
466
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
467
+     * @throws \Exception
468
+     */
469
+    public function dn2groupname($fdn, $ldapName = null) {
470
+        //To avoid bypassing the base DN settings under certain circumstances
471
+        //with the group support, check whether the provided DN matches one of
472
+        //the given Bases
473
+        if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
474
+            return false;
475
+        }
476
+
477
+        return $this->dn2ocname($fdn, $ldapName, false);
478
+    }
479
+
480
+    /**
481
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
482
+     *
483
+     * @param string $dn the dn of the user object
484
+     * @param string $ldapName optional, the display name of the object
485
+     * @return string|false with with the name to use in Nextcloud
486
+     * @throws \Exception
487
+     */
488
+    public function dn2username($fdn, $ldapName = null) {
489
+        //To avoid bypassing the base DN settings under certain circumstances
490
+        //with the group support, check whether the provided DN matches one of
491
+        //the given Bases
492
+        if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
493
+            return false;
494
+        }
495
+
496
+        return $this->dn2ocname($fdn, $ldapName, true);
497
+    }
498
+
499
+    /**
500
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
501
+     *
502
+     * @param string $fdn the dn of the user object
503
+     * @param string|null $ldapName optional, the display name of the object
504
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
505
+     * @param bool|null $newlyMapped
506
+     * @param array|null $record
507
+     * @return false|string with with the name to use in Nextcloud
508
+     * @throws \Exception
509
+     */
510
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
511
+        $newlyMapped = false;
512
+        if ($isUser) {
513
+            $mapper = $this->getUserMapper();
514
+            $nameAttribute = $this->connection->ldapUserDisplayName;
515
+            $filter = $this->connection->ldapUserFilter;
516
+        } else {
517
+            $mapper = $this->getGroupMapper();
518
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
519
+            $filter = $this->connection->ldapGroupFilter;
520
+        }
521
+
522
+        //let's try to retrieve the Nextcloud name from the mappings table
523
+        $ncName = $mapper->getNameByDN($fdn);
524
+        if (is_string($ncName)) {
525
+            return $ncName;
526
+        }
527
+
528
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
529
+        $uuid = $this->getUUID($fdn, $isUser, $record);
530
+        if (is_string($uuid)) {
531
+            $ncName = $mapper->getNameByUUID($uuid);
532
+            if (is_string($ncName)) {
533
+                $mapper->setDNbyUUID($fdn, $uuid);
534
+                return $ncName;
535
+            }
536
+        } else {
537
+            //If the UUID can't be detected something is foul.
538
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for ' . $fdn . '. Skipping.', ILogger::INFO);
539
+            return false;
540
+        }
541
+
542
+        if (is_null($ldapName)) {
543
+            $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
544
+            if (!isset($ldapName[0]) && empty($ldapName[0])) {
545
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for ' . $fdn . ' with filter ' . $filter . '.', ILogger::INFO);
546
+                return false;
547
+            }
548
+            $ldapName = $ldapName[0];
549
+        }
550
+
551
+        if ($isUser) {
552
+            $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
553
+            if ($usernameAttribute !== '') {
554
+                $username = $this->readAttribute($fdn, $usernameAttribute);
555
+                $username = $username[0];
556
+            } else {
557
+                $username = $uuid;
558
+            }
559
+            try {
560
+                $intName = $this->sanitizeUsername($username);
561
+            } catch (\InvalidArgumentException $e) {
562
+                \OC::$server->getLogger()->logException($e, [
563
+                    'app' => 'user_ldap',
564
+                    'level' => ILogger::WARN,
565
+                ]);
566
+                // we don't attempt to set a username here. We can go for
567
+                // for an alternative 4 digit random number as we would append
568
+                // otherwise, however it's likely not enough space in bigger
569
+                // setups, and most importantly: this is not intended.
570
+                return false;
571
+            }
572
+        } else {
573
+            $intName = $ldapName;
574
+        }
575
+
576
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
577
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
578
+        //NOTE: mind, disabling cache affects only this instance! Using it
579
+        // outside of core user management will still cache the user as non-existing.
580
+        $originalTTL = $this->connection->ldapCacheTTL;
581
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
582
+        if ($intName !== ''
583
+            && (($isUser && !$this->ncUserManager->userExists($intName))
584
+                || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
585
+            )
586
+        ) {
587
+            $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
588
+            $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
589
+            if ($newlyMapped) {
590
+                return $intName;
591
+            }
592
+        }
593
+
594
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
595
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
596
+        if (is_string($altName)) {
597
+            if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
598
+                $newlyMapped = true;
599
+                return $altName;
600
+            }
601
+        }
602
+
603
+        //if everything else did not help..
604
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for ' . $fdn . '.', ILogger::INFO);
605
+        return false;
606
+    }
607
+
608
+    public function mapAndAnnounceIfApplicable(
609
+        AbstractMapping $mapper,
610
+        string $fdn,
611
+        string $name,
612
+        string $uuid,
613
+        bool $isUser
614
+    ): bool {
615
+        if ($mapper->map($fdn, $name, $uuid)) {
616
+            if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
617
+                $this->cacheUserExists($name);
618
+                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
619
+            } elseif (!$isUser) {
620
+                $this->cacheGroupExists($name);
621
+            }
622
+            return true;
623
+        }
624
+        return false;
625
+    }
626
+
627
+    /**
628
+     * gives back the user names as they are used ownClod internally
629
+     *
630
+     * @param array $ldapUsers as returned by fetchList()
631
+     * @return array an array with the user names to use in Nextcloud
632
+     *
633
+     * gives back the user names as they are used ownClod internally
634
+     * @throws \Exception
635
+     */
636
+    public function nextcloudUserNames($ldapUsers) {
637
+        return $this->ldap2NextcloudNames($ldapUsers, true);
638
+    }
639
+
640
+    /**
641
+     * gives back the group names as they are used ownClod internally
642
+     *
643
+     * @param array $ldapGroups as returned by fetchList()
644
+     * @return array an array with the group names to use in Nextcloud
645
+     *
646
+     * gives back the group names as they are used ownClod internally
647
+     * @throws \Exception
648
+     */
649
+    public function nextcloudGroupNames($ldapGroups) {
650
+        return $this->ldap2NextcloudNames($ldapGroups, false);
651
+    }
652
+
653
+    /**
654
+     * @param array $ldapObjects as returned by fetchList()
655
+     * @param bool $isUsers
656
+     * @return array
657
+     * @throws \Exception
658
+     */
659
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
660
+        if ($isUsers) {
661
+            $nameAttribute = $this->connection->ldapUserDisplayName;
662
+            $sndAttribute = $this->connection->ldapUserDisplayName2;
663
+        } else {
664
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
665
+        }
666
+        $nextcloudNames = [];
667
+
668
+        foreach ($ldapObjects as $ldapObject) {
669
+            $nameByLDAP = null;
670
+            if (isset($ldapObject[$nameAttribute])
671
+                && is_array($ldapObject[$nameAttribute])
672
+                && isset($ldapObject[$nameAttribute][0])
673
+            ) {
674
+                // might be set, but not necessarily. if so, we use it.
675
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
676
+            }
677
+
678
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
679
+            if ($ncName) {
680
+                $nextcloudNames[] = $ncName;
681
+                if ($isUsers) {
682
+                    $this->updateUserState($ncName);
683
+                    //cache the user names so it does not need to be retrieved
684
+                    //again later (e.g. sharing dialogue).
685
+                    if (is_null($nameByLDAP)) {
686
+                        continue;
687
+                    }
688
+                    $sndName = isset($ldapObject[$sndAttribute][0])
689
+                        ? $ldapObject[$sndAttribute][0] : '';
690
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
691
+                } elseif ($nameByLDAP !== null) {
692
+                    $this->cacheGroupDisplayName($ncName, $nameByLDAP);
693
+                }
694
+            }
695
+        }
696
+        return $nextcloudNames;
697
+    }
698
+
699
+    /**
700
+     * removes the deleted-flag of a user if it was set
701
+     *
702
+     * @param string $ncname
703
+     * @throws \Exception
704
+     */
705
+    public function updateUserState($ncname) {
706
+        $user = $this->userManager->get($ncname);
707
+        if ($user instanceof OfflineUser) {
708
+            $user->unmark();
709
+        }
710
+    }
711
+
712
+    /**
713
+     * caches the user display name
714
+     *
715
+     * @param string $ocName the internal Nextcloud username
716
+     * @param string|false $home the home directory path
717
+     */
718
+    public function cacheUserHome($ocName, $home) {
719
+        $cacheKey = 'getHome' . $ocName;
720
+        $this->connection->writeToCache($cacheKey, $home);
721
+    }
722
+
723
+    /**
724
+     * caches a user as existing
725
+     *
726
+     * @param string $ocName the internal Nextcloud username
727
+     */
728
+    public function cacheUserExists($ocName) {
729
+        $this->connection->writeToCache('userExists' . $ocName, true);
730
+    }
731
+
732
+    /**
733
+     * caches a group as existing
734
+     */
735
+    public function cacheGroupExists(string $gid): void {
736
+        $this->connection->writeToCache('groupExists' . $gid, true);
737
+    }
738
+
739
+    /**
740
+     * caches the user display name
741
+     *
742
+     * @param string $ocName the internal Nextcloud username
743
+     * @param string $displayName the display name
744
+     * @param string $displayName2 the second display name
745
+     * @throws \Exception
746
+     */
747
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
748
+        $user = $this->userManager->get($ocName);
749
+        if ($user === null) {
750
+            return;
751
+        }
752
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
753
+        $cacheKeyTrunk = 'getDisplayName';
754
+        $this->connection->writeToCache($cacheKeyTrunk . $ocName, $displayName);
755
+    }
756
+
757
+    public function cacheGroupDisplayName(string $ncName, string $displayName): void {
758
+        $cacheKey = 'group_getDisplayName' . $ncName;
759
+        $this->connection->writeToCache($cacheKey, $displayName);
760
+    }
761
+
762
+    /**
763
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
764
+     *
765
+     * @param string $name the display name of the object
766
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
767
+     *
768
+     * Instead of using this method directly, call
769
+     * createAltInternalOwnCloudName($name, true)
770
+     */
771
+    private function _createAltInternalOwnCloudNameForUsers($name) {
772
+        $attempts = 0;
773
+        //while loop is just a precaution. If a name is not generated within
774
+        //20 attempts, something else is very wrong. Avoids infinite loop.
775
+        while ($attempts < 20) {
776
+            $altName = $name . '_' . rand(1000, 9999);
777
+            if (!$this->ncUserManager->userExists($altName)) {
778
+                return $altName;
779
+            }
780
+            $attempts++;
781
+        }
782
+        return false;
783
+    }
784
+
785
+    /**
786
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
787
+     *
788
+     * @param string $name the display name of the object
789
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
790
+     *
791
+     * Instead of using this method directly, call
792
+     * createAltInternalOwnCloudName($name, false)
793
+     *
794
+     * Group names are also used as display names, so we do a sequential
795
+     * numbering, e.g. Developers_42 when there are 41 other groups called
796
+     * "Developers"
797
+     */
798
+    private function _createAltInternalOwnCloudNameForGroups($name) {
799
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
800
+        if (!$usedNames || count($usedNames) === 0) {
801
+            $lastNo = 1; //will become name_2
802
+        } else {
803
+            natsort($usedNames);
804
+            $lastName = array_pop($usedNames);
805
+            $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
806
+        }
807
+        $altName = $name . '_' . (string)($lastNo + 1);
808
+        unset($usedNames);
809
+
810
+        $attempts = 1;
811
+        while ($attempts < 21) {
812
+            // Check to be really sure it is unique
813
+            // while loop is just a precaution. If a name is not generated within
814
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
815
+            if (!\OC::$server->getGroupManager()->groupExists($altName)) {
816
+                return $altName;
817
+            }
818
+            $altName = $name . '_' . ($lastNo + $attempts);
819
+            $attempts++;
820
+        }
821
+        return false;
822
+    }
823
+
824
+    /**
825
+     * creates a unique name for internal Nextcloud use.
826
+     *
827
+     * @param string $name the display name of the object
828
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
829
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
830
+     */
831
+    private function createAltInternalOwnCloudName($name, $isUser) {
832
+        $originalTTL = $this->connection->ldapCacheTTL;
833
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
834
+        if ($isUser) {
835
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
836
+        } else {
837
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
838
+        }
839
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
840
+
841
+        return $altName;
842
+    }
843
+
844
+    /**
845
+     * fetches a list of users according to a provided loginName and utilizing
846
+     * the login filter.
847
+     */
848
+    public function fetchUsersByLoginName(string $loginName, array $attributes = ['dn']): array {
849
+        $loginName = $this->escapeFilterPart($loginName);
850
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
851
+        return $this->fetchListOfUsers($filter, $attributes);
852
+    }
853
+
854
+    /**
855
+     * counts the number of users according to a provided loginName and
856
+     * utilizing the login filter.
857
+     *
858
+     * @param string $loginName
859
+     * @return int
860
+     */
861
+    public function countUsersByLoginName($loginName) {
862
+        $loginName = $this->escapeFilterPart($loginName);
863
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
864
+        return $this->countUsers($filter);
865
+    }
866
+
867
+    /**
868
+     * @throws \Exception
869
+     */
870
+    public function fetchListOfUsers(string $filter, array $attr, int $limit = null, int $offset = null, bool $forceApplyAttributes = false): array {
871
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
872
+        $recordsToUpdate = $ldapRecords;
873
+        if (!$forceApplyAttributes) {
874
+            $isBackgroundJobModeAjax = $this->config
875
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
876
+            $listOfDNs = array_reduce($ldapRecords, function ($listOfDNs, $entry) {
877
+                $listOfDNs[] = $entry['dn'][0];
878
+                return $listOfDNs;
879
+            }, []);
880
+            $idsByDn = $this->userMapper->getListOfIdsByDn($listOfDNs);
881
+            $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax, $idsByDn) {
882
+                $newlyMapped = false;
883
+                $uid = $idsByDn[$record['dn'][0]] ?? null;
884
+                if ($uid === null) {
885
+                    $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
886
+                }
887
+                if (is_string($uid)) {
888
+                    $this->cacheUserExists($uid);
889
+                }
890
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
891
+            });
892
+        }
893
+        $this->batchApplyUserAttributes($recordsToUpdate);
894
+        return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
895
+    }
896
+
897
+    /**
898
+     * provided with an array of LDAP user records the method will fetch the
899
+     * user object and requests it to process the freshly fetched attributes and
900
+     * and their values
901
+     *
902
+     * @param array $ldapRecords
903
+     * @throws \Exception
904
+     */
905
+    public function batchApplyUserAttributes(array $ldapRecords) {
906
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
907
+        foreach ($ldapRecords as $userRecord) {
908
+            if (!isset($userRecord[$displayNameAttribute])) {
909
+                // displayName is obligatory
910
+                continue;
911
+            }
912
+            $ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
913
+            if ($ocName === false) {
914
+                continue;
915
+            }
916
+            $this->updateUserState($ocName);
917
+            $user = $this->userManager->get($ocName);
918
+            if ($user !== null) {
919
+                $user->processAttributes($userRecord);
920
+            } else {
921
+                \OC::$server->getLogger()->debug(
922
+                    "The ldap user manager returned null for $ocName",
923
+                    ['app' => 'user_ldap']
924
+                );
925
+            }
926
+        }
927
+    }
928
+
929
+    /**
930
+     * @param string $filter
931
+     * @param string|string[] $attr
932
+     * @param int $limit
933
+     * @param int $offset
934
+     * @return array
935
+     */
936
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
937
+        $groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
938
+
939
+        $listOfDNs = array_reduce($groupRecords, function ($listOfDNs, $entry) {
940
+            $listOfDNs[] = $entry['dn'][0];
941
+            return $listOfDNs;
942
+        }, []);
943
+        $idsByDn = $this->groupMapper->getListOfIdsByDn($listOfDNs);
944
+
945
+        array_walk($groupRecords, function ($record) use ($idsByDn) {
946
+            $newlyMapped = false;
947
+            $gid = $uidsByDn[$record['dn'][0]] ?? null;
948
+            if ($gid === null) {
949
+                $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
950
+            }
951
+            if (!$newlyMapped && is_string($gid)) {
952
+                $this->cacheGroupExists($gid);
953
+            }
954
+        });
955
+        return $this->fetchList($groupRecords, $this->manyAttributes($attr));
956
+    }
957
+
958
+    /**
959
+     * @param array $list
960
+     * @param bool $manyAttributes
961
+     * @return array
962
+     */
963
+    private function fetchList($list, $manyAttributes) {
964
+        if (is_array($list)) {
965
+            if ($manyAttributes) {
966
+                return $list;
967
+            } else {
968
+                $list = array_reduce($list, function ($carry, $item) {
969
+                    $attribute = array_keys($item)[0];
970
+                    $carry[] = $item[$attribute][0];
971
+                    return $carry;
972
+                }, []);
973
+                return array_unique($list, SORT_LOCALE_STRING);
974
+            }
975
+        }
976
+
977
+        //error cause actually, maybe throw an exception in future.
978
+        return [];
979
+    }
980
+
981
+    /**
982
+     * @throws ServerNotAvailableException
983
+     */
984
+    public function searchUsers(string $filter, array $attr = null, int $limit = null, int $offset = null): array {
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
+     * @throws ServerNotAvailableException
999
+     */
1000
+    public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1001
+        $result = false;
1002
+        foreach ($this->connection->ldapBaseUsers as $base) {
1003
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1004
+            $result = is_int($count) ? (int)$result + $count : $result;
1005
+        }
1006
+        return $result;
1007
+    }
1008
+
1009
+    /**
1010
+     * executes an LDAP search, optimized for Groups
1011
+     *
1012
+     * @param string $filter the LDAP filter for the search
1013
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1014
+     * @param integer $limit
1015
+     * @param integer $offset
1016
+     * @return array with the search result
1017
+     *
1018
+     * Executes an LDAP search
1019
+     * @throws ServerNotAvailableException
1020
+     */
1021
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1022
+        $result = [];
1023
+        foreach ($this->connection->ldapBaseGroups as $base) {
1024
+            $result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
1025
+        }
1026
+        return $result;
1027
+    }
1028
+
1029
+    /**
1030
+     * returns the number of available groups
1031
+     *
1032
+     * @param string $filter the LDAP search filter
1033
+     * @param string[] $attr optional
1034
+     * @param int|null $limit
1035
+     * @param int|null $offset
1036
+     * @return int|bool
1037
+     * @throws ServerNotAvailableException
1038
+     */
1039
+    public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1040
+        $result = false;
1041
+        foreach ($this->connection->ldapBaseGroups as $base) {
1042
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1043
+            $result = is_int($count) ? (int)$result + $count : $result;
1044
+        }
1045
+        return $result;
1046
+    }
1047
+
1048
+    /**
1049
+     * returns the number of available objects on the base DN
1050
+     *
1051
+     * @param int|null $limit
1052
+     * @param int|null $offset
1053
+     * @return int|bool
1054
+     * @throws ServerNotAvailableException
1055
+     */
1056
+    public function countObjects($limit = null, $offset = null) {
1057
+        $result = false;
1058
+        foreach ($this->connection->ldapBase as $base) {
1059
+            $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1060
+            $result = is_int($count) ? (int)$result + $count : $result;
1061
+        }
1062
+        return $result;
1063
+    }
1064
+
1065
+    /**
1066
+     * Returns the LDAP handler
1067
+     *
1068
+     * @throws \OC\ServerNotAvailableException
1069
+     */
1070
+
1071
+    /**
1072
+     * @return mixed
1073
+     * @throws \OC\ServerNotAvailableException
1074
+     */
1075
+    private function invokeLDAPMethod() {
1076
+        $arguments = func_get_args();
1077
+        $command = array_shift($arguments);
1078
+        $cr = array_shift($arguments);
1079
+        if (!method_exists($this->ldap, $command)) {
1080
+            return null;
1081
+        }
1082
+        array_unshift($arguments, $cr);
1083
+        // php no longer supports call-time pass-by-reference
1084
+        // thus cannot support controlPagedResultResponse as the third argument
1085
+        // is a reference
1086
+        $doMethod = function () use ($command, &$arguments) {
1087
+            if ($command == 'controlPagedResultResponse') {
1088
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1089
+            } else {
1090
+                return call_user_func_array([$this->ldap, $command], $arguments);
1091
+            }
1092
+        };
1093
+        try {
1094
+            $ret = $doMethod();
1095
+        } catch (ServerNotAvailableException $e) {
1096
+            /* Server connection lost, attempt to reestablish it
1097 1097
 			 * Maybe implement exponential backoff?
1098 1098
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1099 1099
 			 */
1100
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1101
-			$this->connection->resetConnectionResource();
1102
-			$cr = $this->connection->getConnectionResource();
1103
-
1104
-			if (!$this->ldap->isResource($cr)) {
1105
-				// Seems like we didn't find any resource.
1106
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1107
-				throw $e;
1108
-			}
1109
-
1110
-			$arguments[0] = $cr;
1111
-			$ret = $doMethod();
1112
-		}
1113
-		return $ret;
1114
-	}
1115
-
1116
-	/**
1117
-	 * retrieved. Results will according to the order in the array.
1118
-	 *
1119
-	 * @param string $filter
1120
-	 * @param string $base
1121
-	 * @param string[] $attr
1122
-	 * @param int|null $limit optional, maximum results to be counted
1123
-	 * @param int|null $offset optional, a starting point
1124
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1125
-	 * second | false if not successful
1126
-	 * @throws ServerNotAvailableException
1127
-	 */
1128
-	private function executeSearch(
1129
-		string $filter,
1130
-		string $base,
1131
-		?array &$attr,
1132
-		?int $limit,
1133
-		?int $offset
1134
-	) {
1135
-		// See if we have a resource, in case not cancel with message
1136
-		$cr = $this->connection->getConnectionResource();
1137
-		if (!$this->ldap->isResource($cr)) {
1138
-			// Seems like we didn't find any resource.
1139
-			// Return an empty array just like before.
1140
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1141
-			return false;
1142
-		}
1143
-
1144
-		//check whether paged search should be attempted
1145
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, (int)$offset);
1146
-
1147
-		$sr = $this->invokeLDAPMethod('search', $cr, $base, $filter, $attr);
1148
-		// cannot use $cr anymore, might have changed in the previous call!
1149
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1150
-		if (!$this->ldap->isResource($sr) || $error !== 0) {
1151
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  ' . print_r($pagedSearchOK, true), ILogger::ERROR);
1152
-			return false;
1153
-		}
1154
-
1155
-		return [$sr, $pagedSearchOK];
1156
-	}
1157
-
1158
-	/**
1159
-	 * processes an LDAP paged search operation
1160
-	 *
1161
-	 * @param resource $sr the array containing the LDAP search resources
1162
-	 * @param int $foundItems number of results in the single search operation
1163
-	 * @param int $limit maximum results to be counted
1164
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1165
-	 * @param bool $skipHandling required for paged search when cookies to
1166
-	 * prior results need to be gained
1167
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1168
-	 * @throws ServerNotAvailableException
1169
-	 */
1170
-	private function processPagedSearchStatus(
1171
-		$sr,
1172
-		int $foundItems,
1173
-		int $limit,
1174
-		bool $pagedSearchOK,
1175
-		bool $skipHandling
1176
-	): bool {
1177
-		$cookie = null;
1178
-		if ($pagedSearchOK) {
1179
-			$cr = $this->connection->getConnectionResource();
1180
-			if ($this->ldap->controlPagedResultResponse($cr, $sr, $cookie)) {
1181
-				$this->lastCookie = $cookie;
1182
-			}
1183
-
1184
-			//browsing through prior pages to get the cookie for the new one
1185
-			if ($skipHandling) {
1186
-				return false;
1187
-			}
1188
-			// if count is bigger, then the server does not support
1189
-			// paged search. Instead, he did a normal search. We set a
1190
-			// flag here, so the callee knows how to deal with it.
1191
-			if ($foundItems <= $limit) {
1192
-				$this->pagedSearchedSuccessful = true;
1193
-			}
1194
-		} else {
1195
-			if (!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1196
-				\OC::$server->getLogger()->debug(
1197
-					'Paged search was not available',
1198
-					['app' => 'user_ldap']
1199
-				);
1200
-			}
1201
-		}
1202
-		/* ++ Fixing RHDS searches with pages with zero results ++
1100
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1101
+            $this->connection->resetConnectionResource();
1102
+            $cr = $this->connection->getConnectionResource();
1103
+
1104
+            if (!$this->ldap->isResource($cr)) {
1105
+                // Seems like we didn't find any resource.
1106
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1107
+                throw $e;
1108
+            }
1109
+
1110
+            $arguments[0] = $cr;
1111
+            $ret = $doMethod();
1112
+        }
1113
+        return $ret;
1114
+    }
1115
+
1116
+    /**
1117
+     * retrieved. Results will according to the order in the array.
1118
+     *
1119
+     * @param string $filter
1120
+     * @param string $base
1121
+     * @param string[] $attr
1122
+     * @param int|null $limit optional, maximum results to be counted
1123
+     * @param int|null $offset optional, a starting point
1124
+     * @return array|false array with the search result as first value and pagedSearchOK as
1125
+     * second | false if not successful
1126
+     * @throws ServerNotAvailableException
1127
+     */
1128
+    private function executeSearch(
1129
+        string $filter,
1130
+        string $base,
1131
+        ?array &$attr,
1132
+        ?int $limit,
1133
+        ?int $offset
1134
+    ) {
1135
+        // See if we have a resource, in case not cancel with message
1136
+        $cr = $this->connection->getConnectionResource();
1137
+        if (!$this->ldap->isResource($cr)) {
1138
+            // Seems like we didn't find any resource.
1139
+            // Return an empty array just like before.
1140
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1141
+            return false;
1142
+        }
1143
+
1144
+        //check whether paged search should be attempted
1145
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, (int)$offset);
1146
+
1147
+        $sr = $this->invokeLDAPMethod('search', $cr, $base, $filter, $attr);
1148
+        // cannot use $cr anymore, might have changed in the previous call!
1149
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1150
+        if (!$this->ldap->isResource($sr) || $error !== 0) {
1151
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  ' . print_r($pagedSearchOK, true), ILogger::ERROR);
1152
+            return false;
1153
+        }
1154
+
1155
+        return [$sr, $pagedSearchOK];
1156
+    }
1157
+
1158
+    /**
1159
+     * processes an LDAP paged search operation
1160
+     *
1161
+     * @param resource $sr the array containing the LDAP search resources
1162
+     * @param int $foundItems number of results in the single search operation
1163
+     * @param int $limit maximum results to be counted
1164
+     * @param bool $pagedSearchOK whether a paged search has been executed
1165
+     * @param bool $skipHandling required for paged search when cookies to
1166
+     * prior results need to be gained
1167
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1168
+     * @throws ServerNotAvailableException
1169
+     */
1170
+    private function processPagedSearchStatus(
1171
+        $sr,
1172
+        int $foundItems,
1173
+        int $limit,
1174
+        bool $pagedSearchOK,
1175
+        bool $skipHandling
1176
+    ): bool {
1177
+        $cookie = null;
1178
+        if ($pagedSearchOK) {
1179
+            $cr = $this->connection->getConnectionResource();
1180
+            if ($this->ldap->controlPagedResultResponse($cr, $sr, $cookie)) {
1181
+                $this->lastCookie = $cookie;
1182
+            }
1183
+
1184
+            //browsing through prior pages to get the cookie for the new one
1185
+            if ($skipHandling) {
1186
+                return false;
1187
+            }
1188
+            // if count is bigger, then the server does not support
1189
+            // paged search. Instead, he did a normal search. We set a
1190
+            // flag here, so the callee knows how to deal with it.
1191
+            if ($foundItems <= $limit) {
1192
+                $this->pagedSearchedSuccessful = true;
1193
+            }
1194
+        } else {
1195
+            if (!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1196
+                \OC::$server->getLogger()->debug(
1197
+                    'Paged search was not available',
1198
+                    ['app' => 'user_ldap']
1199
+                );
1200
+            }
1201
+        }
1202
+        /* ++ Fixing RHDS searches with pages with zero results ++
1203 1203
 		 * Return cookie status. If we don't have more pages, with RHDS
1204 1204
 		 * cookie is null, with openldap cookie is an empty string and
1205 1205
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1206 1206
 		 */
1207
-		return !empty($cookie) || $cookie === '0';
1208
-	}
1209
-
1210
-	/**
1211
-	 * executes an LDAP search, but counts the results only
1212
-	 *
1213
-	 * @param string $filter the LDAP filter for the search
1214
-	 * @param array $bases an array containing the LDAP subtree(s) that shall be searched
1215
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1216
-	 * retrieved. Results will according to the order in the array.
1217
-	 * @param int $limit optional, maximum results to be counted
1218
-	 * @param int $offset optional, a starting point
1219
-	 * @param bool $skipHandling indicates whether the pages search operation is
1220
-	 * completed
1221
-	 * @return int|false Integer or false if the search could not be initialized
1222
-	 * @throws ServerNotAvailableException
1223
-	 */
1224
-	private function count(
1225
-		string $filter,
1226
-		array $bases,
1227
-		$attr = null,
1228
-		?int $limit = null,
1229
-		?int $offset = null,
1230
-		bool $skipHandling = false
1231
-	) {
1232
-		\OC::$server->getLogger()->debug('Count filter: {filter}', [
1233
-			'app' => 'user_ldap',
1234
-			'filter' => $filter
1235
-		]);
1236
-
1237
-		if (!is_null($attr) && !is_array($attr)) {
1238
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1239
-		}
1240
-
1241
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1242
-		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1243
-			$limitPerPage = $limit;
1244
-		}
1245
-
1246
-		$counter = 0;
1247
-		$count = null;
1248
-		$this->connection->getConnectionResource();
1249
-
1250
-		foreach ($bases as $base) {
1251
-			do {
1252
-				$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1253
-				if ($search === false) {
1254
-					return $counter > 0 ? $counter : false;
1255
-				}
1256
-				list($sr, $pagedSearchOK) = $search;
1257
-
1258
-				/* ++ Fixing RHDS searches with pages with zero results ++
1207
+        return !empty($cookie) || $cookie === '0';
1208
+    }
1209
+
1210
+    /**
1211
+     * executes an LDAP search, but counts the results only
1212
+     *
1213
+     * @param string $filter the LDAP filter for the search
1214
+     * @param array $bases an array containing the LDAP subtree(s) that shall be searched
1215
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1216
+     * retrieved. Results will according to the order in the array.
1217
+     * @param int $limit optional, maximum results to be counted
1218
+     * @param int $offset optional, a starting point
1219
+     * @param bool $skipHandling indicates whether the pages search operation is
1220
+     * completed
1221
+     * @return int|false Integer or false if the search could not be initialized
1222
+     * @throws ServerNotAvailableException
1223
+     */
1224
+    private function count(
1225
+        string $filter,
1226
+        array $bases,
1227
+        $attr = null,
1228
+        ?int $limit = null,
1229
+        ?int $offset = null,
1230
+        bool $skipHandling = false
1231
+    ) {
1232
+        \OC::$server->getLogger()->debug('Count filter: {filter}', [
1233
+            'app' => 'user_ldap',
1234
+            'filter' => $filter
1235
+        ]);
1236
+
1237
+        if (!is_null($attr) && !is_array($attr)) {
1238
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1239
+        }
1240
+
1241
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1242
+        if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1243
+            $limitPerPage = $limit;
1244
+        }
1245
+
1246
+        $counter = 0;
1247
+        $count = null;
1248
+        $this->connection->getConnectionResource();
1249
+
1250
+        foreach ($bases as $base) {
1251
+            do {
1252
+                $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1253
+                if ($search === false) {
1254
+                    return $counter > 0 ? $counter : false;
1255
+                }
1256
+                list($sr, $pagedSearchOK) = $search;
1257
+
1258
+                /* ++ Fixing RHDS searches with pages with zero results ++
1259 1259
 				 * countEntriesInSearchResults() method signature changed
1260 1260
 				 * by removing $limit and &$hasHitLimit parameters
1261 1261
 				 */
1262
-				$count = $this->countEntriesInSearchResults($sr);
1263
-				$counter += $count;
1262
+                $count = $this->countEntriesInSearchResults($sr);
1263
+                $counter += $count;
1264 1264
 
1265
-				$hasMorePages = $this->processPagedSearchStatus($sr, $count, $limitPerPage, $pagedSearchOK, $skipHandling);
1266
-				$offset += $limitPerPage;
1267
-				/* ++ Fixing RHDS searches with pages with zero results ++
1265
+                $hasMorePages = $this->processPagedSearchStatus($sr, $count, $limitPerPage, $pagedSearchOK, $skipHandling);
1266
+                $offset += $limitPerPage;
1267
+                /* ++ Fixing RHDS searches with pages with zero results ++
1268 1268
 				 * Continue now depends on $hasMorePages value
1269 1269
 				 */
1270
-				$continue = $pagedSearchOK && $hasMorePages;
1271
-			} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1272
-		}
1273
-
1274
-		return $counter;
1275
-	}
1276
-
1277
-	/**
1278
-	 * @param resource $sr
1279
-	 * @return int
1280
-	 * @throws ServerNotAvailableException
1281
-	 */
1282
-	private function countEntriesInSearchResults($sr): int {
1283
-		return (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $sr);
1284
-	}
1285
-
1286
-	/**
1287
-	 * Executes an LDAP search
1288
-	 *
1289
-	 * @throws ServerNotAvailableException
1290
-	 */
1291
-	public function search(
1292
-		string $filter,
1293
-		string $base,
1294
-		?array $attr = null,
1295
-		?int $limit = null,
1296
-		?int $offset = null,
1297
-		bool $skipHandling = false
1298
-	): array {
1299
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1300
-		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1301
-			$limitPerPage = $limit;
1302
-		}
1303
-
1304
-		if (!is_null($attr) && !is_array($attr)) {
1305
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1306
-		}
1307
-
1308
-		/* ++ Fixing RHDS searches with pages with zero results ++
1270
+                $continue = $pagedSearchOK && $hasMorePages;
1271
+            } while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1272
+        }
1273
+
1274
+        return $counter;
1275
+    }
1276
+
1277
+    /**
1278
+     * @param resource $sr
1279
+     * @return int
1280
+     * @throws ServerNotAvailableException
1281
+     */
1282
+    private function countEntriesInSearchResults($sr): int {
1283
+        return (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $sr);
1284
+    }
1285
+
1286
+    /**
1287
+     * Executes an LDAP search
1288
+     *
1289
+     * @throws ServerNotAvailableException
1290
+     */
1291
+    public function search(
1292
+        string $filter,
1293
+        string $base,
1294
+        ?array $attr = null,
1295
+        ?int $limit = null,
1296
+        ?int $offset = null,
1297
+        bool $skipHandling = false
1298
+    ): array {
1299
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1300
+        if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1301
+            $limitPerPage = $limit;
1302
+        }
1303
+
1304
+        if (!is_null($attr) && !is_array($attr)) {
1305
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1306
+        }
1307
+
1308
+        /* ++ Fixing RHDS searches with pages with zero results ++
1309 1309
 		 * As we can have pages with zero results and/or pages with less
1310 1310
 		 * than $limit results but with a still valid server 'cookie',
1311 1311
 		 * loops through until we get $continue equals true and
1312 1312
 		 * $findings['count'] < $limit
1313 1313
 		 */
1314
-		$findings = [];
1315
-		$savedoffset = $offset;
1316
-		$iFoundItems = 0;
1317
-
1318
-		do {
1319
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1320
-			if ($search === false) {
1321
-				return [];
1322
-			}
1323
-			list($sr, $pagedSearchOK) = $search;
1324
-			$cr = $this->connection->getConnectionResource();
1325
-
1326
-			if ($skipHandling) {
1327
-				//i.e. result do not need to be fetched, we just need the cookie
1328
-				//thus pass 1 or any other value as $iFoundItems because it is not
1329
-				//used
1330
-				$this->processPagedSearchStatus($sr, 1, $limitPerPage, $pagedSearchOK, $skipHandling);
1331
-				return [];
1332
-			}
1333
-
1334
-			$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $sr));
1335
-			$iFoundItems = max($iFoundItems, $findings['count']);
1336
-			unset($findings['count']);
1337
-
1338
-			$continue = $this->processPagedSearchStatus($sr, $iFoundItems, $limitPerPage, $pagedSearchOK, $skipHandling);
1339
-			$offset += $limitPerPage;
1340
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1341
-
1342
-		// resetting offset
1343
-		$offset = $savedoffset;
1344
-
1345
-		// if we're here, probably no connection resource is returned.
1346
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1347
-		if (is_null($findings)) {
1348
-			return [];
1349
-		}
1350
-
1351
-		if (!is_null($attr)) {
1352
-			$selection = [];
1353
-			$i = 0;
1354
-			foreach ($findings as $item) {
1355
-				if (!is_array($item)) {
1356
-					continue;
1357
-				}
1358
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1359
-				foreach ($attr as $key) {
1360
-					if (isset($item[$key])) {
1361
-						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1362
-							unset($item[$key]['count']);
1363
-						}
1364
-						if ($key !== 'dn') {
1365
-							if ($this->resemblesDN($key)) {
1366
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1367
-							} elseif ($key === 'objectguid' || $key === 'guid') {
1368
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1369
-							} else {
1370
-								$selection[$i][$key] = $item[$key];
1371
-							}
1372
-						} else {
1373
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1374
-						}
1375
-					}
1376
-				}
1377
-				$i++;
1378
-			}
1379
-			$findings = $selection;
1380
-		}
1381
-		//we slice the findings, when
1382
-		//a) paged search unsuccessful, though attempted
1383
-		//b) no paged search, but limit set
1384
-		if ((!$this->getPagedSearchResultState()
1385
-				&& $pagedSearchOK)
1386
-			|| (
1387
-				!$pagedSearchOK
1388
-				&& !is_null($limit)
1389
-			)
1390
-		) {
1391
-			$findings = array_slice($findings, (int)$offset, $limit);
1392
-		}
1393
-		return $findings;
1394
-	}
1395
-
1396
-	/**
1397
-	 * @param string $name
1398
-	 * @return string
1399
-	 * @throws \InvalidArgumentException
1400
-	 */
1401
-	public function sanitizeUsername($name) {
1402
-		$name = trim($name);
1403
-
1404
-		if ($this->connection->ldapIgnoreNamingRules) {
1405
-			return $name;
1406
-		}
1407
-
1408
-		// Transliteration to ASCII
1409
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1410
-		if ($transliterated !== false) {
1411
-			// depending on system config iconv can work or not
1412
-			$name = $transliterated;
1413
-		}
1414
-
1415
-		// Replacements
1416
-		$name = str_replace(' ', '_', $name);
1417
-
1418
-		// Every remaining disallowed characters will be removed
1419
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1420
-
1421
-		if ($name === '') {
1422
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1423
-		}
1424
-
1425
-		return $name;
1426
-	}
1427
-
1428
-	/**
1429
-	 * escapes (user provided) parts for LDAP filter
1430
-	 *
1431
-	 * @param string $input , the provided value
1432
-	 * @param bool $allowAsterisk whether in * at the beginning should be preserved
1433
-	 * @return string the escaped string
1434
-	 */
1435
-	public function escapeFilterPart($input, $allowAsterisk = false): string {
1436
-		$asterisk = '';
1437
-		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1438
-			$asterisk = '*';
1439
-			$input = mb_substr($input, 1, null, 'UTF-8');
1440
-		}
1441
-		$search = ['*', '\\', '(', ')'];
1442
-		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1443
-		return $asterisk . str_replace($search, $replace, $input);
1444
-	}
1445
-
1446
-	/**
1447
-	 * combines the input filters with AND
1448
-	 *
1449
-	 * @param string[] $filters the filters to connect
1450
-	 * @return string the combined filter
1451
-	 */
1452
-	public function combineFilterWithAnd($filters): string {
1453
-		return $this->combineFilter($filters, '&');
1454
-	}
1455
-
1456
-	/**
1457
-	 * combines the input filters with OR
1458
-	 *
1459
-	 * @param string[] $filters the filters to connect
1460
-	 * @return string the combined filter
1461
-	 * Combines Filter arguments with OR
1462
-	 */
1463
-	public function combineFilterWithOr($filters) {
1464
-		return $this->combineFilter($filters, '|');
1465
-	}
1466
-
1467
-	/**
1468
-	 * combines the input filters with given operator
1469
-	 *
1470
-	 * @param string[] $filters the filters to connect
1471
-	 * @param string $operator either & or |
1472
-	 * @return string the combined filter
1473
-	 */
1474
-	private function combineFilter($filters, $operator) {
1475
-		$combinedFilter = '(' . $operator;
1476
-		foreach ($filters as $filter) {
1477
-			if ($filter !== '' && $filter[0] !== '(') {
1478
-				$filter = '(' . $filter . ')';
1479
-			}
1480
-			$combinedFilter .= $filter;
1481
-		}
1482
-		$combinedFilter .= ')';
1483
-		return $combinedFilter;
1484
-	}
1485
-
1486
-	/**
1487
-	 * creates a filter part for to perform search for users
1488
-	 *
1489
-	 * @param string $search the search term
1490
-	 * @return string the final filter part to use in LDAP searches
1491
-	 */
1492
-	public function getFilterPartForUserSearch($search) {
1493
-		return $this->getFilterPartForSearch($search,
1494
-			$this->connection->ldapAttributesForUserSearch,
1495
-			$this->connection->ldapUserDisplayName);
1496
-	}
1497
-
1498
-	/**
1499
-	 * creates a filter part for to perform search for groups
1500
-	 *
1501
-	 * @param string $search the search term
1502
-	 * @return string the final filter part to use in LDAP searches
1503
-	 */
1504
-	public function getFilterPartForGroupSearch($search) {
1505
-		return $this->getFilterPartForSearch($search,
1506
-			$this->connection->ldapAttributesForGroupSearch,
1507
-			$this->connection->ldapGroupDisplayName);
1508
-	}
1509
-
1510
-	/**
1511
-	 * creates a filter part for searches by splitting up the given search
1512
-	 * string into single words
1513
-	 *
1514
-	 * @param string $search the search term
1515
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1516
-	 * otherwise it does not make sense :)
1517
-	 * @return string the final filter part to use in LDAP searches
1518
-	 * @throws DomainException
1519
-	 */
1520
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1521
-		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1522
-			throw new DomainException('searchAttributes must be an array with at least two string');
1523
-		}
1524
-		$searchWords = explode(' ', trim($search));
1525
-		$wordFilters = [];
1526
-		foreach ($searchWords as $word) {
1527
-			$word = $this->prepareSearchTerm($word);
1528
-			//every word needs to appear at least once
1529
-			$wordMatchOneAttrFilters = [];
1530
-			foreach ($searchAttributes as $attr) {
1531
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1532
-			}
1533
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1534
-		}
1535
-		return $this->combineFilterWithAnd($wordFilters);
1536
-	}
1537
-
1538
-	/**
1539
-	 * creates a filter part for searches
1540
-	 *
1541
-	 * @param string $search the search term
1542
-	 * @param string[]|null $searchAttributes
1543
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1544
-	 * did not define search attributes. Typically the display name attribute.
1545
-	 * @return string the final filter part to use in LDAP searches
1546
-	 */
1547
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1548
-		$filter = [];
1549
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1550
-		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1551
-			try {
1552
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1553
-			} catch (DomainException $e) {
1554
-				// Creating advanced filter for search failed, falling back to simple method. Edge case, but valid.
1555
-			}
1556
-		}
1557
-
1558
-		$search = $this->prepareSearchTerm($search);
1559
-		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1560
-			if ($fallbackAttribute === '') {
1561
-				return '';
1562
-			}
1563
-			$filter[] = $fallbackAttribute . '=' . $search;
1564
-		} else {
1565
-			foreach ($searchAttributes as $attribute) {
1566
-				$filter[] = $attribute . '=' . $search;
1567
-			}
1568
-		}
1569
-		if (count($filter) === 1) {
1570
-			return '(' . $filter[0] . ')';
1571
-		}
1572
-		return $this->combineFilterWithOr($filter);
1573
-	}
1574
-
1575
-	/**
1576
-	 * returns the search term depending on whether we are allowed
1577
-	 * list users found by ldap with the current input appended by
1578
-	 * a *
1579
-	 *
1580
-	 * @return string
1581
-	 */
1582
-	private function prepareSearchTerm($term) {
1583
-		$config = \OC::$server->getConfig();
1584
-
1585
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1586
-
1587
-		$result = $term;
1588
-		if ($term === '') {
1589
-			$result = '*';
1590
-		} elseif ($allowEnum !== 'no') {
1591
-			$result = $term . '*';
1592
-		}
1593
-		return $result;
1594
-	}
1595
-
1596
-	/**
1597
-	 * returns the filter used for counting users
1598
-	 *
1599
-	 * @return string
1600
-	 */
1601
-	public function getFilterForUserCount() {
1602
-		$filter = $this->combineFilterWithAnd([
1603
-			$this->connection->ldapUserFilter,
1604
-			$this->connection->ldapUserDisplayName . '=*'
1605
-		]);
1606
-
1607
-		return $filter;
1608
-	}
1609
-
1610
-	/**
1611
-	 * @param string $name
1612
-	 * @param string $password
1613
-	 * @return bool
1614
-	 */
1615
-	public function areCredentialsValid($name, $password) {
1616
-		$name = $this->helper->DNasBaseParameter($name);
1617
-		$testConnection = clone $this->connection;
1618
-		$credentials = [
1619
-			'ldapAgentName' => $name,
1620
-			'ldapAgentPassword' => $password
1621
-		];
1622
-		if (!$testConnection->setConfiguration($credentials)) {
1623
-			return false;
1624
-		}
1625
-		return $testConnection->bind();
1626
-	}
1627
-
1628
-	/**
1629
-	 * reverse lookup of a DN given a known UUID
1630
-	 *
1631
-	 * @param string $uuid
1632
-	 * @return string
1633
-	 * @throws \Exception
1634
-	 */
1635
-	public function getUserDnByUuid($uuid) {
1636
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1637
-		$filter = $this->connection->ldapUserFilter;
1638
-		$bases = $this->connection->ldapBaseUsers;
1639
-
1640
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1641
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1642
-			// existing DN to be able to reliably detect it.
1643
-			foreach ($bases as $base) {
1644
-				$result = $this->search($filter, $base, ['dn'], 1);
1645
-				if (!isset($result[0]) || !isset($result[0]['dn'])) {
1646
-					continue;
1647
-				}
1648
-				$dn = $result[0]['dn'][0];
1649
-				if ($hasFound = $this->detectUuidAttribute($dn, true)) {
1650
-					break;
1651
-				}
1652
-			}
1653
-			if (!isset($hasFound) || !$hasFound) {
1654
-				throw new \Exception('Cannot determine UUID attribute');
1655
-			}
1656
-		} else {
1657
-			// The UUID attribute is either known or an override is given.
1658
-			// By calling this method we ensure that $this->connection->$uuidAttr
1659
-			// is definitely set
1660
-			if (!$this->detectUuidAttribute('', true)) {
1661
-				throw new \Exception('Cannot determine UUID attribute');
1662
-			}
1663
-		}
1664
-
1665
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1666
-		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1667
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1668
-		}
1669
-
1670
-		$filter = $uuidAttr . '=' . $uuid;
1671
-		$result = $this->searchUsers($filter, ['dn'], 2);
1672
-		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1673
-			// we put the count into account to make sure that this is
1674
-			// really unique
1675
-			return $result[0]['dn'][0];
1676
-		}
1677
-
1678
-		throw new \Exception('Cannot determine UUID attribute');
1679
-	}
1680
-
1681
-	/**
1682
-	 * auto-detects the directory's UUID attribute
1683
-	 *
1684
-	 * @param string $dn a known DN used to check against
1685
-	 * @param bool $isUser
1686
-	 * @param bool $force the detection should be run, even if it is not set to auto
1687
-	 * @param array|null $ldapRecord
1688
-	 * @return bool true on success, false otherwise
1689
-	 * @throws ServerNotAvailableException
1690
-	 */
1691
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1692
-		if ($isUser) {
1693
-			$uuidAttr = 'ldapUuidUserAttribute';
1694
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1695
-		} else {
1696
-			$uuidAttr = 'ldapUuidGroupAttribute';
1697
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1698
-		}
1699
-
1700
-		if (!$force) {
1701
-			if ($this->connection->$uuidAttr !== 'auto') {
1702
-				return true;
1703
-			} elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1704
-				$this->connection->$uuidAttr = $uuidOverride;
1705
-				return true;
1706
-			}
1707
-
1708
-			$attribute = $this->connection->getFromCache($uuidAttr);
1709
-			if (!$attribute === null) {
1710
-				$this->connection->$uuidAttr = $attribute;
1711
-				return true;
1712
-			}
1713
-		}
1714
-
1715
-		foreach (self::UUID_ATTRIBUTES as $attribute) {
1716
-			if ($ldapRecord !== null) {
1717
-				// we have the info from LDAP already, we don't need to talk to the server again
1718
-				if (isset($ldapRecord[$attribute])) {
1719
-					$this->connection->$uuidAttr = $attribute;
1720
-					return true;
1721
-				}
1722
-			}
1723
-
1724
-			$value = $this->readAttribute($dn, $attribute);
1725
-			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1726
-				\OC::$server->getLogger()->debug(
1727
-					'Setting {attribute} as {subject}',
1728
-					[
1729
-						'app' => 'user_ldap',
1730
-						'attribute' => $attribute,
1731
-						'subject' => $uuidAttr
1732
-					]
1733
-				);
1734
-				$this->connection->$uuidAttr = $attribute;
1735
-				$this->connection->writeToCache($uuidAttr, $attribute);
1736
-				return true;
1737
-			}
1738
-		}
1739
-		\OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1740
-
1741
-		return false;
1742
-	}
1743
-
1744
-	/**
1745
-	 * @param string $dn
1746
-	 * @param bool $isUser
1747
-	 * @param null $ldapRecord
1748
-	 * @return bool|string
1749
-	 * @throws ServerNotAvailableException
1750
-	 */
1751
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1752
-		if ($isUser) {
1753
-			$uuidAttr = 'ldapUuidUserAttribute';
1754
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1755
-		} else {
1756
-			$uuidAttr = 'ldapUuidGroupAttribute';
1757
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1758
-		}
1759
-
1760
-		$uuid = false;
1761
-		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1762
-			$attr = $this->connection->$uuidAttr;
1763
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1764
-			if (!is_array($uuid)
1765
-				&& $uuidOverride !== ''
1766
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) {
1767
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1768
-					? $ldapRecord[$this->connection->$uuidAttr]
1769
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1770
-			}
1771
-			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1772
-				$uuid = $uuid[0];
1773
-			}
1774
-		}
1775
-
1776
-		return $uuid;
1777
-	}
1778
-
1779
-	/**
1780
-	 * converts a binary ObjectGUID into a string representation
1781
-	 *
1782
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1783
-	 * @return string
1784
-	 * @link https://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1785
-	 */
1786
-	private function convertObjectGUID2Str($oguid) {
1787
-		$hex_guid = bin2hex($oguid);
1788
-		$hex_guid_to_guid_str = '';
1789
-		for ($k = 1; $k <= 4; ++$k) {
1790
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1791
-		}
1792
-		$hex_guid_to_guid_str .= '-';
1793
-		for ($k = 1; $k <= 2; ++$k) {
1794
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1795
-		}
1796
-		$hex_guid_to_guid_str .= '-';
1797
-		for ($k = 1; $k <= 2; ++$k) {
1798
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1799
-		}
1800
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1801
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1802
-
1803
-		return strtoupper($hex_guid_to_guid_str);
1804
-	}
1805
-
1806
-	/**
1807
-	 * the first three blocks of the string-converted GUID happen to be in
1808
-	 * reverse order. In order to use it in a filter, this needs to be
1809
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1810
-	 * to every two hax figures.
1811
-	 *
1812
-	 * If an invalid string is passed, it will be returned without change.
1813
-	 *
1814
-	 * @param string $guid
1815
-	 * @return string
1816
-	 */
1817
-	public function formatGuid2ForFilterUser($guid) {
1818
-		if (!is_string($guid)) {
1819
-			throw new \InvalidArgumentException('String expected');
1820
-		}
1821
-		$blocks = explode('-', $guid);
1822
-		if (count($blocks) !== 5) {
1823
-			/*
1314
+        $findings = [];
1315
+        $savedoffset = $offset;
1316
+        $iFoundItems = 0;
1317
+
1318
+        do {
1319
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1320
+            if ($search === false) {
1321
+                return [];
1322
+            }
1323
+            list($sr, $pagedSearchOK) = $search;
1324
+            $cr = $this->connection->getConnectionResource();
1325
+
1326
+            if ($skipHandling) {
1327
+                //i.e. result do not need to be fetched, we just need the cookie
1328
+                //thus pass 1 or any other value as $iFoundItems because it is not
1329
+                //used
1330
+                $this->processPagedSearchStatus($sr, 1, $limitPerPage, $pagedSearchOK, $skipHandling);
1331
+                return [];
1332
+            }
1333
+
1334
+            $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $sr));
1335
+            $iFoundItems = max($iFoundItems, $findings['count']);
1336
+            unset($findings['count']);
1337
+
1338
+            $continue = $this->processPagedSearchStatus($sr, $iFoundItems, $limitPerPage, $pagedSearchOK, $skipHandling);
1339
+            $offset += $limitPerPage;
1340
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1341
+
1342
+        // resetting offset
1343
+        $offset = $savedoffset;
1344
+
1345
+        // if we're here, probably no connection resource is returned.
1346
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1347
+        if (is_null($findings)) {
1348
+            return [];
1349
+        }
1350
+
1351
+        if (!is_null($attr)) {
1352
+            $selection = [];
1353
+            $i = 0;
1354
+            foreach ($findings as $item) {
1355
+                if (!is_array($item)) {
1356
+                    continue;
1357
+                }
1358
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1359
+                foreach ($attr as $key) {
1360
+                    if (isset($item[$key])) {
1361
+                        if (is_array($item[$key]) && isset($item[$key]['count'])) {
1362
+                            unset($item[$key]['count']);
1363
+                        }
1364
+                        if ($key !== 'dn') {
1365
+                            if ($this->resemblesDN($key)) {
1366
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1367
+                            } elseif ($key === 'objectguid' || $key === 'guid') {
1368
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1369
+                            } else {
1370
+                                $selection[$i][$key] = $item[$key];
1371
+                            }
1372
+                        } else {
1373
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1374
+                        }
1375
+                    }
1376
+                }
1377
+                $i++;
1378
+            }
1379
+            $findings = $selection;
1380
+        }
1381
+        //we slice the findings, when
1382
+        //a) paged search unsuccessful, though attempted
1383
+        //b) no paged search, but limit set
1384
+        if ((!$this->getPagedSearchResultState()
1385
+                && $pagedSearchOK)
1386
+            || (
1387
+                !$pagedSearchOK
1388
+                && !is_null($limit)
1389
+            )
1390
+        ) {
1391
+            $findings = array_slice($findings, (int)$offset, $limit);
1392
+        }
1393
+        return $findings;
1394
+    }
1395
+
1396
+    /**
1397
+     * @param string $name
1398
+     * @return string
1399
+     * @throws \InvalidArgumentException
1400
+     */
1401
+    public function sanitizeUsername($name) {
1402
+        $name = trim($name);
1403
+
1404
+        if ($this->connection->ldapIgnoreNamingRules) {
1405
+            return $name;
1406
+        }
1407
+
1408
+        // Transliteration to ASCII
1409
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1410
+        if ($transliterated !== false) {
1411
+            // depending on system config iconv can work or not
1412
+            $name = $transliterated;
1413
+        }
1414
+
1415
+        // Replacements
1416
+        $name = str_replace(' ', '_', $name);
1417
+
1418
+        // Every remaining disallowed characters will be removed
1419
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1420
+
1421
+        if ($name === '') {
1422
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1423
+        }
1424
+
1425
+        return $name;
1426
+    }
1427
+
1428
+    /**
1429
+     * escapes (user provided) parts for LDAP filter
1430
+     *
1431
+     * @param string $input , the provided value
1432
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1433
+     * @return string the escaped string
1434
+     */
1435
+    public function escapeFilterPart($input, $allowAsterisk = false): string {
1436
+        $asterisk = '';
1437
+        if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1438
+            $asterisk = '*';
1439
+            $input = mb_substr($input, 1, null, 'UTF-8');
1440
+        }
1441
+        $search = ['*', '\\', '(', ')'];
1442
+        $replace = ['\\*', '\\\\', '\\(', '\\)'];
1443
+        return $asterisk . str_replace($search, $replace, $input);
1444
+    }
1445
+
1446
+    /**
1447
+     * combines the input filters with AND
1448
+     *
1449
+     * @param string[] $filters the filters to connect
1450
+     * @return string the combined filter
1451
+     */
1452
+    public function combineFilterWithAnd($filters): string {
1453
+        return $this->combineFilter($filters, '&');
1454
+    }
1455
+
1456
+    /**
1457
+     * combines the input filters with OR
1458
+     *
1459
+     * @param string[] $filters the filters to connect
1460
+     * @return string the combined filter
1461
+     * Combines Filter arguments with OR
1462
+     */
1463
+    public function combineFilterWithOr($filters) {
1464
+        return $this->combineFilter($filters, '|');
1465
+    }
1466
+
1467
+    /**
1468
+     * combines the input filters with given operator
1469
+     *
1470
+     * @param string[] $filters the filters to connect
1471
+     * @param string $operator either & or |
1472
+     * @return string the combined filter
1473
+     */
1474
+    private function combineFilter($filters, $operator) {
1475
+        $combinedFilter = '(' . $operator;
1476
+        foreach ($filters as $filter) {
1477
+            if ($filter !== '' && $filter[0] !== '(') {
1478
+                $filter = '(' . $filter . ')';
1479
+            }
1480
+            $combinedFilter .= $filter;
1481
+        }
1482
+        $combinedFilter .= ')';
1483
+        return $combinedFilter;
1484
+    }
1485
+
1486
+    /**
1487
+     * creates a filter part for to perform search for users
1488
+     *
1489
+     * @param string $search the search term
1490
+     * @return string the final filter part to use in LDAP searches
1491
+     */
1492
+    public function getFilterPartForUserSearch($search) {
1493
+        return $this->getFilterPartForSearch($search,
1494
+            $this->connection->ldapAttributesForUserSearch,
1495
+            $this->connection->ldapUserDisplayName);
1496
+    }
1497
+
1498
+    /**
1499
+     * creates a filter part for to perform search for groups
1500
+     *
1501
+     * @param string $search the search term
1502
+     * @return string the final filter part to use in LDAP searches
1503
+     */
1504
+    public function getFilterPartForGroupSearch($search) {
1505
+        return $this->getFilterPartForSearch($search,
1506
+            $this->connection->ldapAttributesForGroupSearch,
1507
+            $this->connection->ldapGroupDisplayName);
1508
+    }
1509
+
1510
+    /**
1511
+     * creates a filter part for searches by splitting up the given search
1512
+     * string into single words
1513
+     *
1514
+     * @param string $search the search term
1515
+     * @param string[] $searchAttributes needs to have at least two attributes,
1516
+     * otherwise it does not make sense :)
1517
+     * @return string the final filter part to use in LDAP searches
1518
+     * @throws DomainException
1519
+     */
1520
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1521
+        if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1522
+            throw new DomainException('searchAttributes must be an array with at least two string');
1523
+        }
1524
+        $searchWords = explode(' ', trim($search));
1525
+        $wordFilters = [];
1526
+        foreach ($searchWords as $word) {
1527
+            $word = $this->prepareSearchTerm($word);
1528
+            //every word needs to appear at least once
1529
+            $wordMatchOneAttrFilters = [];
1530
+            foreach ($searchAttributes as $attr) {
1531
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1532
+            }
1533
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1534
+        }
1535
+        return $this->combineFilterWithAnd($wordFilters);
1536
+    }
1537
+
1538
+    /**
1539
+     * creates a filter part for searches
1540
+     *
1541
+     * @param string $search the search term
1542
+     * @param string[]|null $searchAttributes
1543
+     * @param string $fallbackAttribute a fallback attribute in case the user
1544
+     * did not define search attributes. Typically the display name attribute.
1545
+     * @return string the final filter part to use in LDAP searches
1546
+     */
1547
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1548
+        $filter = [];
1549
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1550
+        if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1551
+            try {
1552
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1553
+            } catch (DomainException $e) {
1554
+                // Creating advanced filter for search failed, falling back to simple method. Edge case, but valid.
1555
+            }
1556
+        }
1557
+
1558
+        $search = $this->prepareSearchTerm($search);
1559
+        if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1560
+            if ($fallbackAttribute === '') {
1561
+                return '';
1562
+            }
1563
+            $filter[] = $fallbackAttribute . '=' . $search;
1564
+        } else {
1565
+            foreach ($searchAttributes as $attribute) {
1566
+                $filter[] = $attribute . '=' . $search;
1567
+            }
1568
+        }
1569
+        if (count($filter) === 1) {
1570
+            return '(' . $filter[0] . ')';
1571
+        }
1572
+        return $this->combineFilterWithOr($filter);
1573
+    }
1574
+
1575
+    /**
1576
+     * returns the search term depending on whether we are allowed
1577
+     * list users found by ldap with the current input appended by
1578
+     * a *
1579
+     *
1580
+     * @return string
1581
+     */
1582
+    private function prepareSearchTerm($term) {
1583
+        $config = \OC::$server->getConfig();
1584
+
1585
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1586
+
1587
+        $result = $term;
1588
+        if ($term === '') {
1589
+            $result = '*';
1590
+        } elseif ($allowEnum !== 'no') {
1591
+            $result = $term . '*';
1592
+        }
1593
+        return $result;
1594
+    }
1595
+
1596
+    /**
1597
+     * returns the filter used for counting users
1598
+     *
1599
+     * @return string
1600
+     */
1601
+    public function getFilterForUserCount() {
1602
+        $filter = $this->combineFilterWithAnd([
1603
+            $this->connection->ldapUserFilter,
1604
+            $this->connection->ldapUserDisplayName . '=*'
1605
+        ]);
1606
+
1607
+        return $filter;
1608
+    }
1609
+
1610
+    /**
1611
+     * @param string $name
1612
+     * @param string $password
1613
+     * @return bool
1614
+     */
1615
+    public function areCredentialsValid($name, $password) {
1616
+        $name = $this->helper->DNasBaseParameter($name);
1617
+        $testConnection = clone $this->connection;
1618
+        $credentials = [
1619
+            'ldapAgentName' => $name,
1620
+            'ldapAgentPassword' => $password
1621
+        ];
1622
+        if (!$testConnection->setConfiguration($credentials)) {
1623
+            return false;
1624
+        }
1625
+        return $testConnection->bind();
1626
+    }
1627
+
1628
+    /**
1629
+     * reverse lookup of a DN given a known UUID
1630
+     *
1631
+     * @param string $uuid
1632
+     * @return string
1633
+     * @throws \Exception
1634
+     */
1635
+    public function getUserDnByUuid($uuid) {
1636
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1637
+        $filter = $this->connection->ldapUserFilter;
1638
+        $bases = $this->connection->ldapBaseUsers;
1639
+
1640
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1641
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1642
+            // existing DN to be able to reliably detect it.
1643
+            foreach ($bases as $base) {
1644
+                $result = $this->search($filter, $base, ['dn'], 1);
1645
+                if (!isset($result[0]) || !isset($result[0]['dn'])) {
1646
+                    continue;
1647
+                }
1648
+                $dn = $result[0]['dn'][0];
1649
+                if ($hasFound = $this->detectUuidAttribute($dn, true)) {
1650
+                    break;
1651
+                }
1652
+            }
1653
+            if (!isset($hasFound) || !$hasFound) {
1654
+                throw new \Exception('Cannot determine UUID attribute');
1655
+            }
1656
+        } else {
1657
+            // The UUID attribute is either known or an override is given.
1658
+            // By calling this method we ensure that $this->connection->$uuidAttr
1659
+            // is definitely set
1660
+            if (!$this->detectUuidAttribute('', true)) {
1661
+                throw new \Exception('Cannot determine UUID attribute');
1662
+            }
1663
+        }
1664
+
1665
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1666
+        if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1667
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1668
+        }
1669
+
1670
+        $filter = $uuidAttr . '=' . $uuid;
1671
+        $result = $this->searchUsers($filter, ['dn'], 2);
1672
+        if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1673
+            // we put the count into account to make sure that this is
1674
+            // really unique
1675
+            return $result[0]['dn'][0];
1676
+        }
1677
+
1678
+        throw new \Exception('Cannot determine UUID attribute');
1679
+    }
1680
+
1681
+    /**
1682
+     * auto-detects the directory's UUID attribute
1683
+     *
1684
+     * @param string $dn a known DN used to check against
1685
+     * @param bool $isUser
1686
+     * @param bool $force the detection should be run, even if it is not set to auto
1687
+     * @param array|null $ldapRecord
1688
+     * @return bool true on success, false otherwise
1689
+     * @throws ServerNotAvailableException
1690
+     */
1691
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1692
+        if ($isUser) {
1693
+            $uuidAttr = 'ldapUuidUserAttribute';
1694
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1695
+        } else {
1696
+            $uuidAttr = 'ldapUuidGroupAttribute';
1697
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1698
+        }
1699
+
1700
+        if (!$force) {
1701
+            if ($this->connection->$uuidAttr !== 'auto') {
1702
+                return true;
1703
+            } elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1704
+                $this->connection->$uuidAttr = $uuidOverride;
1705
+                return true;
1706
+            }
1707
+
1708
+            $attribute = $this->connection->getFromCache($uuidAttr);
1709
+            if (!$attribute === null) {
1710
+                $this->connection->$uuidAttr = $attribute;
1711
+                return true;
1712
+            }
1713
+        }
1714
+
1715
+        foreach (self::UUID_ATTRIBUTES as $attribute) {
1716
+            if ($ldapRecord !== null) {
1717
+                // we have the info from LDAP already, we don't need to talk to the server again
1718
+                if (isset($ldapRecord[$attribute])) {
1719
+                    $this->connection->$uuidAttr = $attribute;
1720
+                    return true;
1721
+                }
1722
+            }
1723
+
1724
+            $value = $this->readAttribute($dn, $attribute);
1725
+            if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1726
+                \OC::$server->getLogger()->debug(
1727
+                    'Setting {attribute} as {subject}',
1728
+                    [
1729
+                        'app' => 'user_ldap',
1730
+                        'attribute' => $attribute,
1731
+                        'subject' => $uuidAttr
1732
+                    ]
1733
+                );
1734
+                $this->connection->$uuidAttr = $attribute;
1735
+                $this->connection->writeToCache($uuidAttr, $attribute);
1736
+                return true;
1737
+            }
1738
+        }
1739
+        \OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1740
+
1741
+        return false;
1742
+    }
1743
+
1744
+    /**
1745
+     * @param string $dn
1746
+     * @param bool $isUser
1747
+     * @param null $ldapRecord
1748
+     * @return bool|string
1749
+     * @throws ServerNotAvailableException
1750
+     */
1751
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1752
+        if ($isUser) {
1753
+            $uuidAttr = 'ldapUuidUserAttribute';
1754
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1755
+        } else {
1756
+            $uuidAttr = 'ldapUuidGroupAttribute';
1757
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1758
+        }
1759
+
1760
+        $uuid = false;
1761
+        if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1762
+            $attr = $this->connection->$uuidAttr;
1763
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1764
+            if (!is_array($uuid)
1765
+                && $uuidOverride !== ''
1766
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) {
1767
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1768
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1769
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1770
+            }
1771
+            if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1772
+                $uuid = $uuid[0];
1773
+            }
1774
+        }
1775
+
1776
+        return $uuid;
1777
+    }
1778
+
1779
+    /**
1780
+     * converts a binary ObjectGUID into a string representation
1781
+     *
1782
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1783
+     * @return string
1784
+     * @link https://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1785
+     */
1786
+    private function convertObjectGUID2Str($oguid) {
1787
+        $hex_guid = bin2hex($oguid);
1788
+        $hex_guid_to_guid_str = '';
1789
+        for ($k = 1; $k <= 4; ++$k) {
1790
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1791
+        }
1792
+        $hex_guid_to_guid_str .= '-';
1793
+        for ($k = 1; $k <= 2; ++$k) {
1794
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1795
+        }
1796
+        $hex_guid_to_guid_str .= '-';
1797
+        for ($k = 1; $k <= 2; ++$k) {
1798
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1799
+        }
1800
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1801
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1802
+
1803
+        return strtoupper($hex_guid_to_guid_str);
1804
+    }
1805
+
1806
+    /**
1807
+     * the first three blocks of the string-converted GUID happen to be in
1808
+     * reverse order. In order to use it in a filter, this needs to be
1809
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1810
+     * to every two hax figures.
1811
+     *
1812
+     * If an invalid string is passed, it will be returned without change.
1813
+     *
1814
+     * @param string $guid
1815
+     * @return string
1816
+     */
1817
+    public function formatGuid2ForFilterUser($guid) {
1818
+        if (!is_string($guid)) {
1819
+            throw new \InvalidArgumentException('String expected');
1820
+        }
1821
+        $blocks = explode('-', $guid);
1822
+        if (count($blocks) !== 5) {
1823
+            /*
1824 1824
 			 * Why not throw an Exception instead? This method is a utility
1825 1825
 			 * called only when trying to figure out whether a "missing" known
1826 1826
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1831,246 +1831,246 @@  discard block
 block discarded – undo
1831 1831
 			 * an exception here would kill the experience for a valid, acting
1832 1832
 			 * user. Instead we write a log message.
1833 1833
 			 */
1834
-			\OC::$server->getLogger()->info(
1835
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1836
-				'({uuid}) probably does not match UUID configuration.',
1837
-				['app' => 'user_ldap', 'uuid' => $guid]
1838
-			);
1839
-			return $guid;
1840
-		}
1841
-		for ($i = 0; $i < 3; $i++) {
1842
-			$pairs = str_split($blocks[$i], 2);
1843
-			$pairs = array_reverse($pairs);
1844
-			$blocks[$i] = implode('', $pairs);
1845
-		}
1846
-		for ($i = 0; $i < 5; $i++) {
1847
-			$pairs = str_split($blocks[$i], 2);
1848
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1849
-		}
1850
-		return implode('', $blocks);
1851
-	}
1852
-
1853
-	/**
1854
-	 * gets a SID of the domain of the given dn
1855
-	 *
1856
-	 * @param string $dn
1857
-	 * @return string|bool
1858
-	 * @throws ServerNotAvailableException
1859
-	 */
1860
-	public function getSID($dn) {
1861
-		$domainDN = $this->getDomainDNFromDN($dn);
1862
-		$cacheKey = 'getSID-' . $domainDN;
1863
-		$sid = $this->connection->getFromCache($cacheKey);
1864
-		if (!is_null($sid)) {
1865
-			return $sid;
1866
-		}
1867
-
1868
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1869
-		if (!is_array($objectSid) || empty($objectSid)) {
1870
-			$this->connection->writeToCache($cacheKey, false);
1871
-			return false;
1872
-		}
1873
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1874
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1875
-
1876
-		return $domainObjectSid;
1877
-	}
1878
-
1879
-	/**
1880
-	 * converts a binary SID into a string representation
1881
-	 *
1882
-	 * @param string $sid
1883
-	 * @return string
1884
-	 */
1885
-	public function convertSID2Str($sid) {
1886
-		// The format of a SID binary string is as follows:
1887
-		// 1 byte for the revision level
1888
-		// 1 byte for the number n of variable sub-ids
1889
-		// 6 bytes for identifier authority value
1890
-		// n*4 bytes for n sub-ids
1891
-		//
1892
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1893
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1894
-		$revision = ord($sid[0]);
1895
-		$numberSubID = ord($sid[1]);
1896
-
1897
-		$subIdStart = 8; // 1 + 1 + 6
1898
-		$subIdLength = 4;
1899
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1900
-			// Incorrect number of bytes present.
1901
-			return '';
1902
-		}
1903
-
1904
-		// 6 bytes = 48 bits can be represented using floats without loss of
1905
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1906
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1907
-
1908
-		$subIDs = [];
1909
-		for ($i = 0; $i < $numberSubID; $i++) {
1910
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1911
-			$subIDs[] = sprintf('%u', $subID[1]);
1912
-		}
1913
-
1914
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1915
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1916
-	}
1917
-
1918
-	/**
1919
-	 * checks if the given DN is part of the given base DN(s)
1920
-	 *
1921
-	 * @param string $dn the DN
1922
-	 * @param string[] $bases array containing the allowed base DN or DNs
1923
-	 * @return bool
1924
-	 */
1925
-	public function isDNPartOfBase($dn, $bases) {
1926
-		$belongsToBase = false;
1927
-		$bases = $this->helper->sanitizeDN($bases);
1928
-
1929
-		foreach ($bases as $base) {
1930
-			$belongsToBase = true;
1931
-			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1932
-				$belongsToBase = false;
1933
-			}
1934
-			if ($belongsToBase) {
1935
-				break;
1936
-			}
1937
-		}
1938
-		return $belongsToBase;
1939
-	}
1940
-
1941
-	/**
1942
-	 * resets a running Paged Search operation
1943
-	 *
1944
-	 * @throws ServerNotAvailableException
1945
-	 */
1946
-	private function abandonPagedSearch() {
1947
-		if ($this->lastCookie === '') {
1948
-			return;
1949
-		}
1950
-		$cr = $this->connection->getConnectionResource();
1951
-		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false);
1952
-		$this->getPagedSearchResultState();
1953
-		$this->lastCookie = '';
1954
-	}
1955
-
1956
-	/**
1957
-	 * checks whether an LDAP paged search operation has more pages that can be
1958
-	 * retrieved, typically when offset and limit are provided.
1959
-	 *
1960
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1961
-	 * be reset by other operations. Best, call it immediately after a search(),
1962
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1963
-	 * well. Don't rely on it with any fetchList-method.
1964
-	 *
1965
-	 * @return bool
1966
-	 */
1967
-	public function hasMoreResults() {
1968
-		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1969
-			// as in RFC 2696, when all results are returned, the cookie will
1970
-			// be empty.
1971
-			return false;
1972
-		}
1973
-
1974
-		return true;
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
-	 *
1980
-	 * @return boolean|null true on success, null or false otherwise
1981
-	 */
1982
-	public function getPagedSearchResultState() {
1983
-		$result = $this->pagedSearchedSuccessful;
1984
-		$this->pagedSearchedSuccessful = null;
1985
-		return $result;
1986
-	}
1987
-
1988
-	/**
1989
-	 * Prepares a paged search, if possible
1990
-	 *
1991
-	 * @param string $filter the LDAP filter for the search
1992
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1993
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1994
-	 * @param int $limit
1995
-	 * @param int $offset
1996
-	 * @return bool|true
1997
-	 * @throws ServerNotAvailableException
1998
-	 */
1999
-	private function initPagedSearch(
2000
-		string $filter,
2001
-		string $base,
2002
-		?array $attr,
2003
-		int $limit,
2004
-		int $offset
2005
-	): bool {
2006
-		$pagedSearchOK = false;
2007
-		if ($limit !== 0) {
2008
-			\OC::$server->getLogger()->debug(
2009
-				'initializing paged search for filter {filter}, base {base}, attr {attr}, limit {limit}, offset {offset}',
2010
-				[
2011
-					'app' => 'user_ldap',
2012
-					'filter' => $filter,
2013
-					'base' => $base,
2014
-					'attr' => $attr,
2015
-					'limit' => $limit,
2016
-					'offset' => $offset
2017
-				]
2018
-			);
2019
-			//get the cookie from the search for the previous search, required by LDAP
2020
-			if (empty($this->lastCookie) && $this->lastCookie !== "0" && ($offset > 0)) {
2021
-				// no cookie known from a potential previous search. We need
2022
-				// to start from 0 to come to the desired page. cookie value
2023
-				// of '0' is valid, because 389ds
2024
-				$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2025
-				$this->search($filter, $base, $attr, $limit, $reOffset, true);
2026
-				if (!$this->hasMoreResults()) {
2027
-					// when the cookie is reset with != 0 offset, there are no further
2028
-					// results, so stop.
2029
-					return false;
2030
-				}
2031
-			}
2032
-			if ($this->lastCookie !== '' && $offset === 0) {
2033
-				//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2034
-				$this->abandonPagedSearch();
2035
-			}
2036
-			$pagedSearchOK = true === $this->invokeLDAPMethod(
2037
-					'controlPagedResult', $this->connection->getConnectionResource(), $limit, false
2038
-				);
2039
-			if ($pagedSearchOK) {
2040
-				\OC::$server->getLogger()->debug('Ready for a paged search', ['app' => 'user_ldap']);
2041
-			}
2042
-			/* ++ Fixing RHDS searches with pages with zero results ++
1834
+            \OC::$server->getLogger()->info(
1835
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1836
+                '({uuid}) probably does not match UUID configuration.',
1837
+                ['app' => 'user_ldap', 'uuid' => $guid]
1838
+            );
1839
+            return $guid;
1840
+        }
1841
+        for ($i = 0; $i < 3; $i++) {
1842
+            $pairs = str_split($blocks[$i], 2);
1843
+            $pairs = array_reverse($pairs);
1844
+            $blocks[$i] = implode('', $pairs);
1845
+        }
1846
+        for ($i = 0; $i < 5; $i++) {
1847
+            $pairs = str_split($blocks[$i], 2);
1848
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1849
+        }
1850
+        return implode('', $blocks);
1851
+    }
1852
+
1853
+    /**
1854
+     * gets a SID of the domain of the given dn
1855
+     *
1856
+     * @param string $dn
1857
+     * @return string|bool
1858
+     * @throws ServerNotAvailableException
1859
+     */
1860
+    public function getSID($dn) {
1861
+        $domainDN = $this->getDomainDNFromDN($dn);
1862
+        $cacheKey = 'getSID-' . $domainDN;
1863
+        $sid = $this->connection->getFromCache($cacheKey);
1864
+        if (!is_null($sid)) {
1865
+            return $sid;
1866
+        }
1867
+
1868
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1869
+        if (!is_array($objectSid) || empty($objectSid)) {
1870
+            $this->connection->writeToCache($cacheKey, false);
1871
+            return false;
1872
+        }
1873
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1874
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1875
+
1876
+        return $domainObjectSid;
1877
+    }
1878
+
1879
+    /**
1880
+     * converts a binary SID into a string representation
1881
+     *
1882
+     * @param string $sid
1883
+     * @return string
1884
+     */
1885
+    public function convertSID2Str($sid) {
1886
+        // The format of a SID binary string is as follows:
1887
+        // 1 byte for the revision level
1888
+        // 1 byte for the number n of variable sub-ids
1889
+        // 6 bytes for identifier authority value
1890
+        // n*4 bytes for n sub-ids
1891
+        //
1892
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1893
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1894
+        $revision = ord($sid[0]);
1895
+        $numberSubID = ord($sid[1]);
1896
+
1897
+        $subIdStart = 8; // 1 + 1 + 6
1898
+        $subIdLength = 4;
1899
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1900
+            // Incorrect number of bytes present.
1901
+            return '';
1902
+        }
1903
+
1904
+        // 6 bytes = 48 bits can be represented using floats without loss of
1905
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1906
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1907
+
1908
+        $subIDs = [];
1909
+        for ($i = 0; $i < $numberSubID; $i++) {
1910
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1911
+            $subIDs[] = sprintf('%u', $subID[1]);
1912
+        }
1913
+
1914
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1915
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1916
+    }
1917
+
1918
+    /**
1919
+     * checks if the given DN is part of the given base DN(s)
1920
+     *
1921
+     * @param string $dn the DN
1922
+     * @param string[] $bases array containing the allowed base DN or DNs
1923
+     * @return bool
1924
+     */
1925
+    public function isDNPartOfBase($dn, $bases) {
1926
+        $belongsToBase = false;
1927
+        $bases = $this->helper->sanitizeDN($bases);
1928
+
1929
+        foreach ($bases as $base) {
1930
+            $belongsToBase = true;
1931
+            if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1932
+                $belongsToBase = false;
1933
+            }
1934
+            if ($belongsToBase) {
1935
+                break;
1936
+            }
1937
+        }
1938
+        return $belongsToBase;
1939
+    }
1940
+
1941
+    /**
1942
+     * resets a running Paged Search operation
1943
+     *
1944
+     * @throws ServerNotAvailableException
1945
+     */
1946
+    private function abandonPagedSearch() {
1947
+        if ($this->lastCookie === '') {
1948
+            return;
1949
+        }
1950
+        $cr = $this->connection->getConnectionResource();
1951
+        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false);
1952
+        $this->getPagedSearchResultState();
1953
+        $this->lastCookie = '';
1954
+    }
1955
+
1956
+    /**
1957
+     * checks whether an LDAP paged search operation has more pages that can be
1958
+     * retrieved, typically when offset and limit are provided.
1959
+     *
1960
+     * Be very careful to use it: the last cookie value, which is inspected, can
1961
+     * be reset by other operations. Best, call it immediately after a search(),
1962
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1963
+     * well. Don't rely on it with any fetchList-method.
1964
+     *
1965
+     * @return bool
1966
+     */
1967
+    public function hasMoreResults() {
1968
+        if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1969
+            // as in RFC 2696, when all results are returned, the cookie will
1970
+            // be empty.
1971
+            return false;
1972
+        }
1973
+
1974
+        return true;
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
+     *
1980
+     * @return boolean|null true on success, null or false otherwise
1981
+     */
1982
+    public function getPagedSearchResultState() {
1983
+        $result = $this->pagedSearchedSuccessful;
1984
+        $this->pagedSearchedSuccessful = null;
1985
+        return $result;
1986
+    }
1987
+
1988
+    /**
1989
+     * Prepares a paged search, if possible
1990
+     *
1991
+     * @param string $filter the LDAP filter for the search
1992
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1993
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1994
+     * @param int $limit
1995
+     * @param int $offset
1996
+     * @return bool|true
1997
+     * @throws ServerNotAvailableException
1998
+     */
1999
+    private function initPagedSearch(
2000
+        string $filter,
2001
+        string $base,
2002
+        ?array $attr,
2003
+        int $limit,
2004
+        int $offset
2005
+    ): bool {
2006
+        $pagedSearchOK = false;
2007
+        if ($limit !== 0) {
2008
+            \OC::$server->getLogger()->debug(
2009
+                'initializing paged search for filter {filter}, base {base}, attr {attr}, limit {limit}, offset {offset}',
2010
+                [
2011
+                    'app' => 'user_ldap',
2012
+                    'filter' => $filter,
2013
+                    'base' => $base,
2014
+                    'attr' => $attr,
2015
+                    'limit' => $limit,
2016
+                    'offset' => $offset
2017
+                ]
2018
+            );
2019
+            //get the cookie from the search for the previous search, required by LDAP
2020
+            if (empty($this->lastCookie) && $this->lastCookie !== "0" && ($offset > 0)) {
2021
+                // no cookie known from a potential previous search. We need
2022
+                // to start from 0 to come to the desired page. cookie value
2023
+                // of '0' is valid, because 389ds
2024
+                $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2025
+                $this->search($filter, $base, $attr, $limit, $reOffset, true);
2026
+                if (!$this->hasMoreResults()) {
2027
+                    // when the cookie is reset with != 0 offset, there are no further
2028
+                    // results, so stop.
2029
+                    return false;
2030
+                }
2031
+            }
2032
+            if ($this->lastCookie !== '' && $offset === 0) {
2033
+                //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2034
+                $this->abandonPagedSearch();
2035
+            }
2036
+            $pagedSearchOK = true === $this->invokeLDAPMethod(
2037
+                    'controlPagedResult', $this->connection->getConnectionResource(), $limit, false
2038
+                );
2039
+            if ($pagedSearchOK) {
2040
+                \OC::$server->getLogger()->debug('Ready for a paged search', ['app' => 'user_ldap']);
2041
+            }
2042
+            /* ++ Fixing RHDS searches with pages with zero results ++
2043 2043
 			 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
2044 2044
 			 * due to pages with zero results.
2045 2045
 			 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
2046 2046
 			 * if we don't have a previous paged search.
2047 2047
 			 */
2048
-		} elseif ($limit === 0 && !empty($this->lastCookie)) {
2049
-			// a search without limit was requested. However, if we do use
2050
-			// Paged Search once, we always must do it. This requires us to
2051
-			// initialize it with the configured page size.
2052
-			$this->abandonPagedSearch();
2053
-			// in case someone set it to 0 … use 500, otherwise no results will
2054
-			// be returned.
2055
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2056
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2057
-				$this->connection->getConnectionResource(),
2058
-				$pageSize, false);
2059
-		}
2060
-
2061
-		return $pagedSearchOK;
2062
-	}
2063
-
2064
-	/**
2065
-	 * Is more than one $attr used for search?
2066
-	 *
2067
-	 * @param string|string[]|null $attr
2068
-	 * @return bool
2069
-	 */
2070
-	private function manyAttributes($attr): bool {
2071
-		if (\is_array($attr)) {
2072
-			return \count($attr) > 1;
2073
-		}
2074
-		return false;
2075
-	}
2048
+        } elseif ($limit === 0 && !empty($this->lastCookie)) {
2049
+            // a search without limit was requested. However, if we do use
2050
+            // Paged Search once, we always must do it. This requires us to
2051
+            // initialize it with the configured page size.
2052
+            $this->abandonPagedSearch();
2053
+            // in case someone set it to 0 … use 500, otherwise no results will
2054
+            // be returned.
2055
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2056
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2057
+                $this->connection->getConnectionResource(),
2058
+                $pageSize, false);
2059
+        }
2060
+
2061
+        return $pagedSearchOK;
2062
+    }
2063
+
2064
+    /**
2065
+     * Is more than one $attr used for search?
2066
+     *
2067
+     * @param string|string[]|null $attr
2068
+     * @return bool
2069
+     */
2070
+    private function manyAttributes($attr): bool {
2071
+        if (\is_array($attr)) {
2072
+            return \count($attr) > 1;
2073
+        }
2074
+        return false;
2075
+    }
2076 2076
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/LDAP.php 1 patch
Indentation   +383 added lines, -383 removed lines patch added patch discarded remove patch
@@ -39,387 +39,387 @@
 block discarded – undo
39 39
 use OCA\User_LDAP\PagedResults\Php73;
40 40
 
41 41
 class LDAP implements ILDAPWrapper {
42
-	protected $curFunc = '';
43
-	protected $curArgs = [];
44
-
45
-	/** @var IAdapter */
46
-	protected $pagedResultsAdapter;
47
-
48
-	public function __construct() {
49
-		if (version_compare(PHP_VERSION, '7.3', '<') === true) {
50
-			$this->pagedResultsAdapter = new Php54();
51
-		} else {
52
-			$this->pagedResultsAdapter = new Php73();
53
-		}
54
-	}
55
-
56
-	/**
57
-	 * @param resource $link
58
-	 * @param string $dn
59
-	 * @param string $password
60
-	 * @return bool|mixed
61
-	 */
62
-	public function bind($link, $dn, $password) {
63
-		return $this->invokeLDAPMethod('bind', $link, $dn, $password);
64
-	}
65
-
66
-	/**
67
-	 * @param string $host
68
-	 * @param string $port
69
-	 * @return mixed
70
-	 */
71
-	public function connect($host, $port) {
72
-		if (strpos($host, '://') === false) {
73
-			$host = 'ldap://' . $host;
74
-		}
75
-		if (strpos($host, ':', strpos($host, '://') + 1) === false) {
76
-			//ldap_connect ignores port parameter when URLs are passed
77
-			$host .= ':' . $port;
78
-		}
79
-		return $this->invokeLDAPMethod('connect', $host);
80
-	}
81
-
82
-	public function controlPagedResultResponse($link, $result, &$cookie): bool {
83
-		$this->preFunctionCall(
84
-			$this->pagedResultsAdapter->getResponseCallFunc(),
85
-			$this->pagedResultsAdapter->getResponseCallArgs([$link, $result, &$cookie])
86
-		);
87
-
88
-		$result = $this->pagedResultsAdapter->responseCall($link);
89
-		$cookie = $this->pagedResultsAdapter->getCookie($link);
90
-
91
-		if ($this->isResultFalse($result)) {
92
-			$this->postFunctionCall();
93
-		}
94
-
95
-		return $result;
96
-	}
97
-
98
-	/**
99
-	 * @param LDAP $link
100
-	 * @param int $pageSize
101
-	 * @param bool $isCritical
102
-	 * @return mixed|true
103
-	 */
104
-	public function controlPagedResult($link, $pageSize, $isCritical) {
105
-		$fn = $this->pagedResultsAdapter->getRequestCallFunc();
106
-		$this->pagedResultsAdapter->setRequestParameters($link, $pageSize, $isCritical);
107
-		if ($fn === null) {
108
-			return true;
109
-		}
110
-
111
-		$this->preFunctionCall($fn, $this->pagedResultsAdapter->getRequestCallArgs($link));
112
-		$result = $this->pagedResultsAdapter->requestCall($link);
113
-
114
-		if ($this->isResultFalse($result)) {
115
-			$this->postFunctionCall();
116
-		}
117
-
118
-		return $result;
119
-	}
120
-
121
-	/**
122
-	 * @param LDAP $link
123
-	 * @param LDAP $result
124
-	 * @return mixed
125
-	 */
126
-	public function countEntries($link, $result) {
127
-		return $this->invokeLDAPMethod('count_entries', $link, $result);
128
-	}
129
-
130
-	/**
131
-	 * @param LDAP $link
132
-	 * @return integer
133
-	 */
134
-	public function errno($link) {
135
-		return $this->invokeLDAPMethod('errno', $link);
136
-	}
137
-
138
-	/**
139
-	 * @param LDAP $link
140
-	 * @return string
141
-	 */
142
-	public function error($link) {
143
-		return $this->invokeLDAPMethod('error', $link);
144
-	}
145
-
146
-	/**
147
-	 * Splits DN into its component parts
148
-	 * @param string $dn
149
-	 * @param int @withAttrib
150
-	 * @return array|false
151
-	 * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
152
-	 */
153
-	public function explodeDN($dn, $withAttrib) {
154
-		return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
155
-	}
156
-
157
-	/**
158
-	 * @param LDAP $link
159
-	 * @param LDAP $result
160
-	 * @return mixed
161
-	 */
162
-	public function firstEntry($link, $result) {
163
-		return $this->invokeLDAPMethod('first_entry', $link, $result);
164
-	}
165
-
166
-	/**
167
-	 * @param LDAP $link
168
-	 * @param LDAP $result
169
-	 * @return array|mixed
170
-	 */
171
-	public function getAttributes($link, $result) {
172
-		return $this->invokeLDAPMethod('get_attributes', $link, $result);
173
-	}
174
-
175
-	/**
176
-	 * @param LDAP $link
177
-	 * @param LDAP $result
178
-	 * @return mixed|string
179
-	 */
180
-	public function getDN($link, $result) {
181
-		return $this->invokeLDAPMethod('get_dn', $link, $result);
182
-	}
183
-
184
-	/**
185
-	 * @param LDAP $link
186
-	 * @param LDAP $result
187
-	 * @return array|mixed
188
-	 */
189
-	public function getEntries($link, $result) {
190
-		return $this->invokeLDAPMethod('get_entries', $link, $result);
191
-	}
192
-
193
-	/**
194
-	 * @param LDAP $link
195
-	 * @param resource $result
196
-	 * @return mixed
197
-	 */
198
-	public function nextEntry($link, $result) {
199
-		return $this->invokeLDAPMethod('next_entry', $link, $result);
200
-	}
201
-
202
-	/**
203
-	 * @param LDAP $link
204
-	 * @param string $baseDN
205
-	 * @param string $filter
206
-	 * @param array $attr
207
-	 * @return mixed
208
-	 */
209
-	public function read($link, $baseDN, $filter, $attr) {
210
-		$this->pagedResultsAdapter->setReadArgs($link, $baseDN, $filter, $attr);
211
-		return $this->invokeLDAPMethod('read', ...$this->pagedResultsAdapter->getReadArgs($link));
212
-	}
213
-
214
-	/**
215
-	 * @param LDAP $link
216
-	 * @param string[] $baseDN
217
-	 * @param string $filter
218
-	 * @param array $attr
219
-	 * @param int $attrsOnly
220
-	 * @param int $limit
221
-	 * @return mixed
222
-	 * @throws \Exception
223
-	 */
224
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
225
-		$oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
226
-			if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
227
-				return true;
228
-			}
229
-			$oldHandler($no, $message, $file, $line);
230
-			return true;
231
-		});
232
-		try {
233
-			$this->pagedResultsAdapter->setSearchArgs($link, $baseDN, $filter, $attr, $attrsOnly, $limit);
234
-			$result = $this->invokeLDAPMethod('search', ...$this->pagedResultsAdapter->getSearchArgs($link));
235
-
236
-			restore_error_handler();
237
-			return $result;
238
-		} catch (\Exception $e) {
239
-			restore_error_handler();
240
-			throw $e;
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * @param LDAP $link
246
-	 * @param string $userDN
247
-	 * @param string $password
248
-	 * @return bool
249
-	 */
250
-	public function modReplace($link, $userDN, $password) {
251
-		return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
252
-	}
253
-
254
-	/**
255
-	 * @param LDAP $link
256
-	 * @param string $userDN
257
-	 * @param string $oldPassword
258
-	 * @param string $password
259
-	 * @return bool
260
-	 */
261
-	public function exopPasswd($link, $userDN, $oldPassword, $password) {
262
-		return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
263
-	}
264
-
265
-	/**
266
-	 * @param LDAP $link
267
-	 * @param string $option
268
-	 * @param int $value
269
-	 * @return bool|mixed
270
-	 */
271
-	public function setOption($link, $option, $value) {
272
-		return $this->invokeLDAPMethod('set_option', $link, $option, $value);
273
-	}
274
-
275
-	/**
276
-	 * @param LDAP $link
277
-	 * @return mixed|true
278
-	 */
279
-	public function startTls($link) {
280
-		return $this->invokeLDAPMethod('start_tls', $link);
281
-	}
282
-
283
-	/**
284
-	 * @param resource $link
285
-	 * @return bool|mixed
286
-	 */
287
-	public function unbind($link) {
288
-		return $this->invokeLDAPMethod('unbind', $link);
289
-	}
290
-
291
-	/**
292
-	 * Checks whether the server supports LDAP
293
-	 * @return boolean if it the case, false otherwise
294
-	 * */
295
-	public function areLDAPFunctionsAvailable() {
296
-		return function_exists('ldap_connect');
297
-	}
298
-
299
-	/**
300
-	 * Checks whether the submitted parameter is a resource
301
-	 * @param Resource $resource the resource variable to check
302
-	 * @return bool true if it is a resource, false otherwise
303
-	 */
304
-	public function isResource($resource) {
305
-		return is_resource($resource);
306
-	}
307
-
308
-	/**
309
-	 * Checks whether the return value from LDAP is wrong or not.
310
-	 *
311
-	 * When using ldap_search we provide an array, in case multiple bases are
312
-	 * configured. Thus, we need to check the array elements.
313
-	 *
314
-	 * @param $result
315
-	 * @return bool
316
-	 */
317
-	protected function isResultFalse($result) {
318
-		if ($result === false) {
319
-			return true;
320
-		}
321
-
322
-		if ($this->curFunc === 'ldap_search' && is_array($result)) {
323
-			foreach ($result as $singleResult) {
324
-				if ($singleResult === false) {
325
-					return true;
326
-				}
327
-			}
328
-		}
329
-
330
-		return false;
331
-	}
332
-
333
-	/**
334
-	 * @return mixed
335
-	 */
336
-	protected function invokeLDAPMethod() {
337
-		$arguments = func_get_args();
338
-		$func = 'ldap_' . array_shift($arguments);
339
-		if (function_exists($func)) {
340
-			$this->preFunctionCall($func, $arguments);
341
-			$result = call_user_func_array($func, $arguments);
342
-			if ($this->isResultFalse($result)) {
343
-				$this->postFunctionCall();
344
-			}
345
-			return $result;
346
-		}
347
-		return null;
348
-	}
349
-
350
-	/**
351
-	 * @param string $functionName
352
-	 * @param array $args
353
-	 */
354
-	private function preFunctionCall($functionName, $args) {
355
-		$this->curFunc = $functionName;
356
-		$this->curArgs = $args;
357
-	}
358
-
359
-	/**
360
-	 * Analyzes the returned LDAP error and acts accordingly if not 0
361
-	 *
362
-	 * @param resource $resource the LDAP Connection resource
363
-	 * @throws ConstraintViolationException
364
-	 * @throws ServerNotAvailableException
365
-	 * @throws \Exception
366
-	 */
367
-	private function processLDAPError($resource) {
368
-		$errorCode = ldap_errno($resource);
369
-		if ($errorCode === 0) {
370
-			return;
371
-		}
372
-		$errorMsg = ldap_error($resource);
373
-
374
-		if ($this->curFunc === 'ldap_get_entries'
375
-			&& $errorCode === -4) {
376
-		} elseif ($errorCode === 32) {
377
-			//for now
378
-		} elseif ($errorCode === 10) {
379
-			//referrals, we switch them off, but then there is AD :)
380
-		} elseif ($errorCode === -1) {
381
-			throw new ServerNotAvailableException('Lost connection to LDAP server.');
382
-		} elseif ($errorCode === 52) {
383
-			throw new ServerNotAvailableException('LDAP server is shutting down.');
384
-		} elseif ($errorCode === 48) {
385
-			throw new \Exception('LDAP authentication method rejected', $errorCode);
386
-		} elseif ($errorCode === 1) {
387
-			throw new \Exception('LDAP Operations error', $errorCode);
388
-		} elseif ($errorCode === 19) {
389
-			ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
390
-			throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
391
-		} else {
392
-			\OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
393
-				'app' => 'user_ldap',
394
-				'message' => $errorMsg,
395
-				'code' => $errorCode,
396
-				'func' => $this->curFunc,
397
-			]);
398
-		}
399
-	}
400
-
401
-	/**
402
-	 * Called after an ldap method is run to act on LDAP error if necessary
403
-	 * @throw \Exception
404
-	 */
405
-	private function postFunctionCall() {
406
-		if ($this->isResource($this->curArgs[0])) {
407
-			$resource = $this->curArgs[0];
408
-		} elseif (
409
-			   $this->curFunc === 'ldap_search'
410
-			&& is_array($this->curArgs[0])
411
-			&& $this->isResource($this->curArgs[0][0])
412
-		) {
413
-			// we use always the same LDAP connection resource, is enough to
414
-			// take the first one.
415
-			$resource = $this->curArgs[0][0];
416
-		} else {
417
-			return;
418
-		}
419
-
420
-		$this->processLDAPError($resource);
421
-
422
-		$this->curFunc = '';
423
-		$this->curArgs = [];
424
-	}
42
+    protected $curFunc = '';
43
+    protected $curArgs = [];
44
+
45
+    /** @var IAdapter */
46
+    protected $pagedResultsAdapter;
47
+
48
+    public function __construct() {
49
+        if (version_compare(PHP_VERSION, '7.3', '<') === true) {
50
+            $this->pagedResultsAdapter = new Php54();
51
+        } else {
52
+            $this->pagedResultsAdapter = new Php73();
53
+        }
54
+    }
55
+
56
+    /**
57
+     * @param resource $link
58
+     * @param string $dn
59
+     * @param string $password
60
+     * @return bool|mixed
61
+     */
62
+    public function bind($link, $dn, $password) {
63
+        return $this->invokeLDAPMethod('bind', $link, $dn, $password);
64
+    }
65
+
66
+    /**
67
+     * @param string $host
68
+     * @param string $port
69
+     * @return mixed
70
+     */
71
+    public function connect($host, $port) {
72
+        if (strpos($host, '://') === false) {
73
+            $host = 'ldap://' . $host;
74
+        }
75
+        if (strpos($host, ':', strpos($host, '://') + 1) === false) {
76
+            //ldap_connect ignores port parameter when URLs are passed
77
+            $host .= ':' . $port;
78
+        }
79
+        return $this->invokeLDAPMethod('connect', $host);
80
+    }
81
+
82
+    public function controlPagedResultResponse($link, $result, &$cookie): bool {
83
+        $this->preFunctionCall(
84
+            $this->pagedResultsAdapter->getResponseCallFunc(),
85
+            $this->pagedResultsAdapter->getResponseCallArgs([$link, $result, &$cookie])
86
+        );
87
+
88
+        $result = $this->pagedResultsAdapter->responseCall($link);
89
+        $cookie = $this->pagedResultsAdapter->getCookie($link);
90
+
91
+        if ($this->isResultFalse($result)) {
92
+            $this->postFunctionCall();
93
+        }
94
+
95
+        return $result;
96
+    }
97
+
98
+    /**
99
+     * @param LDAP $link
100
+     * @param int $pageSize
101
+     * @param bool $isCritical
102
+     * @return mixed|true
103
+     */
104
+    public function controlPagedResult($link, $pageSize, $isCritical) {
105
+        $fn = $this->pagedResultsAdapter->getRequestCallFunc();
106
+        $this->pagedResultsAdapter->setRequestParameters($link, $pageSize, $isCritical);
107
+        if ($fn === null) {
108
+            return true;
109
+        }
110
+
111
+        $this->preFunctionCall($fn, $this->pagedResultsAdapter->getRequestCallArgs($link));
112
+        $result = $this->pagedResultsAdapter->requestCall($link);
113
+
114
+        if ($this->isResultFalse($result)) {
115
+            $this->postFunctionCall();
116
+        }
117
+
118
+        return $result;
119
+    }
120
+
121
+    /**
122
+     * @param LDAP $link
123
+     * @param LDAP $result
124
+     * @return mixed
125
+     */
126
+    public function countEntries($link, $result) {
127
+        return $this->invokeLDAPMethod('count_entries', $link, $result);
128
+    }
129
+
130
+    /**
131
+     * @param LDAP $link
132
+     * @return integer
133
+     */
134
+    public function errno($link) {
135
+        return $this->invokeLDAPMethod('errno', $link);
136
+    }
137
+
138
+    /**
139
+     * @param LDAP $link
140
+     * @return string
141
+     */
142
+    public function error($link) {
143
+        return $this->invokeLDAPMethod('error', $link);
144
+    }
145
+
146
+    /**
147
+     * Splits DN into its component parts
148
+     * @param string $dn
149
+     * @param int @withAttrib
150
+     * @return array|false
151
+     * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
152
+     */
153
+    public function explodeDN($dn, $withAttrib) {
154
+        return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
155
+    }
156
+
157
+    /**
158
+     * @param LDAP $link
159
+     * @param LDAP $result
160
+     * @return mixed
161
+     */
162
+    public function firstEntry($link, $result) {
163
+        return $this->invokeLDAPMethod('first_entry', $link, $result);
164
+    }
165
+
166
+    /**
167
+     * @param LDAP $link
168
+     * @param LDAP $result
169
+     * @return array|mixed
170
+     */
171
+    public function getAttributes($link, $result) {
172
+        return $this->invokeLDAPMethod('get_attributes', $link, $result);
173
+    }
174
+
175
+    /**
176
+     * @param LDAP $link
177
+     * @param LDAP $result
178
+     * @return mixed|string
179
+     */
180
+    public function getDN($link, $result) {
181
+        return $this->invokeLDAPMethod('get_dn', $link, $result);
182
+    }
183
+
184
+    /**
185
+     * @param LDAP $link
186
+     * @param LDAP $result
187
+     * @return array|mixed
188
+     */
189
+    public function getEntries($link, $result) {
190
+        return $this->invokeLDAPMethod('get_entries', $link, $result);
191
+    }
192
+
193
+    /**
194
+     * @param LDAP $link
195
+     * @param resource $result
196
+     * @return mixed
197
+     */
198
+    public function nextEntry($link, $result) {
199
+        return $this->invokeLDAPMethod('next_entry', $link, $result);
200
+    }
201
+
202
+    /**
203
+     * @param LDAP $link
204
+     * @param string $baseDN
205
+     * @param string $filter
206
+     * @param array $attr
207
+     * @return mixed
208
+     */
209
+    public function read($link, $baseDN, $filter, $attr) {
210
+        $this->pagedResultsAdapter->setReadArgs($link, $baseDN, $filter, $attr);
211
+        return $this->invokeLDAPMethod('read', ...$this->pagedResultsAdapter->getReadArgs($link));
212
+    }
213
+
214
+    /**
215
+     * @param LDAP $link
216
+     * @param string[] $baseDN
217
+     * @param string $filter
218
+     * @param array $attr
219
+     * @param int $attrsOnly
220
+     * @param int $limit
221
+     * @return mixed
222
+     * @throws \Exception
223
+     */
224
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
225
+        $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
226
+            if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
227
+                return true;
228
+            }
229
+            $oldHandler($no, $message, $file, $line);
230
+            return true;
231
+        });
232
+        try {
233
+            $this->pagedResultsAdapter->setSearchArgs($link, $baseDN, $filter, $attr, $attrsOnly, $limit);
234
+            $result = $this->invokeLDAPMethod('search', ...$this->pagedResultsAdapter->getSearchArgs($link));
235
+
236
+            restore_error_handler();
237
+            return $result;
238
+        } catch (\Exception $e) {
239
+            restore_error_handler();
240
+            throw $e;
241
+        }
242
+    }
243
+
244
+    /**
245
+     * @param LDAP $link
246
+     * @param string $userDN
247
+     * @param string $password
248
+     * @return bool
249
+     */
250
+    public function modReplace($link, $userDN, $password) {
251
+        return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
252
+    }
253
+
254
+    /**
255
+     * @param LDAP $link
256
+     * @param string $userDN
257
+     * @param string $oldPassword
258
+     * @param string $password
259
+     * @return bool
260
+     */
261
+    public function exopPasswd($link, $userDN, $oldPassword, $password) {
262
+        return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
263
+    }
264
+
265
+    /**
266
+     * @param LDAP $link
267
+     * @param string $option
268
+     * @param int $value
269
+     * @return bool|mixed
270
+     */
271
+    public function setOption($link, $option, $value) {
272
+        return $this->invokeLDAPMethod('set_option', $link, $option, $value);
273
+    }
274
+
275
+    /**
276
+     * @param LDAP $link
277
+     * @return mixed|true
278
+     */
279
+    public function startTls($link) {
280
+        return $this->invokeLDAPMethod('start_tls', $link);
281
+    }
282
+
283
+    /**
284
+     * @param resource $link
285
+     * @return bool|mixed
286
+     */
287
+    public function unbind($link) {
288
+        return $this->invokeLDAPMethod('unbind', $link);
289
+    }
290
+
291
+    /**
292
+     * Checks whether the server supports LDAP
293
+     * @return boolean if it the case, false otherwise
294
+     * */
295
+    public function areLDAPFunctionsAvailable() {
296
+        return function_exists('ldap_connect');
297
+    }
298
+
299
+    /**
300
+     * Checks whether the submitted parameter is a resource
301
+     * @param Resource $resource the resource variable to check
302
+     * @return bool true if it is a resource, false otherwise
303
+     */
304
+    public function isResource($resource) {
305
+        return is_resource($resource);
306
+    }
307
+
308
+    /**
309
+     * Checks whether the return value from LDAP is wrong or not.
310
+     *
311
+     * When using ldap_search we provide an array, in case multiple bases are
312
+     * configured. Thus, we need to check the array elements.
313
+     *
314
+     * @param $result
315
+     * @return bool
316
+     */
317
+    protected function isResultFalse($result) {
318
+        if ($result === false) {
319
+            return true;
320
+        }
321
+
322
+        if ($this->curFunc === 'ldap_search' && is_array($result)) {
323
+            foreach ($result as $singleResult) {
324
+                if ($singleResult === false) {
325
+                    return true;
326
+                }
327
+            }
328
+        }
329
+
330
+        return false;
331
+    }
332
+
333
+    /**
334
+     * @return mixed
335
+     */
336
+    protected function invokeLDAPMethod() {
337
+        $arguments = func_get_args();
338
+        $func = 'ldap_' . array_shift($arguments);
339
+        if (function_exists($func)) {
340
+            $this->preFunctionCall($func, $arguments);
341
+            $result = call_user_func_array($func, $arguments);
342
+            if ($this->isResultFalse($result)) {
343
+                $this->postFunctionCall();
344
+            }
345
+            return $result;
346
+        }
347
+        return null;
348
+    }
349
+
350
+    /**
351
+     * @param string $functionName
352
+     * @param array $args
353
+     */
354
+    private function preFunctionCall($functionName, $args) {
355
+        $this->curFunc = $functionName;
356
+        $this->curArgs = $args;
357
+    }
358
+
359
+    /**
360
+     * Analyzes the returned LDAP error and acts accordingly if not 0
361
+     *
362
+     * @param resource $resource the LDAP Connection resource
363
+     * @throws ConstraintViolationException
364
+     * @throws ServerNotAvailableException
365
+     * @throws \Exception
366
+     */
367
+    private function processLDAPError($resource) {
368
+        $errorCode = ldap_errno($resource);
369
+        if ($errorCode === 0) {
370
+            return;
371
+        }
372
+        $errorMsg = ldap_error($resource);
373
+
374
+        if ($this->curFunc === 'ldap_get_entries'
375
+            && $errorCode === -4) {
376
+        } elseif ($errorCode === 32) {
377
+            //for now
378
+        } elseif ($errorCode === 10) {
379
+            //referrals, we switch them off, but then there is AD :)
380
+        } elseif ($errorCode === -1) {
381
+            throw new ServerNotAvailableException('Lost connection to LDAP server.');
382
+        } elseif ($errorCode === 52) {
383
+            throw new ServerNotAvailableException('LDAP server is shutting down.');
384
+        } elseif ($errorCode === 48) {
385
+            throw new \Exception('LDAP authentication method rejected', $errorCode);
386
+        } elseif ($errorCode === 1) {
387
+            throw new \Exception('LDAP Operations error', $errorCode);
388
+        } elseif ($errorCode === 19) {
389
+            ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
390
+            throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
391
+        } else {
392
+            \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
393
+                'app' => 'user_ldap',
394
+                'message' => $errorMsg,
395
+                'code' => $errorCode,
396
+                'func' => $this->curFunc,
397
+            ]);
398
+        }
399
+    }
400
+
401
+    /**
402
+     * Called after an ldap method is run to act on LDAP error if necessary
403
+     * @throw \Exception
404
+     */
405
+    private function postFunctionCall() {
406
+        if ($this->isResource($this->curArgs[0])) {
407
+            $resource = $this->curArgs[0];
408
+        } elseif (
409
+                $this->curFunc === 'ldap_search'
410
+            && is_array($this->curArgs[0])
411
+            && $this->isResource($this->curArgs[0][0])
412
+        ) {
413
+            // we use always the same LDAP connection resource, is enough to
414
+            // take the first one.
415
+            $resource = $this->curArgs[0][0];
416
+        } else {
417
+            return;
418
+        }
419
+
420
+        $this->processLDAPError($resource);
421
+
422
+        $this->curFunc = '';
423
+        $this->curArgs = [];
424
+    }
425 425
 }
Please login to merge, or discard this patch.