Completed
Pull Request — master (#3676)
by Individual IT
12:49
created
lib/private/Files/View.php 3 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * and does not take the chroot into account )
201 201
 	 *
202 202
 	 * @param string $path
203
-	 * @return \OCP\Files\Mount\IMountPoint
203
+	 * @return Mount\MountPoint|null
204 204
 	 */
205 205
 	public function getMount($path) {
206 206
 		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 
964 964
 	/**
965 965
 	 * @param string $path
966
-	 * @return bool|string
966
+	 * @return string|false
967 967
 	 * @throws \OCP\Files\InvalidPathException
968 968
 	 */
969 969
 	public function toTmpFile($path) {
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
 	 * @param string $path
1079 1079
 	 * @param array $hooks (optional)
1080 1080
 	 * @param mixed $extraParam (optional)
1081
-	 * @return mixed
1081
+	 * @return string
1082 1082
 	 * @throws \Exception
1083 1083
 	 *
1084 1084
 	 * This method takes requests for basic filesystem functions (e.g. reading & writing
@@ -2086,7 +2086,7 @@  discard block
 block discarded – undo
2086 2086
 
2087 2087
 	/**
2088 2088
 	 * @param string $filename
2089
-	 * @return array
2089
+	 * @return string[]
2090 2090
 	 * @throws \OC\User\NoUserException
2091 2091
 	 * @throws NotFoundException
2092 2092
 	 */
Please login to merge, or discard this patch.
Indentation   +2034 added lines, -2034 removed lines patch added patch discarded remove patch
@@ -84,2038 +84,2038 @@
 block discarded – undo
84 84
  * \OC\Files\Storage\Storage object
85 85
  */
86 86
 class View {
87
-	/** @var string */
88
-	private $fakeRoot = '';
89
-
90
-	/**
91
-	 * @var \OCP\Lock\ILockingProvider
92
-	 */
93
-	private $lockingProvider;
94
-
95
-	private $lockingEnabled;
96
-
97
-	private $updaterEnabled = true;
98
-
99
-	private $userManager;
100
-
101
-	/**
102
-	 * @param string $root
103
-	 * @throws \Exception If $root contains an invalid path
104
-	 */
105
-	public function __construct($root = '') {
106
-		if (is_null($root)) {
107
-			throw new \InvalidArgumentException('Root can\'t be null');
108
-		}
109
-		if (!Filesystem::isValidPath($root)) {
110
-			throw new \Exception();
111
-		}
112
-
113
-		$this->fakeRoot = $root;
114
-		$this->lockingProvider = \OC::$server->getLockingProvider();
115
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
116
-		$this->userManager = \OC::$server->getUserManager();
117
-	}
118
-
119
-	public function getAbsolutePath($path = '/') {
120
-		if ($path === null) {
121
-			return null;
122
-		}
123
-		$this->assertPathLength($path);
124
-		if ($path === '') {
125
-			$path = '/';
126
-		}
127
-		if ($path[0] !== '/') {
128
-			$path = '/' . $path;
129
-		}
130
-		return $this->fakeRoot . $path;
131
-	}
132
-
133
-	/**
134
-	 * change the root to a fake root
135
-	 *
136
-	 * @param string $fakeRoot
137
-	 * @return boolean|null
138
-	 */
139
-	public function chroot($fakeRoot) {
140
-		if (!$fakeRoot == '') {
141
-			if ($fakeRoot[0] !== '/') {
142
-				$fakeRoot = '/' . $fakeRoot;
143
-			}
144
-		}
145
-		$this->fakeRoot = $fakeRoot;
146
-	}
147
-
148
-	/**
149
-	 * get the fake root
150
-	 *
151
-	 * @return string
152
-	 */
153
-	public function getRoot() {
154
-		return $this->fakeRoot;
155
-	}
156
-
157
-	/**
158
-	 * get path relative to the root of the view
159
-	 *
160
-	 * @param string $path
161
-	 * @return string
162
-	 */
163
-	public function getRelativePath($path) {
164
-		$this->assertPathLength($path);
165
-		if ($this->fakeRoot == '') {
166
-			return $path;
167
-		}
168
-
169
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
170
-			return '/';
171
-		}
172
-
173
-		// missing slashes can cause wrong matches!
174
-		$root = rtrim($this->fakeRoot, '/') . '/';
175
-
176
-		if (strpos($path, $root) !== 0) {
177
-			return null;
178
-		} else {
179
-			$path = substr($path, strlen($this->fakeRoot));
180
-			if (strlen($path) === 0) {
181
-				return '/';
182
-			} else {
183
-				return $path;
184
-			}
185
-		}
186
-	}
187
-
188
-	/**
189
-	 * get the mountpoint of the storage object for a path
190
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
191
-	 * returned mountpoint is relative to the absolute root of the filesystem
192
-	 * and does not take the chroot into account )
193
-	 *
194
-	 * @param string $path
195
-	 * @return string
196
-	 */
197
-	public function getMountPoint($path) {
198
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
199
-	}
200
-
201
-	/**
202
-	 * get the mountpoint of the storage object for a path
203
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
204
-	 * returned mountpoint is relative to the absolute root of the filesystem
205
-	 * and does not take the chroot into account )
206
-	 *
207
-	 * @param string $path
208
-	 * @return \OCP\Files\Mount\IMountPoint
209
-	 */
210
-	public function getMount($path) {
211
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
212
-	}
213
-
214
-	/**
215
-	 * resolve a path to a storage and internal path
216
-	 *
217
-	 * @param string $path
218
-	 * @return array an array consisting of the storage and the internal path
219
-	 */
220
-	public function resolvePath($path) {
221
-		$a = $this->getAbsolutePath($path);
222
-		$p = Filesystem::normalizePath($a);
223
-		return Filesystem::resolvePath($p);
224
-	}
225
-
226
-	/**
227
-	 * return the path to a local version of the file
228
-	 * we need this because we can't know if a file is stored local or not from
229
-	 * outside the filestorage and for some purposes a local file is needed
230
-	 *
231
-	 * @param string $path
232
-	 * @return string
233
-	 */
234
-	public function getLocalFile($path) {
235
-		$parent = substr($path, 0, strrpos($path, '/'));
236
-		$path = $this->getAbsolutePath($path);
237
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
238
-		if (Filesystem::isValidPath($parent) and $storage) {
239
-			return $storage->getLocalFile($internalPath);
240
-		} else {
241
-			return null;
242
-		}
243
-	}
244
-
245
-	/**
246
-	 * @param string $path
247
-	 * @return string
248
-	 */
249
-	public function getLocalFolder($path) {
250
-		$parent = substr($path, 0, strrpos($path, '/'));
251
-		$path = $this->getAbsolutePath($path);
252
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
253
-		if (Filesystem::isValidPath($parent) and $storage) {
254
-			return $storage->getLocalFolder($internalPath);
255
-		} else {
256
-			return null;
257
-		}
258
-	}
259
-
260
-	/**
261
-	 * the following functions operate with arguments and return values identical
262
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
263
-	 * for \OC\Files\Storage\Storage via basicOperation().
264
-	 */
265
-	public function mkdir($path) {
266
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
267
-	}
268
-
269
-	/**
270
-	 * remove mount point
271
-	 *
272
-	 * @param \OC\Files\Mount\MoveableMount $mount
273
-	 * @param string $path relative to data/
274
-	 * @return boolean
275
-	 */
276
-	protected function removeMount($mount, $path) {
277
-		if ($mount instanceof MoveableMount) {
278
-			// cut of /user/files to get the relative path to data/user/files
279
-			$pathParts = explode('/', $path, 4);
280
-			$relPath = '/' . $pathParts[3];
281
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
282
-			\OC_Hook::emit(
283
-				Filesystem::CLASSNAME, "umount",
284
-				array(Filesystem::signal_param_path => $relPath)
285
-			);
286
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
287
-			$result = $mount->removeMount();
288
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
289
-			if ($result) {
290
-				\OC_Hook::emit(
291
-					Filesystem::CLASSNAME, "post_umount",
292
-					array(Filesystem::signal_param_path => $relPath)
293
-				);
294
-			}
295
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
296
-			return $result;
297
-		} else {
298
-			// do not allow deleting the storage's root / the mount point
299
-			// because for some storages it might delete the whole contents
300
-			// but isn't supposed to work that way
301
-			return false;
302
-		}
303
-	}
304
-
305
-	public function disableCacheUpdate() {
306
-		$this->updaterEnabled = false;
307
-	}
308
-
309
-	public function enableCacheUpdate() {
310
-		$this->updaterEnabled = true;
311
-	}
312
-
313
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
314
-		if ($this->updaterEnabled) {
315
-			if (is_null($time)) {
316
-				$time = time();
317
-			}
318
-			$storage->getUpdater()->update($internalPath, $time);
319
-		}
320
-	}
321
-
322
-	protected function removeUpdate(Storage $storage, $internalPath) {
323
-		if ($this->updaterEnabled) {
324
-			$storage->getUpdater()->remove($internalPath);
325
-		}
326
-	}
327
-
328
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
329
-		if ($this->updaterEnabled) {
330
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * @param string $path
336
-	 * @return bool|mixed
337
-	 */
338
-	public function rmdir($path) {
339
-		$absolutePath = $this->getAbsolutePath($path);
340
-		$mount = Filesystem::getMountManager()->find($absolutePath);
341
-		if ($mount->getInternalPath($absolutePath) === '') {
342
-			return $this->removeMount($mount, $absolutePath);
343
-		}
344
-		if ($this->is_dir($path)) {
345
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
346
-		} else {
347
-			$result = false;
348
-		}
349
-
350
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
351
-			$storage = $mount->getStorage();
352
-			$internalPath = $mount->getInternalPath($absolutePath);
353
-			$storage->getUpdater()->remove($internalPath);
354
-		}
355
-		return $result;
356
-	}
357
-
358
-	/**
359
-	 * @param string $path
360
-	 * @return resource
361
-	 */
362
-	public function opendir($path) {
363
-		return $this->basicOperation('opendir', $path, array('read'));
364
-	}
365
-
366
-	/**
367
-	 * @param $handle
368
-	 * @return mixed
369
-	 */
370
-	public function readdir($handle) {
371
-		$fsLocal = new Storage\Local(array('datadir' => '/'));
372
-		return $fsLocal->readdir($handle);
373
-	}
374
-
375
-	/**
376
-	 * @param string $path
377
-	 * @return bool|mixed
378
-	 */
379
-	public function is_dir($path) {
380
-		if ($path == '/') {
381
-			return true;
382
-		}
383
-		return $this->basicOperation('is_dir', $path);
384
-	}
385
-
386
-	/**
387
-	 * @param string $path
388
-	 * @return bool|mixed
389
-	 */
390
-	public function is_file($path) {
391
-		if ($path == '/') {
392
-			return false;
393
-		}
394
-		return $this->basicOperation('is_file', $path);
395
-	}
396
-
397
-	/**
398
-	 * @param string $path
399
-	 * @return mixed
400
-	 */
401
-	public function stat($path) {
402
-		return $this->basicOperation('stat', $path);
403
-	}
404
-
405
-	/**
406
-	 * @param string $path
407
-	 * @return mixed
408
-	 */
409
-	public function filetype($path) {
410
-		return $this->basicOperation('filetype', $path);
411
-	}
412
-
413
-	/**
414
-	 * @param string $path
415
-	 * @return mixed
416
-	 */
417
-	public function filesize($path) {
418
-		return $this->basicOperation('filesize', $path);
419
-	}
420
-
421
-	/**
422
-	 * @param string $path
423
-	 * @return bool|mixed
424
-	 * @throws \OCP\Files\InvalidPathException
425
-	 */
426
-	public function readfile($path) {
427
-		$this->assertPathLength($path);
428
-		@ob_end_clean();
429
-		$handle = $this->fopen($path, 'rb');
430
-		if ($handle) {
431
-			$chunkSize = 8192; // 8 kB chunks
432
-			while (!feof($handle)) {
433
-				echo fread($handle, $chunkSize);
434
-				flush();
435
-			}
436
-			fclose($handle);
437
-			$size = $this->filesize($path);
438
-			return $size;
439
-		}
440
-		return false;
441
-	}
442
-
443
-	/**
444
-	 * @param string $path
445
-	 * @param int $from
446
-	 * @param int $to
447
-	 * @return bool|mixed
448
-	 * @throws \OCP\Files\InvalidPathException
449
-	 * @throws \OCP\Files\UnseekableException
450
-	 */
451
-	public function readfilePart($path, $from, $to) {
452
-		$this->assertPathLength($path);
453
-		@ob_end_clean();
454
-		$handle = $this->fopen($path, 'rb');
455
-		if ($handle) {
456
-			if (fseek($handle, $from) === 0) {
457
-				$chunkSize = 8192; // 8 kB chunks
458
-				$end = $to + 1;
459
-				while (!feof($handle) && ftell($handle) < $end) {
460
-					$len = $end - ftell($handle);
461
-					if ($len > $chunkSize) {
462
-						$len = $chunkSize;
463
-					}
464
-					echo fread($handle, $len);
465
-					flush();
466
-				}
467
-				$size = ftell($handle) - $from;
468
-				return $size;
469
-			}
470
-
471
-			throw new \OCP\Files\UnseekableException('fseek error');
472
-		}
473
-		return false;
474
-	}
475
-
476
-	/**
477
-	 * @param string $path
478
-	 * @return mixed
479
-	 */
480
-	public function isCreatable($path) {
481
-		return $this->basicOperation('isCreatable', $path);
482
-	}
483
-
484
-	/**
485
-	 * @param string $path
486
-	 * @return mixed
487
-	 */
488
-	public function isReadable($path) {
489
-		return $this->basicOperation('isReadable', $path);
490
-	}
491
-
492
-	/**
493
-	 * @param string $path
494
-	 * @return mixed
495
-	 */
496
-	public function isUpdatable($path) {
497
-		return $this->basicOperation('isUpdatable', $path);
498
-	}
499
-
500
-	/**
501
-	 * @param string $path
502
-	 * @return bool|mixed
503
-	 */
504
-	public function isDeletable($path) {
505
-		$absolutePath = $this->getAbsolutePath($path);
506
-		$mount = Filesystem::getMountManager()->find($absolutePath);
507
-		if ($mount->getInternalPath($absolutePath) === '') {
508
-			return $mount instanceof MoveableMount;
509
-		}
510
-		return $this->basicOperation('isDeletable', $path);
511
-	}
512
-
513
-	/**
514
-	 * @param string $path
515
-	 * @return mixed
516
-	 */
517
-	public function isSharable($path) {
518
-		return $this->basicOperation('isSharable', $path);
519
-	}
520
-
521
-	/**
522
-	 * @param string $path
523
-	 * @return bool|mixed
524
-	 */
525
-	public function file_exists($path) {
526
-		if ($path == '/') {
527
-			return true;
528
-		}
529
-		return $this->basicOperation('file_exists', $path);
530
-	}
531
-
532
-	/**
533
-	 * @param string $path
534
-	 * @return mixed
535
-	 */
536
-	public function filemtime($path) {
537
-		return $this->basicOperation('filemtime', $path);
538
-	}
539
-
540
-	/**
541
-	 * @param string $path
542
-	 * @param int|string $mtime
543
-	 * @return bool
544
-	 */
545
-	public function touch($path, $mtime = null) {
546
-		if (!is_null($mtime) and !is_numeric($mtime)) {
547
-			$mtime = strtotime($mtime);
548
-		}
549
-
550
-		$hooks = array('touch');
551
-
552
-		if (!$this->file_exists($path)) {
553
-			$hooks[] = 'create';
554
-			$hooks[] = 'write';
555
-		}
556
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
557
-		if (!$result) {
558
-			// If create file fails because of permissions on external storage like SMB folders,
559
-			// check file exists and return false if not.
560
-			if (!$this->file_exists($path)) {
561
-				return false;
562
-			}
563
-			if (is_null($mtime)) {
564
-				$mtime = time();
565
-			}
566
-			//if native touch fails, we emulate it by changing the mtime in the cache
567
-			$this->putFileInfo($path, array('mtime' => $mtime));
568
-		}
569
-		return true;
570
-	}
571
-
572
-	/**
573
-	 * @param string $path
574
-	 * @return mixed
575
-	 */
576
-	public function file_get_contents($path) {
577
-		return $this->basicOperation('file_get_contents', $path, array('read'));
578
-	}
579
-
580
-	/**
581
-	 * @param bool $exists
582
-	 * @param string $path
583
-	 * @param bool $run
584
-	 */
585
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
586
-		if (!$exists) {
587
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
588
-				Filesystem::signal_param_path => $this->getHookPath($path),
589
-				Filesystem::signal_param_run => &$run,
590
-			));
591
-		} else {
592
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
593
-				Filesystem::signal_param_path => $this->getHookPath($path),
594
-				Filesystem::signal_param_run => &$run,
595
-			));
596
-		}
597
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
598
-			Filesystem::signal_param_path => $this->getHookPath($path),
599
-			Filesystem::signal_param_run => &$run,
600
-		));
601
-	}
602
-
603
-	/**
604
-	 * @param bool $exists
605
-	 * @param string $path
606
-	 */
607
-	protected function emit_file_hooks_post($exists, $path) {
608
-		if (!$exists) {
609
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
610
-				Filesystem::signal_param_path => $this->getHookPath($path),
611
-			));
612
-		} else {
613
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
614
-				Filesystem::signal_param_path => $this->getHookPath($path),
615
-			));
616
-		}
617
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
618
-			Filesystem::signal_param_path => $this->getHookPath($path),
619
-		));
620
-	}
621
-
622
-	/**
623
-	 * @param string $path
624
-	 * @param mixed $data
625
-	 * @return bool|mixed
626
-	 * @throws \Exception
627
-	 */
628
-	public function file_put_contents($path, $data) {
629
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
630
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
631
-			if (Filesystem::isValidPath($path)
632
-				and !Filesystem::isFileBlacklisted($path)
633
-			) {
634
-				$path = $this->getRelativePath($absolutePath);
635
-
636
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
637
-
638
-				$exists = $this->file_exists($path);
639
-				$run = true;
640
-				if ($this->shouldEmitHooks($path)) {
641
-					$this->emit_file_hooks_pre($exists, $path, $run);
642
-				}
643
-				if (!$run) {
644
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
645
-					return false;
646
-				}
647
-
648
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
649
-
650
-				/** @var \OC\Files\Storage\Storage $storage */
651
-				list($storage, $internalPath) = $this->resolvePath($path);
652
-				$target = $storage->fopen($internalPath, 'w');
653
-				if ($target) {
654
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
655
-					fclose($target);
656
-					fclose($data);
657
-
658
-					$this->writeUpdate($storage, $internalPath);
659
-
660
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
661
-
662
-					if ($this->shouldEmitHooks($path) && $result !== false) {
663
-						$this->emit_file_hooks_post($exists, $path);
664
-					}
665
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
666
-					return $result;
667
-				} else {
668
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
669
-					return false;
670
-				}
671
-			} else {
672
-				return false;
673
-			}
674
-		} else {
675
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
676
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
677
-		}
678
-	}
679
-
680
-	/**
681
-	 * @param string $path
682
-	 * @return bool|mixed
683
-	 */
684
-	public function unlink($path) {
685
-		if ($path === '' || $path === '/') {
686
-			// do not allow deleting the root
687
-			return false;
688
-		}
689
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
690
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
691
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
692
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
693
-			return $this->removeMount($mount, $absolutePath);
694
-		}
695
-		$result = $this->basicOperation('unlink', $path, array('delete'));
696
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
697
-			$storage = $mount->getStorage();
698
-			$internalPath = $mount->getInternalPath($absolutePath);
699
-			$storage->getUpdater()->remove($internalPath);
700
-			return true;
701
-		} else {
702
-			return $result;
703
-		}
704
-	}
705
-
706
-	/**
707
-	 * @param string $directory
708
-	 * @return bool|mixed
709
-	 */
710
-	public function deleteAll($directory) {
711
-		return $this->rmdir($directory);
712
-	}
713
-
714
-	/**
715
-	 * Rename/move a file or folder from the source path to target path.
716
-	 *
717
-	 * @param string $path1 source path
718
-	 * @param string $path2 target path
719
-	 *
720
-	 * @return bool|mixed
721
-	 */
722
-	public function rename($path1, $path2) {
723
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
724
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
725
-		$result = false;
726
-		if (
727
-			Filesystem::isValidPath($path2)
728
-			and Filesystem::isValidPath($path1)
729
-			and !Filesystem::isFileBlacklisted($path2)
730
-		) {
731
-			$path1 = $this->getRelativePath($absolutePath1);
732
-			$path2 = $this->getRelativePath($absolutePath2);
733
-			$exists = $this->file_exists($path2);
734
-
735
-			if ($path1 == null or $path2 == null) {
736
-				return false;
737
-			}
738
-
739
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
740
-			try {
741
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
742
-			} catch (LockedException $e) {
743
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
744
-				throw $e;
745
-			}
746
-
747
-			$run = true;
748
-			if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
749
-				// if it was a rename from a part file to a regular file it was a write and not a rename operation
750
-				$this->emit_file_hooks_pre($exists, $path2, $run);
751
-			} elseif ($this->shouldEmitHooks($path1)) {
752
-				\OC_Hook::emit(
753
-					Filesystem::CLASSNAME, Filesystem::signal_rename,
754
-					array(
755
-						Filesystem::signal_param_oldpath => $this->getHookPath($path1),
756
-						Filesystem::signal_param_newpath => $this->getHookPath($path2),
757
-						Filesystem::signal_param_run => &$run
758
-					)
759
-				);
760
-			}
761
-			if ($run) {
762
-				$this->verifyPath(dirname($path2), basename($path2));
763
-
764
-				$manager = Filesystem::getMountManager();
765
-				$mount1 = $this->getMount($path1);
766
-				$mount2 = $this->getMount($path2);
767
-				$storage1 = $mount1->getStorage();
768
-				$storage2 = $mount2->getStorage();
769
-				$internalPath1 = $mount1->getInternalPath($absolutePath1);
770
-				$internalPath2 = $mount2->getInternalPath($absolutePath2);
771
-
772
-				$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
773
-				$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
774
-
775
-				if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
776
-					if ($this->isTargetAllowed($absolutePath2)) {
777
-						/**
778
-						 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
779
-						 */
780
-						$sourceMountPoint = $mount1->getMountPoint();
781
-						$result = $mount1->moveMount($absolutePath2);
782
-						$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
783
-					} else {
784
-						$result = false;
785
-					}
786
-					// moving a file/folder within the same mount point
787
-				} elseif ($storage1 === $storage2) {
788
-					if ($storage1) {
789
-						$result = $storage1->rename($internalPath1, $internalPath2);
790
-					} else {
791
-						$result = false;
792
-					}
793
-					// moving a file/folder between storages (from $storage1 to $storage2)
794
-				} else {
795
-					$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
796
-				}
797
-
798
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
799
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
800
-
801
-					$this->writeUpdate($storage2, $internalPath2);
802
-				} else if ($result) {
803
-					if ($internalPath1 !== '') { // don't do a cache update for moved mounts
804
-						$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
805
-					}
806
-				}
807
-
808
-				$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
809
-				$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
810
-
811
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
812
-					if ($this->shouldEmitHooks()) {
813
-						$this->emit_file_hooks_post($exists, $path2);
814
-					}
815
-				} elseif ($result) {
816
-					if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
817
-						\OC_Hook::emit(
818
-							Filesystem::CLASSNAME,
819
-							Filesystem::signal_post_rename,
820
-							array(
821
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
822
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
823
-							)
824
-						);
825
-					}
826
-				}
827
-			}
828
-			$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
829
-			$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
830
-		}
831
-		return $result;
832
-	}
833
-
834
-	/**
835
-	 * Copy a file/folder from the source path to target path
836
-	 *
837
-	 * @param string $path1 source path
838
-	 * @param string $path2 target path
839
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
840
-	 *
841
-	 * @return bool|mixed
842
-	 */
843
-	public function copy($path1, $path2, $preserveMtime = false) {
844
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
845
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
846
-		$result = false;
847
-		if (
848
-			Filesystem::isValidPath($path2)
849
-			and Filesystem::isValidPath($path1)
850
-			and !Filesystem::isFileBlacklisted($path2)
851
-		) {
852
-			$path1 = $this->getRelativePath($absolutePath1);
853
-			$path2 = $this->getRelativePath($absolutePath2);
854
-
855
-			if ($path1 == null or $path2 == null) {
856
-				return false;
857
-			}
858
-			$run = true;
859
-
860
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
861
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
862
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
863
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
864
-
865
-			try {
866
-
867
-				$exists = $this->file_exists($path2);
868
-				if ($this->shouldEmitHooks()) {
869
-					\OC_Hook::emit(
870
-						Filesystem::CLASSNAME,
871
-						Filesystem::signal_copy,
872
-						array(
873
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
874
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
875
-							Filesystem::signal_param_run => &$run
876
-						)
877
-					);
878
-					$this->emit_file_hooks_pre($exists, $path2, $run);
879
-				}
880
-				if ($run) {
881
-					$mount1 = $this->getMount($path1);
882
-					$mount2 = $this->getMount($path2);
883
-					$storage1 = $mount1->getStorage();
884
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
885
-					$storage2 = $mount2->getStorage();
886
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
887
-
888
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
889
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
890
-
891
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
892
-						if ($storage1) {
893
-							$result = $storage1->copy($internalPath1, $internalPath2);
894
-						} else {
895
-							$result = false;
896
-						}
897
-					} else {
898
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
899
-					}
900
-
901
-					$this->writeUpdate($storage2, $internalPath2);
902
-
903
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
904
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
905
-
906
-					if ($this->shouldEmitHooks() && $result !== false) {
907
-						\OC_Hook::emit(
908
-							Filesystem::CLASSNAME,
909
-							Filesystem::signal_post_copy,
910
-							array(
911
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
912
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
913
-							)
914
-						);
915
-						$this->emit_file_hooks_post($exists, $path2);
916
-					}
917
-
918
-				}
919
-			} catch (\Exception $e) {
920
-				$this->unlockFile($path2, $lockTypePath2);
921
-				$this->unlockFile($path1, $lockTypePath1);
922
-				throw $e;
923
-			}
924
-
925
-			$this->unlockFile($path2, $lockTypePath2);
926
-			$this->unlockFile($path1, $lockTypePath1);
927
-
928
-		}
929
-		return $result;
930
-	}
931
-
932
-	/**
933
-	 * @param string $path
934
-	 * @param string $mode 'r' or 'w'
935
-	 * @return resource
936
-	 */
937
-	public function fopen($path, $mode) {
938
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
939
-		$hooks = array();
940
-		switch ($mode) {
941
-			case 'r':
942
-				$hooks[] = 'read';
943
-				break;
944
-			case 'r+':
945
-			case 'w+':
946
-			case 'x+':
947
-			case 'a+':
948
-				$hooks[] = 'read';
949
-				$hooks[] = 'write';
950
-				break;
951
-			case 'w':
952
-			case 'x':
953
-			case 'a':
954
-				$hooks[] = 'write';
955
-				break;
956
-			default:
957
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
958
-		}
959
-
960
-		if ($mode !== 'r' && $mode !== 'w') {
961
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
962
-		}
963
-
964
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
965
-	}
966
-
967
-	/**
968
-	 * @param string $path
969
-	 * @return bool|string
970
-	 * @throws \OCP\Files\InvalidPathException
971
-	 */
972
-	public function toTmpFile($path) {
973
-		$this->assertPathLength($path);
974
-		if (Filesystem::isValidPath($path)) {
975
-			$source = $this->fopen($path, 'r');
976
-			if ($source) {
977
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
978
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
979
-				file_put_contents($tmpFile, $source);
980
-				return $tmpFile;
981
-			} else {
982
-				return false;
983
-			}
984
-		} else {
985
-			return false;
986
-		}
987
-	}
988
-
989
-	/**
990
-	 * @param string $tmpFile
991
-	 * @param string $path
992
-	 * @return bool|mixed
993
-	 * @throws \OCP\Files\InvalidPathException
994
-	 */
995
-	public function fromTmpFile($tmpFile, $path) {
996
-		$this->assertPathLength($path);
997
-		if (Filesystem::isValidPath($path)) {
998
-
999
-			// Get directory that the file is going into
1000
-			$filePath = dirname($path);
1001
-
1002
-			// Create the directories if any
1003
-			if (!$this->file_exists($filePath)) {
1004
-				$result = $this->createParentDirectories($filePath);
1005
-				if ($result === false) {
1006
-					return false;
1007
-				}
1008
-			}
1009
-
1010
-			$source = fopen($tmpFile, 'r');
1011
-			if ($source) {
1012
-				$result = $this->file_put_contents($path, $source);
1013
-				// $this->file_put_contents() might have already closed
1014
-				// the resource, so we check it, before trying to close it
1015
-				// to avoid messages in the error log.
1016
-				if (is_resource($source)) {
1017
-					fclose($source);
1018
-				}
1019
-				unlink($tmpFile);
1020
-				return $result;
1021
-			} else {
1022
-				return false;
1023
-			}
1024
-		} else {
1025
-			return false;
1026
-		}
1027
-	}
1028
-
1029
-
1030
-	/**
1031
-	 * @param string $path
1032
-	 * @return mixed
1033
-	 * @throws \OCP\Files\InvalidPathException
1034
-	 */
1035
-	public function getMimeType($path) {
1036
-		$this->assertPathLength($path);
1037
-		return $this->basicOperation('getMimeType', $path);
1038
-	}
1039
-
1040
-	/**
1041
-	 * @param string $type
1042
-	 * @param string $path
1043
-	 * @param bool $raw
1044
-	 * @return bool|null|string
1045
-	 */
1046
-	public function hash($type, $path, $raw = false) {
1047
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1048
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1049
-		if (Filesystem::isValidPath($path)) {
1050
-			$path = $this->getRelativePath($absolutePath);
1051
-			if ($path == null) {
1052
-				return false;
1053
-			}
1054
-			if ($this->shouldEmitHooks($path)) {
1055
-				\OC_Hook::emit(
1056
-					Filesystem::CLASSNAME,
1057
-					Filesystem::signal_read,
1058
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1059
-				);
1060
-			}
1061
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1062
-			if ($storage) {
1063
-				$result = $storage->hash($type, $internalPath, $raw);
1064
-				return $result;
1065
-			}
1066
-		}
1067
-		return null;
1068
-	}
1069
-
1070
-	/**
1071
-	 * @param string $path
1072
-	 * @return mixed
1073
-	 * @throws \OCP\Files\InvalidPathException
1074
-	 */
1075
-	public function free_space($path = '/') {
1076
-		$this->assertPathLength($path);
1077
-		return $this->basicOperation('free_space', $path);
1078
-	}
1079
-
1080
-	/**
1081
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1082
-	 *
1083
-	 * @param string $operation
1084
-	 * @param string $path
1085
-	 * @param array $hooks (optional)
1086
-	 * @param mixed $extraParam (optional)
1087
-	 * @return mixed
1088
-	 * @throws \Exception
1089
-	 *
1090
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1091
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1092
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1093
-	 */
1094
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1095
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1096
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1097
-		if (Filesystem::isValidPath($path)
1098
-			and !Filesystem::isFileBlacklisted($path)
1099
-		) {
1100
-			$path = $this->getRelativePath($absolutePath);
1101
-			if ($path == null) {
1102
-				return false;
1103
-			}
1104
-
1105
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1106
-				// always a shared lock during pre-hooks so the hook can read the file
1107
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1108
-			}
1109
-
1110
-			$run = $this->runHooks($hooks, $path);
1111
-			/** @var \OC\Files\Storage\Storage $storage */
1112
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1113
-			if ($run and $storage) {
1114
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1115
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1116
-				}
1117
-				try {
1118
-					if (!is_null($extraParam)) {
1119
-						$result = $storage->$operation($internalPath, $extraParam);
1120
-					} else {
1121
-						$result = $storage->$operation($internalPath);
1122
-					}
1123
-				} catch (\Exception $e) {
1124
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1125
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1126
-					} else if (in_array('read', $hooks)) {
1127
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1128
-					}
1129
-					throw $e;
1130
-				}
1131
-
1132
-				if ($result && in_array('delete', $hooks) and $result) {
1133
-					$this->removeUpdate($storage, $internalPath);
1134
-				}
1135
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1136
-					$this->writeUpdate($storage, $internalPath);
1137
-				}
1138
-				if ($result && in_array('touch', $hooks)) {
1139
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1140
-				}
1141
-
1142
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1143
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1144
-				}
1145
-
1146
-				$unlockLater = false;
1147
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1148
-					$unlockLater = true;
1149
-					// make sure our unlocking callback will still be called if connection is aborted
1150
-					ignore_user_abort(true);
1151
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1152
-						if (in_array('write', $hooks)) {
1153
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1154
-						} else if (in_array('read', $hooks)) {
1155
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1156
-						}
1157
-					});
1158
-				}
1159
-
1160
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1161
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1162
-						$this->runHooks($hooks, $path, true);
1163
-					}
1164
-				}
1165
-
1166
-				if (!$unlockLater
1167
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1168
-				) {
1169
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1170
-				}
1171
-				return $result;
1172
-			} else {
1173
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1174
-			}
1175
-		}
1176
-		return null;
1177
-	}
1178
-
1179
-	/**
1180
-	 * get the path relative to the default root for hook usage
1181
-	 *
1182
-	 * @param string $path
1183
-	 * @return string
1184
-	 */
1185
-	private function getHookPath($path) {
1186
-		if (!Filesystem::getView()) {
1187
-			return $path;
1188
-		}
1189
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1190
-	}
1191
-
1192
-	private function shouldEmitHooks($path = '') {
1193
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1194
-			return false;
1195
-		}
1196
-		if (!Filesystem::$loaded) {
1197
-			return false;
1198
-		}
1199
-		$defaultRoot = Filesystem::getRoot();
1200
-		if ($defaultRoot === null) {
1201
-			return false;
1202
-		}
1203
-		if ($this->fakeRoot === $defaultRoot) {
1204
-			return true;
1205
-		}
1206
-		$fullPath = $this->getAbsolutePath($path);
1207
-
1208
-		if ($fullPath === $defaultRoot) {
1209
-			return true;
1210
-		}
1211
-
1212
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1213
-	}
1214
-
1215
-	/**
1216
-	 * @param string[] $hooks
1217
-	 * @param string $path
1218
-	 * @param bool $post
1219
-	 * @return bool
1220
-	 */
1221
-	private function runHooks($hooks, $path, $post = false) {
1222
-		$relativePath = $path;
1223
-		$path = $this->getHookPath($path);
1224
-		$prefix = ($post) ? 'post_' : '';
1225
-		$run = true;
1226
-		if ($this->shouldEmitHooks($relativePath)) {
1227
-			foreach ($hooks as $hook) {
1228
-				if ($hook != 'read') {
1229
-					\OC_Hook::emit(
1230
-						Filesystem::CLASSNAME,
1231
-						$prefix . $hook,
1232
-						array(
1233
-							Filesystem::signal_param_run => &$run,
1234
-							Filesystem::signal_param_path => $path
1235
-						)
1236
-					);
1237
-				} elseif (!$post) {
1238
-					\OC_Hook::emit(
1239
-						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1241
-						array(
1242
-							Filesystem::signal_param_path => $path
1243
-						)
1244
-					);
1245
-				}
1246
-			}
1247
-		}
1248
-		return $run;
1249
-	}
1250
-
1251
-	/**
1252
-	 * check if a file or folder has been updated since $time
1253
-	 *
1254
-	 * @param string $path
1255
-	 * @param int $time
1256
-	 * @return bool
1257
-	 */
1258
-	public function hasUpdated($path, $time) {
1259
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1260
-	}
1261
-
1262
-	/**
1263
-	 * @param string $ownerId
1264
-	 * @return \OC\User\User
1265
-	 */
1266
-	private function getUserObjectForOwner($ownerId) {
1267
-		$owner = $this->userManager->get($ownerId);
1268
-		if ($owner instanceof IUser) {
1269
-			return $owner;
1270
-		} else {
1271
-			return new User($ownerId, null);
1272
-		}
1273
-	}
1274
-
1275
-	/**
1276
-	 * Get file info from cache
1277
-	 *
1278
-	 * If the file is not in cached it will be scanned
1279
-	 * If the file has changed on storage the cache will be updated
1280
-	 *
1281
-	 * @param \OC\Files\Storage\Storage $storage
1282
-	 * @param string $internalPath
1283
-	 * @param string $relativePath
1284
-	 * @return array|bool
1285
-	 */
1286
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1287
-		$cache = $storage->getCache($internalPath);
1288
-		$data = $cache->get($internalPath);
1289
-		$watcher = $storage->getWatcher($internalPath);
1290
-
1291
-		try {
1292
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1293
-			if (!$data || $data['size'] === -1) {
1294
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1295
-				if (!$storage->file_exists($internalPath)) {
1296
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1297
-					return false;
1298
-				}
1299
-				$scanner = $storage->getScanner($internalPath);
1300
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1301
-				$data = $cache->get($internalPath);
1302
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1303
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1304
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1305
-				$watcher->update($internalPath, $data);
1306
-				$storage->getPropagator()->propagateChange($internalPath, time());
1307
-				$data = $cache->get($internalPath);
1308
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1309
-			}
1310
-		} catch (LockedException $e) {
1311
-			// if the file is locked we just use the old cache info
1312
-		}
1313
-
1314
-		return $data;
1315
-	}
1316
-
1317
-	/**
1318
-	 * get the filesystem info
1319
-	 *
1320
-	 * @param string $path
1321
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1322
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1323
-	 * defaults to true
1324
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1325
-	 */
1326
-	public function getFileInfo($path, $includeMountPoints = true) {
1327
-		$this->assertPathLength($path);
1328
-		if (!Filesystem::isValidPath($path)) {
1329
-			return false;
1330
-		}
1331
-		if (Cache\Scanner::isPartialFile($path)) {
1332
-			return $this->getPartFileInfo($path);
1333
-		}
1334
-		$relativePath = $path;
1335
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1336
-
1337
-		$mount = Filesystem::getMountManager()->find($path);
1338
-		$storage = $mount->getStorage();
1339
-		$internalPath = $mount->getInternalPath($path);
1340
-		if ($storage) {
1341
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1342
-
1343
-			if (!$data instanceof ICacheEntry) {
1344
-				return false;
1345
-			}
1346
-
1347
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1348
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1349
-			}
1350
-
1351
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1352
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1353
-
1354
-			if ($data and isset($data['fileid'])) {
1355
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1356
-					//add the sizes of other mount points to the folder
1357
-					$extOnly = ($includeMountPoints === 'ext');
1358
-					$mounts = Filesystem::getMountManager()->findIn($path);
1359
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1360
-						$subStorage = $mount->getStorage();
1361
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1362
-					}));
1363
-				}
1364
-			}
1365
-
1366
-			return $info;
1367
-		}
1368
-
1369
-		return false;
1370
-	}
1371
-
1372
-	/**
1373
-	 * get the content of a directory
1374
-	 *
1375
-	 * @param string $directory path under datadirectory
1376
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1377
-	 * @return FileInfo[]
1378
-	 */
1379
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1380
-		$this->assertPathLength($directory);
1381
-		if (!Filesystem::isValidPath($directory)) {
1382
-			return [];
1383
-		}
1384
-		$path = $this->getAbsolutePath($directory);
1385
-		$path = Filesystem::normalizePath($path);
1386
-		$mount = $this->getMount($directory);
1387
-		$storage = $mount->getStorage();
1388
-		$internalPath = $mount->getInternalPath($path);
1389
-		if ($storage) {
1390
-			$cache = $storage->getCache($internalPath);
1391
-			$user = \OC_User::getUser();
1392
-
1393
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1394
-
1395
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1396
-				return [];
1397
-			}
1398
-
1399
-			$folderId = $data['fileid'];
1400
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1401
-
1402
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1403
-			/**
1404
-			 * @var \OC\Files\FileInfo[] $files
1405
-			 */
1406
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1407
-				if ($sharingDisabled) {
1408
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1409
-				}
1410
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1411
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1412
-			}, $contents);
1413
-
1414
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1415
-			$mounts = Filesystem::getMountManager()->findIn($path);
1416
-			$dirLength = strlen($path);
1417
-			foreach ($mounts as $mount) {
1418
-				$mountPoint = $mount->getMountPoint();
1419
-				$subStorage = $mount->getStorage();
1420
-				if ($subStorage) {
1421
-					$subCache = $subStorage->getCache('');
1422
-
1423
-					$rootEntry = $subCache->get('');
1424
-					if (!$rootEntry) {
1425
-						$subScanner = $subStorage->getScanner('');
1426
-						try {
1427
-							$subScanner->scanFile('');
1428
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1429
-							continue;
1430
-						} catch (\OCP\Files\StorageInvalidException $e) {
1431
-							continue;
1432
-						} catch (\Exception $e) {
1433
-							// sometimes when the storage is not available it can be any exception
1434
-							\OCP\Util::writeLog(
1435
-								'core',
1436
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1437
-								get_class($e) . ': ' . $e->getMessage(),
1438
-								\OCP\Util::ERROR
1439
-							);
1440
-							continue;
1441
-						}
1442
-						$rootEntry = $subCache->get('');
1443
-					}
1444
-
1445
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1446
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1447
-						if ($pos = strpos($relativePath, '/')) {
1448
-							//mountpoint inside subfolder add size to the correct folder
1449
-							$entryName = substr($relativePath, 0, $pos);
1450
-							foreach ($files as &$entry) {
1451
-								if ($entry->getName() === $entryName) {
1452
-									$entry->addSubEntry($rootEntry, $mountPoint);
1453
-								}
1454
-							}
1455
-						} else { //mountpoint in this folder, add an entry for it
1456
-							$rootEntry['name'] = $relativePath;
1457
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1458
-							$permissions = $rootEntry['permissions'];
1459
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1460
-							// for shared files/folders we use the permissions given by the owner
1461
-							if ($mount instanceof MoveableMount) {
1462
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1463
-							} else {
1464
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1465
-							}
1466
-
1467
-							//remove any existing entry with the same name
1468
-							foreach ($files as $i => $file) {
1469
-								if ($file['name'] === $rootEntry['name']) {
1470
-									unset($files[$i]);
1471
-									break;
1472
-								}
1473
-							}
1474
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1475
-
1476
-							// if sharing was disabled for the user we remove the share permissions
1477
-							if (\OCP\Util::isSharingDisabledForUser()) {
1478
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1479
-							}
1480
-
1481
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1482
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1483
-						}
1484
-					}
1485
-				}
1486
-			}
1487
-
1488
-			if ($mimetype_filter) {
1489
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1490
-					if (strpos($mimetype_filter, '/')) {
1491
-						return $file->getMimetype() === $mimetype_filter;
1492
-					} else {
1493
-						return $file->getMimePart() === $mimetype_filter;
1494
-					}
1495
-				});
1496
-			}
1497
-
1498
-			return $files;
1499
-		} else {
1500
-			return [];
1501
-		}
1502
-	}
1503
-
1504
-	/**
1505
-	 * change file metadata
1506
-	 *
1507
-	 * @param string $path
1508
-	 * @param array|\OCP\Files\FileInfo $data
1509
-	 * @return int
1510
-	 *
1511
-	 * returns the fileid of the updated file
1512
-	 */
1513
-	public function putFileInfo($path, $data) {
1514
-		$this->assertPathLength($path);
1515
-		if ($data instanceof FileInfo) {
1516
-			$data = $data->getData();
1517
-		}
1518
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1519
-		/**
1520
-		 * @var \OC\Files\Storage\Storage $storage
1521
-		 * @var string $internalPath
1522
-		 */
1523
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1524
-		if ($storage) {
1525
-			$cache = $storage->getCache($path);
1526
-
1527
-			if (!$cache->inCache($internalPath)) {
1528
-				$scanner = $storage->getScanner($internalPath);
1529
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1530
-			}
1531
-
1532
-			return $cache->put($internalPath, $data);
1533
-		} else {
1534
-			return -1;
1535
-		}
1536
-	}
1537
-
1538
-	/**
1539
-	 * search for files with the name matching $query
1540
-	 *
1541
-	 * @param string $query
1542
-	 * @return FileInfo[]
1543
-	 */
1544
-	public function search($query) {
1545
-		return $this->searchCommon('search', array('%' . $query . '%'));
1546
-	}
1547
-
1548
-	/**
1549
-	 * search for files with the name matching $query
1550
-	 *
1551
-	 * @param string $query
1552
-	 * @return FileInfo[]
1553
-	 */
1554
-	public function searchRaw($query) {
1555
-		return $this->searchCommon('search', array($query));
1556
-	}
1557
-
1558
-	/**
1559
-	 * search for files by mimetype
1560
-	 *
1561
-	 * @param string $mimetype
1562
-	 * @return FileInfo[]
1563
-	 */
1564
-	public function searchByMime($mimetype) {
1565
-		return $this->searchCommon('searchByMime', array($mimetype));
1566
-	}
1567
-
1568
-	/**
1569
-	 * search for files by tag
1570
-	 *
1571
-	 * @param string|int $tag name or tag id
1572
-	 * @param string $userId owner of the tags
1573
-	 * @return FileInfo[]
1574
-	 */
1575
-	public function searchByTag($tag, $userId) {
1576
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1577
-	}
1578
-
1579
-	/**
1580
-	 * @param string $method cache method
1581
-	 * @param array $args
1582
-	 * @return FileInfo[]
1583
-	 */
1584
-	private function searchCommon($method, $args) {
1585
-		$files = array();
1586
-		$rootLength = strlen($this->fakeRoot);
1587
-
1588
-		$mount = $this->getMount('');
1589
-		$mountPoint = $mount->getMountPoint();
1590
-		$storage = $mount->getStorage();
1591
-		if ($storage) {
1592
-			$cache = $storage->getCache('');
1593
-
1594
-			$results = call_user_func_array(array($cache, $method), $args);
1595
-			foreach ($results as $result) {
1596
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1597
-					$internalPath = $result['path'];
1598
-					$path = $mountPoint . $result['path'];
1599
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1600
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1601
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1602
-				}
1603
-			}
1604
-
1605
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1606
-			foreach ($mounts as $mount) {
1607
-				$mountPoint = $mount->getMountPoint();
1608
-				$storage = $mount->getStorage();
1609
-				if ($storage) {
1610
-					$cache = $storage->getCache('');
1611
-
1612
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1613
-					$results = call_user_func_array(array($cache, $method), $args);
1614
-					if ($results) {
1615
-						foreach ($results as $result) {
1616
-							$internalPath = $result['path'];
1617
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1618
-							$path = rtrim($mountPoint . $internalPath, '/');
1619
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1620
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1621
-						}
1622
-					}
1623
-				}
1624
-			}
1625
-		}
1626
-		return $files;
1627
-	}
1628
-
1629
-	/**
1630
-	 * Get the owner for a file or folder
1631
-	 *
1632
-	 * @param string $path
1633
-	 * @return string the user id of the owner
1634
-	 * @throws NotFoundException
1635
-	 */
1636
-	public function getOwner($path) {
1637
-		$info = $this->getFileInfo($path);
1638
-		if (!$info) {
1639
-			throw new NotFoundException($path . ' not found while trying to get owner');
1640
-		}
1641
-		return $info->getOwner()->getUID();
1642
-	}
1643
-
1644
-	/**
1645
-	 * get the ETag for a file or folder
1646
-	 *
1647
-	 * @param string $path
1648
-	 * @return string
1649
-	 */
1650
-	public function getETag($path) {
1651
-		/**
1652
-		 * @var Storage\Storage $storage
1653
-		 * @var string $internalPath
1654
-		 */
1655
-		list($storage, $internalPath) = $this->resolvePath($path);
1656
-		if ($storage) {
1657
-			return $storage->getETag($internalPath);
1658
-		} else {
1659
-			return null;
1660
-		}
1661
-	}
1662
-
1663
-	/**
1664
-	 * Get the path of a file by id, relative to the view
1665
-	 *
1666
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1667
-	 *
1668
-	 * @param int $id
1669
-	 * @throws NotFoundException
1670
-	 * @return string
1671
-	 */
1672
-	public function getPath($id) {
1673
-		$id = (int)$id;
1674
-		$manager = Filesystem::getMountManager();
1675
-		$mounts = $manager->findIn($this->fakeRoot);
1676
-		$mounts[] = $manager->find($this->fakeRoot);
1677
-		// reverse the array so we start with the storage this view is in
1678
-		// which is the most likely to contain the file we're looking for
1679
-		$mounts = array_reverse($mounts);
1680
-		foreach ($mounts as $mount) {
1681
-			/**
1682
-			 * @var \OC\Files\Mount\MountPoint $mount
1683
-			 */
1684
-			if ($mount->getStorage()) {
1685
-				$cache = $mount->getStorage()->getCache();
1686
-				$internalPath = $cache->getPathById($id);
1687
-				if (is_string($internalPath)) {
1688
-					$fullPath = $mount->getMountPoint() . $internalPath;
1689
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1690
-						return $path;
1691
-					}
1692
-				}
1693
-			}
1694
-		}
1695
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1696
-	}
1697
-
1698
-	/**
1699
-	 * @param string $path
1700
-	 * @throws InvalidPathException
1701
-	 */
1702
-	private function assertPathLength($path) {
1703
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1704
-		// Check for the string length - performed using isset() instead of strlen()
1705
-		// because isset() is about 5x-40x faster.
1706
-		if (isset($path[$maxLen])) {
1707
-			$pathLen = strlen($path);
1708
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1709
-		}
1710
-	}
1711
-
1712
-	/**
1713
-	 * check if it is allowed to move a mount point to a given target.
1714
-	 * It is not allowed to move a mount point into a different mount point or
1715
-	 * into an already shared folder
1716
-	 *
1717
-	 * @param string $target path
1718
-	 * @return boolean
1719
-	 */
1720
-	private function isTargetAllowed($target) {
1721
-
1722
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1723
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1724
-			\OCP\Util::writeLog('files',
1725
-				'It is not allowed to move one mount point into another one',
1726
-				\OCP\Util::DEBUG);
1727
-			return false;
1728
-		}
1729
-
1730
-		// note: cannot use the view because the target is already locked
1731
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1732
-		if ($fileId === -1) {
1733
-			// target might not exist, need to check parent instead
1734
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1735
-		}
1736
-
1737
-		// check if any of the parents were shared by the current owner (include collections)
1738
-		$shares = \OCP\Share::getItemShared(
1739
-			'folder',
1740
-			$fileId,
1741
-			\OCP\Share::FORMAT_NONE,
1742
-			null,
1743
-			true
1744
-		);
1745
-
1746
-		if (count($shares) > 0) {
1747
-			\OCP\Util::writeLog('files',
1748
-				'It is not allowed to move one mount point into a shared folder',
1749
-				\OCP\Util::DEBUG);
1750
-			return false;
1751
-		}
1752
-
1753
-		return true;
1754
-	}
1755
-
1756
-	/**
1757
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1758
-	 *
1759
-	 * @param string $path
1760
-	 * @return \OCP\Files\FileInfo
1761
-	 */
1762
-	private function getPartFileInfo($path) {
1763
-		$mount = $this->getMount($path);
1764
-		$storage = $mount->getStorage();
1765
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1766
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1767
-		return new FileInfo(
1768
-			$this->getAbsolutePath($path),
1769
-			$storage,
1770
-			$internalPath,
1771
-			[
1772
-				'fileid' => null,
1773
-				'mimetype' => $storage->getMimeType($internalPath),
1774
-				'name' => basename($path),
1775
-				'etag' => null,
1776
-				'size' => $storage->filesize($internalPath),
1777
-				'mtime' => $storage->filemtime($internalPath),
1778
-				'encrypted' => false,
1779
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1780
-			],
1781
-			$mount,
1782
-			$owner
1783
-		);
1784
-	}
1785
-
1786
-	/**
1787
-	 * @param string $path
1788
-	 * @param string $fileName
1789
-	 * @throws InvalidPathException
1790
-	 */
1791
-	public function verifyPath($path, $fileName) {
1792
-		try {
1793
-			/** @type \OCP\Files\Storage $storage */
1794
-			list($storage, $internalPath) = $this->resolvePath($path);
1795
-			$storage->verifyPath($internalPath, $fileName);
1796
-		} catch (ReservedWordException $ex) {
1797
-			$l = \OC::$server->getL10N('lib');
1798
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1799
-		} catch (InvalidCharacterInPathException $ex) {
1800
-			$l = \OC::$server->getL10N('lib');
1801
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1802
-		} catch (FileNameTooLongException $ex) {
1803
-			$l = \OC::$server->getL10N('lib');
1804
-			throw new InvalidPathException($l->t('File name is too long'));
1805
-		} catch (InvalidDirectoryException $ex) {
1806
-			$l = \OC::$server->getL10N('lib');
1807
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1808
-		} catch (EmptyFileNameException $ex) {
1809
-			$l = \OC::$server->getL10N('lib');
1810
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1811
-		}
1812
-	}
1813
-
1814
-	/**
1815
-	 * get all parent folders of $path
1816
-	 *
1817
-	 * @param string $path
1818
-	 * @return string[]
1819
-	 */
1820
-	private function getParents($path) {
1821
-		$path = trim($path, '/');
1822
-		if (!$path) {
1823
-			return [];
1824
-		}
1825
-
1826
-		$parts = explode('/', $path);
1827
-
1828
-		// remove the single file
1829
-		array_pop($parts);
1830
-		$result = array('/');
1831
-		$resultPath = '';
1832
-		foreach ($parts as $part) {
1833
-			if ($part) {
1834
-				$resultPath .= '/' . $part;
1835
-				$result[] = $resultPath;
1836
-			}
1837
-		}
1838
-		return $result;
1839
-	}
1840
-
1841
-	/**
1842
-	 * Returns the mount point for which to lock
1843
-	 *
1844
-	 * @param string $absolutePath absolute path
1845
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1846
-	 * is mounted directly on the given path, false otherwise
1847
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1848
-	 */
1849
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1850
-		$results = [];
1851
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1852
-		if (!$mount) {
1853
-			return $results;
1854
-		}
1855
-
1856
-		if ($useParentMount) {
1857
-			// find out if something is mounted directly on the path
1858
-			$internalPath = $mount->getInternalPath($absolutePath);
1859
-			if ($internalPath === '') {
1860
-				// resolve the parent mount instead
1861
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1862
-			}
1863
-		}
1864
-
1865
-		return $mount;
1866
-	}
1867
-
1868
-	/**
1869
-	 * Lock the given path
1870
-	 *
1871
-	 * @param string $path the path of the file to lock, relative to the view
1872
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1873
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1874
-	 *
1875
-	 * @return bool False if the path is excluded from locking, true otherwise
1876
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1877
-	 */
1878
-	private function lockPath($path, $type, $lockMountPoint = false) {
1879
-		$absolutePath = $this->getAbsolutePath($path);
1880
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1881
-		if (!$this->shouldLockFile($absolutePath)) {
1882
-			return false;
1883
-		}
1884
-
1885
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1886
-		if ($mount) {
1887
-			try {
1888
-				$storage = $mount->getStorage();
1889
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1890
-					$storage->acquireLock(
1891
-						$mount->getInternalPath($absolutePath),
1892
-						$type,
1893
-						$this->lockingProvider
1894
-					);
1895
-				}
1896
-			} catch (\OCP\Lock\LockedException $e) {
1897
-				// rethrow with the a human-readable path
1898
-				throw new \OCP\Lock\LockedException(
1899
-					$this->getPathRelativeToFiles($absolutePath),
1900
-					$e
1901
-				);
1902
-			}
1903
-		}
1904
-
1905
-		return true;
1906
-	}
1907
-
1908
-	/**
1909
-	 * Change the lock type
1910
-	 *
1911
-	 * @param string $path the path of the file to lock, relative to the view
1912
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1913
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1914
-	 *
1915
-	 * @return bool False if the path is excluded from locking, true otherwise
1916
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1917
-	 */
1918
-	public function changeLock($path, $type, $lockMountPoint = false) {
1919
-		$path = Filesystem::normalizePath($path);
1920
-		$absolutePath = $this->getAbsolutePath($path);
1921
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1922
-		if (!$this->shouldLockFile($absolutePath)) {
1923
-			return false;
1924
-		}
1925
-
1926
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1927
-		if ($mount) {
1928
-			try {
1929
-				$storage = $mount->getStorage();
1930
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1931
-					$storage->changeLock(
1932
-						$mount->getInternalPath($absolutePath),
1933
-						$type,
1934
-						$this->lockingProvider
1935
-					);
1936
-				}
1937
-			} catch (\OCP\Lock\LockedException $e) {
1938
-				// rethrow with the a human-readable path
1939
-				throw new \OCP\Lock\LockedException(
1940
-					$this->getPathRelativeToFiles($absolutePath),
1941
-					$e
1942
-				);
1943
-			}
1944
-		}
1945
-
1946
-		return true;
1947
-	}
1948
-
1949
-	/**
1950
-	 * Unlock the given path
1951
-	 *
1952
-	 * @param string $path the path of the file to unlock, relative to the view
1953
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1954
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1955
-	 *
1956
-	 * @return bool False if the path is excluded from locking, true otherwise
1957
-	 */
1958
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1959
-		$absolutePath = $this->getAbsolutePath($path);
1960
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1961
-		if (!$this->shouldLockFile($absolutePath)) {
1962
-			return false;
1963
-		}
1964
-
1965
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1966
-		if ($mount) {
1967
-			$storage = $mount->getStorage();
1968
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1969
-				$storage->releaseLock(
1970
-					$mount->getInternalPath($absolutePath),
1971
-					$type,
1972
-					$this->lockingProvider
1973
-				);
1974
-			}
1975
-		}
1976
-
1977
-		return true;
1978
-	}
1979
-
1980
-	/**
1981
-	 * Lock a path and all its parents up to the root of the view
1982
-	 *
1983
-	 * @param string $path the path of the file to lock relative to the view
1984
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1985
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1986
-	 *
1987
-	 * @return bool False if the path is excluded from locking, true otherwise
1988
-	 */
1989
-	public function lockFile($path, $type, $lockMountPoint = false) {
1990
-		$absolutePath = $this->getAbsolutePath($path);
1991
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1992
-		if (!$this->shouldLockFile($absolutePath)) {
1993
-			return false;
1994
-		}
1995
-
1996
-		$this->lockPath($path, $type, $lockMountPoint);
1997
-
1998
-		$parents = $this->getParents($path);
1999
-		foreach ($parents as $parent) {
2000
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2001
-		}
2002
-
2003
-		return true;
2004
-	}
2005
-
2006
-	/**
2007
-	 * Unlock a path and all its parents up to the root of the view
2008
-	 *
2009
-	 * @param string $path the path of the file to lock relative to the view
2010
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2011
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2012
-	 *
2013
-	 * @return bool False if the path is excluded from locking, true otherwise
2014
-	 */
2015
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2016
-		$absolutePath = $this->getAbsolutePath($path);
2017
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2018
-		if (!$this->shouldLockFile($absolutePath)) {
2019
-			return false;
2020
-		}
2021
-
2022
-		$this->unlockPath($path, $type, $lockMountPoint);
2023
-
2024
-		$parents = $this->getParents($path);
2025
-		foreach ($parents as $parent) {
2026
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2027
-		}
2028
-
2029
-		return true;
2030
-	}
2031
-
2032
-	/**
2033
-	 * Only lock files in data/user/files/
2034
-	 *
2035
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2036
-	 * @return bool
2037
-	 */
2038
-	protected function shouldLockFile($path) {
2039
-		$path = Filesystem::normalizePath($path);
2040
-
2041
-		$pathSegments = explode('/', $path);
2042
-		if (isset($pathSegments[2])) {
2043
-			// E.g.: /username/files/path-to-file
2044
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2045
-		}
2046
-
2047
-		return true;
2048
-	}
2049
-
2050
-	/**
2051
-	 * Shortens the given absolute path to be relative to
2052
-	 * "$user/files".
2053
-	 *
2054
-	 * @param string $absolutePath absolute path which is under "files"
2055
-	 *
2056
-	 * @return string path relative to "files" with trimmed slashes or null
2057
-	 * if the path was NOT relative to files
2058
-	 *
2059
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2060
-	 * @since 8.1.0
2061
-	 */
2062
-	public function getPathRelativeToFiles($absolutePath) {
2063
-		$path = Filesystem::normalizePath($absolutePath);
2064
-		$parts = explode('/', trim($path, '/'), 3);
2065
-		// "$user", "files", "path/to/dir"
2066
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2067
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2068
-		}
2069
-		if (isset($parts[2])) {
2070
-			return $parts[2];
2071
-		}
2072
-		return '';
2073
-	}
2074
-
2075
-	/**
2076
-	 * @param string $filename
2077
-	 * @return array
2078
-	 * @throws \OC\User\NoUserException
2079
-	 * @throws NotFoundException
2080
-	 */
2081
-	public function getUidAndFilename($filename) {
2082
-		$info = $this->getFileInfo($filename);
2083
-		if (!$info instanceof \OCP\Files\FileInfo) {
2084
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2085
-		}
2086
-		$uid = $info->getOwner()->getUID();
2087
-		if ($uid != \OCP\User::getUser()) {
2088
-			Filesystem::initMountPoints($uid);
2089
-			$ownerView = new View('/' . $uid . '/files');
2090
-			try {
2091
-				$filename = $ownerView->getPath($info['fileid']);
2092
-			} catch (NotFoundException $e) {
2093
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2094
-			}
2095
-		}
2096
-		return [$uid, $filename];
2097
-	}
2098
-
2099
-	/**
2100
-	 * Creates parent non-existing folders
2101
-	 *
2102
-	 * @param string $filePath
2103
-	 * @return bool
2104
-	 */
2105
-	private function createParentDirectories($filePath) {
2106
-		$directoryParts = explode('/', $filePath);
2107
-		$directoryParts = array_filter($directoryParts);
2108
-		foreach ($directoryParts as $key => $part) {
2109
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2110
-			$currentPath = '/' . implode('/', $currentPathElements);
2111
-			if ($this->is_file($currentPath)) {
2112
-				return false;
2113
-			}
2114
-			if (!$this->file_exists($currentPath)) {
2115
-				$this->mkdir($currentPath);
2116
-			}
2117
-		}
2118
-
2119
-		return true;
2120
-	}
87
+    /** @var string */
88
+    private $fakeRoot = '';
89
+
90
+    /**
91
+     * @var \OCP\Lock\ILockingProvider
92
+     */
93
+    private $lockingProvider;
94
+
95
+    private $lockingEnabled;
96
+
97
+    private $updaterEnabled = true;
98
+
99
+    private $userManager;
100
+
101
+    /**
102
+     * @param string $root
103
+     * @throws \Exception If $root contains an invalid path
104
+     */
105
+    public function __construct($root = '') {
106
+        if (is_null($root)) {
107
+            throw new \InvalidArgumentException('Root can\'t be null');
108
+        }
109
+        if (!Filesystem::isValidPath($root)) {
110
+            throw new \Exception();
111
+        }
112
+
113
+        $this->fakeRoot = $root;
114
+        $this->lockingProvider = \OC::$server->getLockingProvider();
115
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
116
+        $this->userManager = \OC::$server->getUserManager();
117
+    }
118
+
119
+    public function getAbsolutePath($path = '/') {
120
+        if ($path === null) {
121
+            return null;
122
+        }
123
+        $this->assertPathLength($path);
124
+        if ($path === '') {
125
+            $path = '/';
126
+        }
127
+        if ($path[0] !== '/') {
128
+            $path = '/' . $path;
129
+        }
130
+        return $this->fakeRoot . $path;
131
+    }
132
+
133
+    /**
134
+     * change the root to a fake root
135
+     *
136
+     * @param string $fakeRoot
137
+     * @return boolean|null
138
+     */
139
+    public function chroot($fakeRoot) {
140
+        if (!$fakeRoot == '') {
141
+            if ($fakeRoot[0] !== '/') {
142
+                $fakeRoot = '/' . $fakeRoot;
143
+            }
144
+        }
145
+        $this->fakeRoot = $fakeRoot;
146
+    }
147
+
148
+    /**
149
+     * get the fake root
150
+     *
151
+     * @return string
152
+     */
153
+    public function getRoot() {
154
+        return $this->fakeRoot;
155
+    }
156
+
157
+    /**
158
+     * get path relative to the root of the view
159
+     *
160
+     * @param string $path
161
+     * @return string
162
+     */
163
+    public function getRelativePath($path) {
164
+        $this->assertPathLength($path);
165
+        if ($this->fakeRoot == '') {
166
+            return $path;
167
+        }
168
+
169
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
170
+            return '/';
171
+        }
172
+
173
+        // missing slashes can cause wrong matches!
174
+        $root = rtrim($this->fakeRoot, '/') . '/';
175
+
176
+        if (strpos($path, $root) !== 0) {
177
+            return null;
178
+        } else {
179
+            $path = substr($path, strlen($this->fakeRoot));
180
+            if (strlen($path) === 0) {
181
+                return '/';
182
+            } else {
183
+                return $path;
184
+            }
185
+        }
186
+    }
187
+
188
+    /**
189
+     * get the mountpoint of the storage object for a path
190
+     * ( note: because a storage is not always mounted inside the fakeroot, the
191
+     * returned mountpoint is relative to the absolute root of the filesystem
192
+     * and does not take the chroot into account )
193
+     *
194
+     * @param string $path
195
+     * @return string
196
+     */
197
+    public function getMountPoint($path) {
198
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
199
+    }
200
+
201
+    /**
202
+     * get the mountpoint of the storage object for a path
203
+     * ( note: because a storage is not always mounted inside the fakeroot, the
204
+     * returned mountpoint is relative to the absolute root of the filesystem
205
+     * and does not take the chroot into account )
206
+     *
207
+     * @param string $path
208
+     * @return \OCP\Files\Mount\IMountPoint
209
+     */
210
+    public function getMount($path) {
211
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
212
+    }
213
+
214
+    /**
215
+     * resolve a path to a storage and internal path
216
+     *
217
+     * @param string $path
218
+     * @return array an array consisting of the storage and the internal path
219
+     */
220
+    public function resolvePath($path) {
221
+        $a = $this->getAbsolutePath($path);
222
+        $p = Filesystem::normalizePath($a);
223
+        return Filesystem::resolvePath($p);
224
+    }
225
+
226
+    /**
227
+     * return the path to a local version of the file
228
+     * we need this because we can't know if a file is stored local or not from
229
+     * outside the filestorage and for some purposes a local file is needed
230
+     *
231
+     * @param string $path
232
+     * @return string
233
+     */
234
+    public function getLocalFile($path) {
235
+        $parent = substr($path, 0, strrpos($path, '/'));
236
+        $path = $this->getAbsolutePath($path);
237
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
238
+        if (Filesystem::isValidPath($parent) and $storage) {
239
+            return $storage->getLocalFile($internalPath);
240
+        } else {
241
+            return null;
242
+        }
243
+    }
244
+
245
+    /**
246
+     * @param string $path
247
+     * @return string
248
+     */
249
+    public function getLocalFolder($path) {
250
+        $parent = substr($path, 0, strrpos($path, '/'));
251
+        $path = $this->getAbsolutePath($path);
252
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
253
+        if (Filesystem::isValidPath($parent) and $storage) {
254
+            return $storage->getLocalFolder($internalPath);
255
+        } else {
256
+            return null;
257
+        }
258
+    }
259
+
260
+    /**
261
+     * the following functions operate with arguments and return values identical
262
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
263
+     * for \OC\Files\Storage\Storage via basicOperation().
264
+     */
265
+    public function mkdir($path) {
266
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
267
+    }
268
+
269
+    /**
270
+     * remove mount point
271
+     *
272
+     * @param \OC\Files\Mount\MoveableMount $mount
273
+     * @param string $path relative to data/
274
+     * @return boolean
275
+     */
276
+    protected function removeMount($mount, $path) {
277
+        if ($mount instanceof MoveableMount) {
278
+            // cut of /user/files to get the relative path to data/user/files
279
+            $pathParts = explode('/', $path, 4);
280
+            $relPath = '/' . $pathParts[3];
281
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
282
+            \OC_Hook::emit(
283
+                Filesystem::CLASSNAME, "umount",
284
+                array(Filesystem::signal_param_path => $relPath)
285
+            );
286
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
287
+            $result = $mount->removeMount();
288
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
289
+            if ($result) {
290
+                \OC_Hook::emit(
291
+                    Filesystem::CLASSNAME, "post_umount",
292
+                    array(Filesystem::signal_param_path => $relPath)
293
+                );
294
+            }
295
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
296
+            return $result;
297
+        } else {
298
+            // do not allow deleting the storage's root / the mount point
299
+            // because for some storages it might delete the whole contents
300
+            // but isn't supposed to work that way
301
+            return false;
302
+        }
303
+    }
304
+
305
+    public function disableCacheUpdate() {
306
+        $this->updaterEnabled = false;
307
+    }
308
+
309
+    public function enableCacheUpdate() {
310
+        $this->updaterEnabled = true;
311
+    }
312
+
313
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
314
+        if ($this->updaterEnabled) {
315
+            if (is_null($time)) {
316
+                $time = time();
317
+            }
318
+            $storage->getUpdater()->update($internalPath, $time);
319
+        }
320
+    }
321
+
322
+    protected function removeUpdate(Storage $storage, $internalPath) {
323
+        if ($this->updaterEnabled) {
324
+            $storage->getUpdater()->remove($internalPath);
325
+        }
326
+    }
327
+
328
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
329
+        if ($this->updaterEnabled) {
330
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
331
+        }
332
+    }
333
+
334
+    /**
335
+     * @param string $path
336
+     * @return bool|mixed
337
+     */
338
+    public function rmdir($path) {
339
+        $absolutePath = $this->getAbsolutePath($path);
340
+        $mount = Filesystem::getMountManager()->find($absolutePath);
341
+        if ($mount->getInternalPath($absolutePath) === '') {
342
+            return $this->removeMount($mount, $absolutePath);
343
+        }
344
+        if ($this->is_dir($path)) {
345
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
346
+        } else {
347
+            $result = false;
348
+        }
349
+
350
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
351
+            $storage = $mount->getStorage();
352
+            $internalPath = $mount->getInternalPath($absolutePath);
353
+            $storage->getUpdater()->remove($internalPath);
354
+        }
355
+        return $result;
356
+    }
357
+
358
+    /**
359
+     * @param string $path
360
+     * @return resource
361
+     */
362
+    public function opendir($path) {
363
+        return $this->basicOperation('opendir', $path, array('read'));
364
+    }
365
+
366
+    /**
367
+     * @param $handle
368
+     * @return mixed
369
+     */
370
+    public function readdir($handle) {
371
+        $fsLocal = new Storage\Local(array('datadir' => '/'));
372
+        return $fsLocal->readdir($handle);
373
+    }
374
+
375
+    /**
376
+     * @param string $path
377
+     * @return bool|mixed
378
+     */
379
+    public function is_dir($path) {
380
+        if ($path == '/') {
381
+            return true;
382
+        }
383
+        return $this->basicOperation('is_dir', $path);
384
+    }
385
+
386
+    /**
387
+     * @param string $path
388
+     * @return bool|mixed
389
+     */
390
+    public function is_file($path) {
391
+        if ($path == '/') {
392
+            return false;
393
+        }
394
+        return $this->basicOperation('is_file', $path);
395
+    }
396
+
397
+    /**
398
+     * @param string $path
399
+     * @return mixed
400
+     */
401
+    public function stat($path) {
402
+        return $this->basicOperation('stat', $path);
403
+    }
404
+
405
+    /**
406
+     * @param string $path
407
+     * @return mixed
408
+     */
409
+    public function filetype($path) {
410
+        return $this->basicOperation('filetype', $path);
411
+    }
412
+
413
+    /**
414
+     * @param string $path
415
+     * @return mixed
416
+     */
417
+    public function filesize($path) {
418
+        return $this->basicOperation('filesize', $path);
419
+    }
420
+
421
+    /**
422
+     * @param string $path
423
+     * @return bool|mixed
424
+     * @throws \OCP\Files\InvalidPathException
425
+     */
426
+    public function readfile($path) {
427
+        $this->assertPathLength($path);
428
+        @ob_end_clean();
429
+        $handle = $this->fopen($path, 'rb');
430
+        if ($handle) {
431
+            $chunkSize = 8192; // 8 kB chunks
432
+            while (!feof($handle)) {
433
+                echo fread($handle, $chunkSize);
434
+                flush();
435
+            }
436
+            fclose($handle);
437
+            $size = $this->filesize($path);
438
+            return $size;
439
+        }
440
+        return false;
441
+    }
442
+
443
+    /**
444
+     * @param string $path
445
+     * @param int $from
446
+     * @param int $to
447
+     * @return bool|mixed
448
+     * @throws \OCP\Files\InvalidPathException
449
+     * @throws \OCP\Files\UnseekableException
450
+     */
451
+    public function readfilePart($path, $from, $to) {
452
+        $this->assertPathLength($path);
453
+        @ob_end_clean();
454
+        $handle = $this->fopen($path, 'rb');
455
+        if ($handle) {
456
+            if (fseek($handle, $from) === 0) {
457
+                $chunkSize = 8192; // 8 kB chunks
458
+                $end = $to + 1;
459
+                while (!feof($handle) && ftell($handle) < $end) {
460
+                    $len = $end - ftell($handle);
461
+                    if ($len > $chunkSize) {
462
+                        $len = $chunkSize;
463
+                    }
464
+                    echo fread($handle, $len);
465
+                    flush();
466
+                }
467
+                $size = ftell($handle) - $from;
468
+                return $size;
469
+            }
470
+
471
+            throw new \OCP\Files\UnseekableException('fseek error');
472
+        }
473
+        return false;
474
+    }
475
+
476
+    /**
477
+     * @param string $path
478
+     * @return mixed
479
+     */
480
+    public function isCreatable($path) {
481
+        return $this->basicOperation('isCreatable', $path);
482
+    }
483
+
484
+    /**
485
+     * @param string $path
486
+     * @return mixed
487
+     */
488
+    public function isReadable($path) {
489
+        return $this->basicOperation('isReadable', $path);
490
+    }
491
+
492
+    /**
493
+     * @param string $path
494
+     * @return mixed
495
+     */
496
+    public function isUpdatable($path) {
497
+        return $this->basicOperation('isUpdatable', $path);
498
+    }
499
+
500
+    /**
501
+     * @param string $path
502
+     * @return bool|mixed
503
+     */
504
+    public function isDeletable($path) {
505
+        $absolutePath = $this->getAbsolutePath($path);
506
+        $mount = Filesystem::getMountManager()->find($absolutePath);
507
+        if ($mount->getInternalPath($absolutePath) === '') {
508
+            return $mount instanceof MoveableMount;
509
+        }
510
+        return $this->basicOperation('isDeletable', $path);
511
+    }
512
+
513
+    /**
514
+     * @param string $path
515
+     * @return mixed
516
+     */
517
+    public function isSharable($path) {
518
+        return $this->basicOperation('isSharable', $path);
519
+    }
520
+
521
+    /**
522
+     * @param string $path
523
+     * @return bool|mixed
524
+     */
525
+    public function file_exists($path) {
526
+        if ($path == '/') {
527
+            return true;
528
+        }
529
+        return $this->basicOperation('file_exists', $path);
530
+    }
531
+
532
+    /**
533
+     * @param string $path
534
+     * @return mixed
535
+     */
536
+    public function filemtime($path) {
537
+        return $this->basicOperation('filemtime', $path);
538
+    }
539
+
540
+    /**
541
+     * @param string $path
542
+     * @param int|string $mtime
543
+     * @return bool
544
+     */
545
+    public function touch($path, $mtime = null) {
546
+        if (!is_null($mtime) and !is_numeric($mtime)) {
547
+            $mtime = strtotime($mtime);
548
+        }
549
+
550
+        $hooks = array('touch');
551
+
552
+        if (!$this->file_exists($path)) {
553
+            $hooks[] = 'create';
554
+            $hooks[] = 'write';
555
+        }
556
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
557
+        if (!$result) {
558
+            // If create file fails because of permissions on external storage like SMB folders,
559
+            // check file exists and return false if not.
560
+            if (!$this->file_exists($path)) {
561
+                return false;
562
+            }
563
+            if (is_null($mtime)) {
564
+                $mtime = time();
565
+            }
566
+            //if native touch fails, we emulate it by changing the mtime in the cache
567
+            $this->putFileInfo($path, array('mtime' => $mtime));
568
+        }
569
+        return true;
570
+    }
571
+
572
+    /**
573
+     * @param string $path
574
+     * @return mixed
575
+     */
576
+    public function file_get_contents($path) {
577
+        return $this->basicOperation('file_get_contents', $path, array('read'));
578
+    }
579
+
580
+    /**
581
+     * @param bool $exists
582
+     * @param string $path
583
+     * @param bool $run
584
+     */
585
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
586
+        if (!$exists) {
587
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
588
+                Filesystem::signal_param_path => $this->getHookPath($path),
589
+                Filesystem::signal_param_run => &$run,
590
+            ));
591
+        } else {
592
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
593
+                Filesystem::signal_param_path => $this->getHookPath($path),
594
+                Filesystem::signal_param_run => &$run,
595
+            ));
596
+        }
597
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
598
+            Filesystem::signal_param_path => $this->getHookPath($path),
599
+            Filesystem::signal_param_run => &$run,
600
+        ));
601
+    }
602
+
603
+    /**
604
+     * @param bool $exists
605
+     * @param string $path
606
+     */
607
+    protected function emit_file_hooks_post($exists, $path) {
608
+        if (!$exists) {
609
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
610
+                Filesystem::signal_param_path => $this->getHookPath($path),
611
+            ));
612
+        } else {
613
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
614
+                Filesystem::signal_param_path => $this->getHookPath($path),
615
+            ));
616
+        }
617
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
618
+            Filesystem::signal_param_path => $this->getHookPath($path),
619
+        ));
620
+    }
621
+
622
+    /**
623
+     * @param string $path
624
+     * @param mixed $data
625
+     * @return bool|mixed
626
+     * @throws \Exception
627
+     */
628
+    public function file_put_contents($path, $data) {
629
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
630
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
631
+            if (Filesystem::isValidPath($path)
632
+                and !Filesystem::isFileBlacklisted($path)
633
+            ) {
634
+                $path = $this->getRelativePath($absolutePath);
635
+
636
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
637
+
638
+                $exists = $this->file_exists($path);
639
+                $run = true;
640
+                if ($this->shouldEmitHooks($path)) {
641
+                    $this->emit_file_hooks_pre($exists, $path, $run);
642
+                }
643
+                if (!$run) {
644
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
645
+                    return false;
646
+                }
647
+
648
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
649
+
650
+                /** @var \OC\Files\Storage\Storage $storage */
651
+                list($storage, $internalPath) = $this->resolvePath($path);
652
+                $target = $storage->fopen($internalPath, 'w');
653
+                if ($target) {
654
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
655
+                    fclose($target);
656
+                    fclose($data);
657
+
658
+                    $this->writeUpdate($storage, $internalPath);
659
+
660
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
661
+
662
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
663
+                        $this->emit_file_hooks_post($exists, $path);
664
+                    }
665
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
666
+                    return $result;
667
+                } else {
668
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
669
+                    return false;
670
+                }
671
+            } else {
672
+                return false;
673
+            }
674
+        } else {
675
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
676
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
677
+        }
678
+    }
679
+
680
+    /**
681
+     * @param string $path
682
+     * @return bool|mixed
683
+     */
684
+    public function unlink($path) {
685
+        if ($path === '' || $path === '/') {
686
+            // do not allow deleting the root
687
+            return false;
688
+        }
689
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
690
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
691
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
692
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
693
+            return $this->removeMount($mount, $absolutePath);
694
+        }
695
+        $result = $this->basicOperation('unlink', $path, array('delete'));
696
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
697
+            $storage = $mount->getStorage();
698
+            $internalPath = $mount->getInternalPath($absolutePath);
699
+            $storage->getUpdater()->remove($internalPath);
700
+            return true;
701
+        } else {
702
+            return $result;
703
+        }
704
+    }
705
+
706
+    /**
707
+     * @param string $directory
708
+     * @return bool|mixed
709
+     */
710
+    public function deleteAll($directory) {
711
+        return $this->rmdir($directory);
712
+    }
713
+
714
+    /**
715
+     * Rename/move a file or folder from the source path to target path.
716
+     *
717
+     * @param string $path1 source path
718
+     * @param string $path2 target path
719
+     *
720
+     * @return bool|mixed
721
+     */
722
+    public function rename($path1, $path2) {
723
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
724
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
725
+        $result = false;
726
+        if (
727
+            Filesystem::isValidPath($path2)
728
+            and Filesystem::isValidPath($path1)
729
+            and !Filesystem::isFileBlacklisted($path2)
730
+        ) {
731
+            $path1 = $this->getRelativePath($absolutePath1);
732
+            $path2 = $this->getRelativePath($absolutePath2);
733
+            $exists = $this->file_exists($path2);
734
+
735
+            if ($path1 == null or $path2 == null) {
736
+                return false;
737
+            }
738
+
739
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
740
+            try {
741
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
742
+            } catch (LockedException $e) {
743
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
744
+                throw $e;
745
+            }
746
+
747
+            $run = true;
748
+            if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
749
+                // if it was a rename from a part file to a regular file it was a write and not a rename operation
750
+                $this->emit_file_hooks_pre($exists, $path2, $run);
751
+            } elseif ($this->shouldEmitHooks($path1)) {
752
+                \OC_Hook::emit(
753
+                    Filesystem::CLASSNAME, Filesystem::signal_rename,
754
+                    array(
755
+                        Filesystem::signal_param_oldpath => $this->getHookPath($path1),
756
+                        Filesystem::signal_param_newpath => $this->getHookPath($path2),
757
+                        Filesystem::signal_param_run => &$run
758
+                    )
759
+                );
760
+            }
761
+            if ($run) {
762
+                $this->verifyPath(dirname($path2), basename($path2));
763
+
764
+                $manager = Filesystem::getMountManager();
765
+                $mount1 = $this->getMount($path1);
766
+                $mount2 = $this->getMount($path2);
767
+                $storage1 = $mount1->getStorage();
768
+                $storage2 = $mount2->getStorage();
769
+                $internalPath1 = $mount1->getInternalPath($absolutePath1);
770
+                $internalPath2 = $mount2->getInternalPath($absolutePath2);
771
+
772
+                $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
773
+                $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
774
+
775
+                if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
776
+                    if ($this->isTargetAllowed($absolutePath2)) {
777
+                        /**
778
+                         * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
779
+                         */
780
+                        $sourceMountPoint = $mount1->getMountPoint();
781
+                        $result = $mount1->moveMount($absolutePath2);
782
+                        $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
783
+                    } else {
784
+                        $result = false;
785
+                    }
786
+                    // moving a file/folder within the same mount point
787
+                } elseif ($storage1 === $storage2) {
788
+                    if ($storage1) {
789
+                        $result = $storage1->rename($internalPath1, $internalPath2);
790
+                    } else {
791
+                        $result = false;
792
+                    }
793
+                    // moving a file/folder between storages (from $storage1 to $storage2)
794
+                } else {
795
+                    $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
796
+                }
797
+
798
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
799
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
800
+
801
+                    $this->writeUpdate($storage2, $internalPath2);
802
+                } else if ($result) {
803
+                    if ($internalPath1 !== '') { // don't do a cache update for moved mounts
804
+                        $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
805
+                    }
806
+                }
807
+
808
+                $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
809
+                $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
810
+
811
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
812
+                    if ($this->shouldEmitHooks()) {
813
+                        $this->emit_file_hooks_post($exists, $path2);
814
+                    }
815
+                } elseif ($result) {
816
+                    if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
817
+                        \OC_Hook::emit(
818
+                            Filesystem::CLASSNAME,
819
+                            Filesystem::signal_post_rename,
820
+                            array(
821
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
822
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
823
+                            )
824
+                        );
825
+                    }
826
+                }
827
+            }
828
+            $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
829
+            $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
830
+        }
831
+        return $result;
832
+    }
833
+
834
+    /**
835
+     * Copy a file/folder from the source path to target path
836
+     *
837
+     * @param string $path1 source path
838
+     * @param string $path2 target path
839
+     * @param bool $preserveMtime whether to preserve mtime on the copy
840
+     *
841
+     * @return bool|mixed
842
+     */
843
+    public function copy($path1, $path2, $preserveMtime = false) {
844
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
845
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
846
+        $result = false;
847
+        if (
848
+            Filesystem::isValidPath($path2)
849
+            and Filesystem::isValidPath($path1)
850
+            and !Filesystem::isFileBlacklisted($path2)
851
+        ) {
852
+            $path1 = $this->getRelativePath($absolutePath1);
853
+            $path2 = $this->getRelativePath($absolutePath2);
854
+
855
+            if ($path1 == null or $path2 == null) {
856
+                return false;
857
+            }
858
+            $run = true;
859
+
860
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
861
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
862
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
863
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
864
+
865
+            try {
866
+
867
+                $exists = $this->file_exists($path2);
868
+                if ($this->shouldEmitHooks()) {
869
+                    \OC_Hook::emit(
870
+                        Filesystem::CLASSNAME,
871
+                        Filesystem::signal_copy,
872
+                        array(
873
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
874
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
875
+                            Filesystem::signal_param_run => &$run
876
+                        )
877
+                    );
878
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
879
+                }
880
+                if ($run) {
881
+                    $mount1 = $this->getMount($path1);
882
+                    $mount2 = $this->getMount($path2);
883
+                    $storage1 = $mount1->getStorage();
884
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
885
+                    $storage2 = $mount2->getStorage();
886
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
887
+
888
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
889
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
890
+
891
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
892
+                        if ($storage1) {
893
+                            $result = $storage1->copy($internalPath1, $internalPath2);
894
+                        } else {
895
+                            $result = false;
896
+                        }
897
+                    } else {
898
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
899
+                    }
900
+
901
+                    $this->writeUpdate($storage2, $internalPath2);
902
+
903
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
904
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
905
+
906
+                    if ($this->shouldEmitHooks() && $result !== false) {
907
+                        \OC_Hook::emit(
908
+                            Filesystem::CLASSNAME,
909
+                            Filesystem::signal_post_copy,
910
+                            array(
911
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
912
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
913
+                            )
914
+                        );
915
+                        $this->emit_file_hooks_post($exists, $path2);
916
+                    }
917
+
918
+                }
919
+            } catch (\Exception $e) {
920
+                $this->unlockFile($path2, $lockTypePath2);
921
+                $this->unlockFile($path1, $lockTypePath1);
922
+                throw $e;
923
+            }
924
+
925
+            $this->unlockFile($path2, $lockTypePath2);
926
+            $this->unlockFile($path1, $lockTypePath1);
927
+
928
+        }
929
+        return $result;
930
+    }
931
+
932
+    /**
933
+     * @param string $path
934
+     * @param string $mode 'r' or 'w'
935
+     * @return resource
936
+     */
937
+    public function fopen($path, $mode) {
938
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
939
+        $hooks = array();
940
+        switch ($mode) {
941
+            case 'r':
942
+                $hooks[] = 'read';
943
+                break;
944
+            case 'r+':
945
+            case 'w+':
946
+            case 'x+':
947
+            case 'a+':
948
+                $hooks[] = 'read';
949
+                $hooks[] = 'write';
950
+                break;
951
+            case 'w':
952
+            case 'x':
953
+            case 'a':
954
+                $hooks[] = 'write';
955
+                break;
956
+            default:
957
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
958
+        }
959
+
960
+        if ($mode !== 'r' && $mode !== 'w') {
961
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
962
+        }
963
+
964
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
965
+    }
966
+
967
+    /**
968
+     * @param string $path
969
+     * @return bool|string
970
+     * @throws \OCP\Files\InvalidPathException
971
+     */
972
+    public function toTmpFile($path) {
973
+        $this->assertPathLength($path);
974
+        if (Filesystem::isValidPath($path)) {
975
+            $source = $this->fopen($path, 'r');
976
+            if ($source) {
977
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
978
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
979
+                file_put_contents($tmpFile, $source);
980
+                return $tmpFile;
981
+            } else {
982
+                return false;
983
+            }
984
+        } else {
985
+            return false;
986
+        }
987
+    }
988
+
989
+    /**
990
+     * @param string $tmpFile
991
+     * @param string $path
992
+     * @return bool|mixed
993
+     * @throws \OCP\Files\InvalidPathException
994
+     */
995
+    public function fromTmpFile($tmpFile, $path) {
996
+        $this->assertPathLength($path);
997
+        if (Filesystem::isValidPath($path)) {
998
+
999
+            // Get directory that the file is going into
1000
+            $filePath = dirname($path);
1001
+
1002
+            // Create the directories if any
1003
+            if (!$this->file_exists($filePath)) {
1004
+                $result = $this->createParentDirectories($filePath);
1005
+                if ($result === false) {
1006
+                    return false;
1007
+                }
1008
+            }
1009
+
1010
+            $source = fopen($tmpFile, 'r');
1011
+            if ($source) {
1012
+                $result = $this->file_put_contents($path, $source);
1013
+                // $this->file_put_contents() might have already closed
1014
+                // the resource, so we check it, before trying to close it
1015
+                // to avoid messages in the error log.
1016
+                if (is_resource($source)) {
1017
+                    fclose($source);
1018
+                }
1019
+                unlink($tmpFile);
1020
+                return $result;
1021
+            } else {
1022
+                return false;
1023
+            }
1024
+        } else {
1025
+            return false;
1026
+        }
1027
+    }
1028
+
1029
+
1030
+    /**
1031
+     * @param string $path
1032
+     * @return mixed
1033
+     * @throws \OCP\Files\InvalidPathException
1034
+     */
1035
+    public function getMimeType($path) {
1036
+        $this->assertPathLength($path);
1037
+        return $this->basicOperation('getMimeType', $path);
1038
+    }
1039
+
1040
+    /**
1041
+     * @param string $type
1042
+     * @param string $path
1043
+     * @param bool $raw
1044
+     * @return bool|null|string
1045
+     */
1046
+    public function hash($type, $path, $raw = false) {
1047
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1048
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1049
+        if (Filesystem::isValidPath($path)) {
1050
+            $path = $this->getRelativePath($absolutePath);
1051
+            if ($path == null) {
1052
+                return false;
1053
+            }
1054
+            if ($this->shouldEmitHooks($path)) {
1055
+                \OC_Hook::emit(
1056
+                    Filesystem::CLASSNAME,
1057
+                    Filesystem::signal_read,
1058
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1059
+                );
1060
+            }
1061
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1062
+            if ($storage) {
1063
+                $result = $storage->hash($type, $internalPath, $raw);
1064
+                return $result;
1065
+            }
1066
+        }
1067
+        return null;
1068
+    }
1069
+
1070
+    /**
1071
+     * @param string $path
1072
+     * @return mixed
1073
+     * @throws \OCP\Files\InvalidPathException
1074
+     */
1075
+    public function free_space($path = '/') {
1076
+        $this->assertPathLength($path);
1077
+        return $this->basicOperation('free_space', $path);
1078
+    }
1079
+
1080
+    /**
1081
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1082
+     *
1083
+     * @param string $operation
1084
+     * @param string $path
1085
+     * @param array $hooks (optional)
1086
+     * @param mixed $extraParam (optional)
1087
+     * @return mixed
1088
+     * @throws \Exception
1089
+     *
1090
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1091
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1092
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1093
+     */
1094
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1095
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1096
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1097
+        if (Filesystem::isValidPath($path)
1098
+            and !Filesystem::isFileBlacklisted($path)
1099
+        ) {
1100
+            $path = $this->getRelativePath($absolutePath);
1101
+            if ($path == null) {
1102
+                return false;
1103
+            }
1104
+
1105
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1106
+                // always a shared lock during pre-hooks so the hook can read the file
1107
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1108
+            }
1109
+
1110
+            $run = $this->runHooks($hooks, $path);
1111
+            /** @var \OC\Files\Storage\Storage $storage */
1112
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1113
+            if ($run and $storage) {
1114
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1115
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1116
+                }
1117
+                try {
1118
+                    if (!is_null($extraParam)) {
1119
+                        $result = $storage->$operation($internalPath, $extraParam);
1120
+                    } else {
1121
+                        $result = $storage->$operation($internalPath);
1122
+                    }
1123
+                } catch (\Exception $e) {
1124
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1125
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1126
+                    } else if (in_array('read', $hooks)) {
1127
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1128
+                    }
1129
+                    throw $e;
1130
+                }
1131
+
1132
+                if ($result && in_array('delete', $hooks) and $result) {
1133
+                    $this->removeUpdate($storage, $internalPath);
1134
+                }
1135
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1136
+                    $this->writeUpdate($storage, $internalPath);
1137
+                }
1138
+                if ($result && in_array('touch', $hooks)) {
1139
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1140
+                }
1141
+
1142
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1143
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1144
+                }
1145
+
1146
+                $unlockLater = false;
1147
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1148
+                    $unlockLater = true;
1149
+                    // make sure our unlocking callback will still be called if connection is aborted
1150
+                    ignore_user_abort(true);
1151
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1152
+                        if (in_array('write', $hooks)) {
1153
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1154
+                        } else if (in_array('read', $hooks)) {
1155
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1156
+                        }
1157
+                    });
1158
+                }
1159
+
1160
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1161
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1162
+                        $this->runHooks($hooks, $path, true);
1163
+                    }
1164
+                }
1165
+
1166
+                if (!$unlockLater
1167
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1168
+                ) {
1169
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1170
+                }
1171
+                return $result;
1172
+            } else {
1173
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1174
+            }
1175
+        }
1176
+        return null;
1177
+    }
1178
+
1179
+    /**
1180
+     * get the path relative to the default root for hook usage
1181
+     *
1182
+     * @param string $path
1183
+     * @return string
1184
+     */
1185
+    private function getHookPath($path) {
1186
+        if (!Filesystem::getView()) {
1187
+            return $path;
1188
+        }
1189
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1190
+    }
1191
+
1192
+    private function shouldEmitHooks($path = '') {
1193
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1194
+            return false;
1195
+        }
1196
+        if (!Filesystem::$loaded) {
1197
+            return false;
1198
+        }
1199
+        $defaultRoot = Filesystem::getRoot();
1200
+        if ($defaultRoot === null) {
1201
+            return false;
1202
+        }
1203
+        if ($this->fakeRoot === $defaultRoot) {
1204
+            return true;
1205
+        }
1206
+        $fullPath = $this->getAbsolutePath($path);
1207
+
1208
+        if ($fullPath === $defaultRoot) {
1209
+            return true;
1210
+        }
1211
+
1212
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1213
+    }
1214
+
1215
+    /**
1216
+     * @param string[] $hooks
1217
+     * @param string $path
1218
+     * @param bool $post
1219
+     * @return bool
1220
+     */
1221
+    private function runHooks($hooks, $path, $post = false) {
1222
+        $relativePath = $path;
1223
+        $path = $this->getHookPath($path);
1224
+        $prefix = ($post) ? 'post_' : '';
1225
+        $run = true;
1226
+        if ($this->shouldEmitHooks($relativePath)) {
1227
+            foreach ($hooks as $hook) {
1228
+                if ($hook != 'read') {
1229
+                    \OC_Hook::emit(
1230
+                        Filesystem::CLASSNAME,
1231
+                        $prefix . $hook,
1232
+                        array(
1233
+                            Filesystem::signal_param_run => &$run,
1234
+                            Filesystem::signal_param_path => $path
1235
+                        )
1236
+                    );
1237
+                } elseif (!$post) {
1238
+                    \OC_Hook::emit(
1239
+                        Filesystem::CLASSNAME,
1240
+                        $prefix . $hook,
1241
+                        array(
1242
+                            Filesystem::signal_param_path => $path
1243
+                        )
1244
+                    );
1245
+                }
1246
+            }
1247
+        }
1248
+        return $run;
1249
+    }
1250
+
1251
+    /**
1252
+     * check if a file or folder has been updated since $time
1253
+     *
1254
+     * @param string $path
1255
+     * @param int $time
1256
+     * @return bool
1257
+     */
1258
+    public function hasUpdated($path, $time) {
1259
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1260
+    }
1261
+
1262
+    /**
1263
+     * @param string $ownerId
1264
+     * @return \OC\User\User
1265
+     */
1266
+    private function getUserObjectForOwner($ownerId) {
1267
+        $owner = $this->userManager->get($ownerId);
1268
+        if ($owner instanceof IUser) {
1269
+            return $owner;
1270
+        } else {
1271
+            return new User($ownerId, null);
1272
+        }
1273
+    }
1274
+
1275
+    /**
1276
+     * Get file info from cache
1277
+     *
1278
+     * If the file is not in cached it will be scanned
1279
+     * If the file has changed on storage the cache will be updated
1280
+     *
1281
+     * @param \OC\Files\Storage\Storage $storage
1282
+     * @param string $internalPath
1283
+     * @param string $relativePath
1284
+     * @return array|bool
1285
+     */
1286
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1287
+        $cache = $storage->getCache($internalPath);
1288
+        $data = $cache->get($internalPath);
1289
+        $watcher = $storage->getWatcher($internalPath);
1290
+
1291
+        try {
1292
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1293
+            if (!$data || $data['size'] === -1) {
1294
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1295
+                if (!$storage->file_exists($internalPath)) {
1296
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1297
+                    return false;
1298
+                }
1299
+                $scanner = $storage->getScanner($internalPath);
1300
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1301
+                $data = $cache->get($internalPath);
1302
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1303
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1304
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1305
+                $watcher->update($internalPath, $data);
1306
+                $storage->getPropagator()->propagateChange($internalPath, time());
1307
+                $data = $cache->get($internalPath);
1308
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1309
+            }
1310
+        } catch (LockedException $e) {
1311
+            // if the file is locked we just use the old cache info
1312
+        }
1313
+
1314
+        return $data;
1315
+    }
1316
+
1317
+    /**
1318
+     * get the filesystem info
1319
+     *
1320
+     * @param string $path
1321
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1322
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1323
+     * defaults to true
1324
+     * @return \OC\Files\FileInfo|false False if file does not exist
1325
+     */
1326
+    public function getFileInfo($path, $includeMountPoints = true) {
1327
+        $this->assertPathLength($path);
1328
+        if (!Filesystem::isValidPath($path)) {
1329
+            return false;
1330
+        }
1331
+        if (Cache\Scanner::isPartialFile($path)) {
1332
+            return $this->getPartFileInfo($path);
1333
+        }
1334
+        $relativePath = $path;
1335
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1336
+
1337
+        $mount = Filesystem::getMountManager()->find($path);
1338
+        $storage = $mount->getStorage();
1339
+        $internalPath = $mount->getInternalPath($path);
1340
+        if ($storage) {
1341
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1342
+
1343
+            if (!$data instanceof ICacheEntry) {
1344
+                return false;
1345
+            }
1346
+
1347
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1348
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1349
+            }
1350
+
1351
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1352
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1353
+
1354
+            if ($data and isset($data['fileid'])) {
1355
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1356
+                    //add the sizes of other mount points to the folder
1357
+                    $extOnly = ($includeMountPoints === 'ext');
1358
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1359
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1360
+                        $subStorage = $mount->getStorage();
1361
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1362
+                    }));
1363
+                }
1364
+            }
1365
+
1366
+            return $info;
1367
+        }
1368
+
1369
+        return false;
1370
+    }
1371
+
1372
+    /**
1373
+     * get the content of a directory
1374
+     *
1375
+     * @param string $directory path under datadirectory
1376
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1377
+     * @return FileInfo[]
1378
+     */
1379
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1380
+        $this->assertPathLength($directory);
1381
+        if (!Filesystem::isValidPath($directory)) {
1382
+            return [];
1383
+        }
1384
+        $path = $this->getAbsolutePath($directory);
1385
+        $path = Filesystem::normalizePath($path);
1386
+        $mount = $this->getMount($directory);
1387
+        $storage = $mount->getStorage();
1388
+        $internalPath = $mount->getInternalPath($path);
1389
+        if ($storage) {
1390
+            $cache = $storage->getCache($internalPath);
1391
+            $user = \OC_User::getUser();
1392
+
1393
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1394
+
1395
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1396
+                return [];
1397
+            }
1398
+
1399
+            $folderId = $data['fileid'];
1400
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1401
+
1402
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1403
+            /**
1404
+             * @var \OC\Files\FileInfo[] $files
1405
+             */
1406
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1407
+                if ($sharingDisabled) {
1408
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1409
+                }
1410
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1411
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1412
+            }, $contents);
1413
+
1414
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1415
+            $mounts = Filesystem::getMountManager()->findIn($path);
1416
+            $dirLength = strlen($path);
1417
+            foreach ($mounts as $mount) {
1418
+                $mountPoint = $mount->getMountPoint();
1419
+                $subStorage = $mount->getStorage();
1420
+                if ($subStorage) {
1421
+                    $subCache = $subStorage->getCache('');
1422
+
1423
+                    $rootEntry = $subCache->get('');
1424
+                    if (!$rootEntry) {
1425
+                        $subScanner = $subStorage->getScanner('');
1426
+                        try {
1427
+                            $subScanner->scanFile('');
1428
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1429
+                            continue;
1430
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1431
+                            continue;
1432
+                        } catch (\Exception $e) {
1433
+                            // sometimes when the storage is not available it can be any exception
1434
+                            \OCP\Util::writeLog(
1435
+                                'core',
1436
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1437
+                                get_class($e) . ': ' . $e->getMessage(),
1438
+                                \OCP\Util::ERROR
1439
+                            );
1440
+                            continue;
1441
+                        }
1442
+                        $rootEntry = $subCache->get('');
1443
+                    }
1444
+
1445
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1446
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1447
+                        if ($pos = strpos($relativePath, '/')) {
1448
+                            //mountpoint inside subfolder add size to the correct folder
1449
+                            $entryName = substr($relativePath, 0, $pos);
1450
+                            foreach ($files as &$entry) {
1451
+                                if ($entry->getName() === $entryName) {
1452
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1453
+                                }
1454
+                            }
1455
+                        } else { //mountpoint in this folder, add an entry for it
1456
+                            $rootEntry['name'] = $relativePath;
1457
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1458
+                            $permissions = $rootEntry['permissions'];
1459
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1460
+                            // for shared files/folders we use the permissions given by the owner
1461
+                            if ($mount instanceof MoveableMount) {
1462
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1463
+                            } else {
1464
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1465
+                            }
1466
+
1467
+                            //remove any existing entry with the same name
1468
+                            foreach ($files as $i => $file) {
1469
+                                if ($file['name'] === $rootEntry['name']) {
1470
+                                    unset($files[$i]);
1471
+                                    break;
1472
+                                }
1473
+                            }
1474
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1475
+
1476
+                            // if sharing was disabled for the user we remove the share permissions
1477
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1478
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1479
+                            }
1480
+
1481
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1482
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1483
+                        }
1484
+                    }
1485
+                }
1486
+            }
1487
+
1488
+            if ($mimetype_filter) {
1489
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1490
+                    if (strpos($mimetype_filter, '/')) {
1491
+                        return $file->getMimetype() === $mimetype_filter;
1492
+                    } else {
1493
+                        return $file->getMimePart() === $mimetype_filter;
1494
+                    }
1495
+                });
1496
+            }
1497
+
1498
+            return $files;
1499
+        } else {
1500
+            return [];
1501
+        }
1502
+    }
1503
+
1504
+    /**
1505
+     * change file metadata
1506
+     *
1507
+     * @param string $path
1508
+     * @param array|\OCP\Files\FileInfo $data
1509
+     * @return int
1510
+     *
1511
+     * returns the fileid of the updated file
1512
+     */
1513
+    public function putFileInfo($path, $data) {
1514
+        $this->assertPathLength($path);
1515
+        if ($data instanceof FileInfo) {
1516
+            $data = $data->getData();
1517
+        }
1518
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1519
+        /**
1520
+         * @var \OC\Files\Storage\Storage $storage
1521
+         * @var string $internalPath
1522
+         */
1523
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1524
+        if ($storage) {
1525
+            $cache = $storage->getCache($path);
1526
+
1527
+            if (!$cache->inCache($internalPath)) {
1528
+                $scanner = $storage->getScanner($internalPath);
1529
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1530
+            }
1531
+
1532
+            return $cache->put($internalPath, $data);
1533
+        } else {
1534
+            return -1;
1535
+        }
1536
+    }
1537
+
1538
+    /**
1539
+     * search for files with the name matching $query
1540
+     *
1541
+     * @param string $query
1542
+     * @return FileInfo[]
1543
+     */
1544
+    public function search($query) {
1545
+        return $this->searchCommon('search', array('%' . $query . '%'));
1546
+    }
1547
+
1548
+    /**
1549
+     * search for files with the name matching $query
1550
+     *
1551
+     * @param string $query
1552
+     * @return FileInfo[]
1553
+     */
1554
+    public function searchRaw($query) {
1555
+        return $this->searchCommon('search', array($query));
1556
+    }
1557
+
1558
+    /**
1559
+     * search for files by mimetype
1560
+     *
1561
+     * @param string $mimetype
1562
+     * @return FileInfo[]
1563
+     */
1564
+    public function searchByMime($mimetype) {
1565
+        return $this->searchCommon('searchByMime', array($mimetype));
1566
+    }
1567
+
1568
+    /**
1569
+     * search for files by tag
1570
+     *
1571
+     * @param string|int $tag name or tag id
1572
+     * @param string $userId owner of the tags
1573
+     * @return FileInfo[]
1574
+     */
1575
+    public function searchByTag($tag, $userId) {
1576
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1577
+    }
1578
+
1579
+    /**
1580
+     * @param string $method cache method
1581
+     * @param array $args
1582
+     * @return FileInfo[]
1583
+     */
1584
+    private function searchCommon($method, $args) {
1585
+        $files = array();
1586
+        $rootLength = strlen($this->fakeRoot);
1587
+
1588
+        $mount = $this->getMount('');
1589
+        $mountPoint = $mount->getMountPoint();
1590
+        $storage = $mount->getStorage();
1591
+        if ($storage) {
1592
+            $cache = $storage->getCache('');
1593
+
1594
+            $results = call_user_func_array(array($cache, $method), $args);
1595
+            foreach ($results as $result) {
1596
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1597
+                    $internalPath = $result['path'];
1598
+                    $path = $mountPoint . $result['path'];
1599
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1600
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1601
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1602
+                }
1603
+            }
1604
+
1605
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1606
+            foreach ($mounts as $mount) {
1607
+                $mountPoint = $mount->getMountPoint();
1608
+                $storage = $mount->getStorage();
1609
+                if ($storage) {
1610
+                    $cache = $storage->getCache('');
1611
+
1612
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1613
+                    $results = call_user_func_array(array($cache, $method), $args);
1614
+                    if ($results) {
1615
+                        foreach ($results as $result) {
1616
+                            $internalPath = $result['path'];
1617
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1618
+                            $path = rtrim($mountPoint . $internalPath, '/');
1619
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1620
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1621
+                        }
1622
+                    }
1623
+                }
1624
+            }
1625
+        }
1626
+        return $files;
1627
+    }
1628
+
1629
+    /**
1630
+     * Get the owner for a file or folder
1631
+     *
1632
+     * @param string $path
1633
+     * @return string the user id of the owner
1634
+     * @throws NotFoundException
1635
+     */
1636
+    public function getOwner($path) {
1637
+        $info = $this->getFileInfo($path);
1638
+        if (!$info) {
1639
+            throw new NotFoundException($path . ' not found while trying to get owner');
1640
+        }
1641
+        return $info->getOwner()->getUID();
1642
+    }
1643
+
1644
+    /**
1645
+     * get the ETag for a file or folder
1646
+     *
1647
+     * @param string $path
1648
+     * @return string
1649
+     */
1650
+    public function getETag($path) {
1651
+        /**
1652
+         * @var Storage\Storage $storage
1653
+         * @var string $internalPath
1654
+         */
1655
+        list($storage, $internalPath) = $this->resolvePath($path);
1656
+        if ($storage) {
1657
+            return $storage->getETag($internalPath);
1658
+        } else {
1659
+            return null;
1660
+        }
1661
+    }
1662
+
1663
+    /**
1664
+     * Get the path of a file by id, relative to the view
1665
+     *
1666
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1667
+     *
1668
+     * @param int $id
1669
+     * @throws NotFoundException
1670
+     * @return string
1671
+     */
1672
+    public function getPath($id) {
1673
+        $id = (int)$id;
1674
+        $manager = Filesystem::getMountManager();
1675
+        $mounts = $manager->findIn($this->fakeRoot);
1676
+        $mounts[] = $manager->find($this->fakeRoot);
1677
+        // reverse the array so we start with the storage this view is in
1678
+        // which is the most likely to contain the file we're looking for
1679
+        $mounts = array_reverse($mounts);
1680
+        foreach ($mounts as $mount) {
1681
+            /**
1682
+             * @var \OC\Files\Mount\MountPoint $mount
1683
+             */
1684
+            if ($mount->getStorage()) {
1685
+                $cache = $mount->getStorage()->getCache();
1686
+                $internalPath = $cache->getPathById($id);
1687
+                if (is_string($internalPath)) {
1688
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1689
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1690
+                        return $path;
1691
+                    }
1692
+                }
1693
+            }
1694
+        }
1695
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1696
+    }
1697
+
1698
+    /**
1699
+     * @param string $path
1700
+     * @throws InvalidPathException
1701
+     */
1702
+    private function assertPathLength($path) {
1703
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1704
+        // Check for the string length - performed using isset() instead of strlen()
1705
+        // because isset() is about 5x-40x faster.
1706
+        if (isset($path[$maxLen])) {
1707
+            $pathLen = strlen($path);
1708
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1709
+        }
1710
+    }
1711
+
1712
+    /**
1713
+     * check if it is allowed to move a mount point to a given target.
1714
+     * It is not allowed to move a mount point into a different mount point or
1715
+     * into an already shared folder
1716
+     *
1717
+     * @param string $target path
1718
+     * @return boolean
1719
+     */
1720
+    private function isTargetAllowed($target) {
1721
+
1722
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1723
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1724
+            \OCP\Util::writeLog('files',
1725
+                'It is not allowed to move one mount point into another one',
1726
+                \OCP\Util::DEBUG);
1727
+            return false;
1728
+        }
1729
+
1730
+        // note: cannot use the view because the target is already locked
1731
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1732
+        if ($fileId === -1) {
1733
+            // target might not exist, need to check parent instead
1734
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1735
+        }
1736
+
1737
+        // check if any of the parents were shared by the current owner (include collections)
1738
+        $shares = \OCP\Share::getItemShared(
1739
+            'folder',
1740
+            $fileId,
1741
+            \OCP\Share::FORMAT_NONE,
1742
+            null,
1743
+            true
1744
+        );
1745
+
1746
+        if (count($shares) > 0) {
1747
+            \OCP\Util::writeLog('files',
1748
+                'It is not allowed to move one mount point into a shared folder',
1749
+                \OCP\Util::DEBUG);
1750
+            return false;
1751
+        }
1752
+
1753
+        return true;
1754
+    }
1755
+
1756
+    /**
1757
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1758
+     *
1759
+     * @param string $path
1760
+     * @return \OCP\Files\FileInfo
1761
+     */
1762
+    private function getPartFileInfo($path) {
1763
+        $mount = $this->getMount($path);
1764
+        $storage = $mount->getStorage();
1765
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1766
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1767
+        return new FileInfo(
1768
+            $this->getAbsolutePath($path),
1769
+            $storage,
1770
+            $internalPath,
1771
+            [
1772
+                'fileid' => null,
1773
+                'mimetype' => $storage->getMimeType($internalPath),
1774
+                'name' => basename($path),
1775
+                'etag' => null,
1776
+                'size' => $storage->filesize($internalPath),
1777
+                'mtime' => $storage->filemtime($internalPath),
1778
+                'encrypted' => false,
1779
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1780
+            ],
1781
+            $mount,
1782
+            $owner
1783
+        );
1784
+    }
1785
+
1786
+    /**
1787
+     * @param string $path
1788
+     * @param string $fileName
1789
+     * @throws InvalidPathException
1790
+     */
1791
+    public function verifyPath($path, $fileName) {
1792
+        try {
1793
+            /** @type \OCP\Files\Storage $storage */
1794
+            list($storage, $internalPath) = $this->resolvePath($path);
1795
+            $storage->verifyPath($internalPath, $fileName);
1796
+        } catch (ReservedWordException $ex) {
1797
+            $l = \OC::$server->getL10N('lib');
1798
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1799
+        } catch (InvalidCharacterInPathException $ex) {
1800
+            $l = \OC::$server->getL10N('lib');
1801
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1802
+        } catch (FileNameTooLongException $ex) {
1803
+            $l = \OC::$server->getL10N('lib');
1804
+            throw new InvalidPathException($l->t('File name is too long'));
1805
+        } catch (InvalidDirectoryException $ex) {
1806
+            $l = \OC::$server->getL10N('lib');
1807
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1808
+        } catch (EmptyFileNameException $ex) {
1809
+            $l = \OC::$server->getL10N('lib');
1810
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1811
+        }
1812
+    }
1813
+
1814
+    /**
1815
+     * get all parent folders of $path
1816
+     *
1817
+     * @param string $path
1818
+     * @return string[]
1819
+     */
1820
+    private function getParents($path) {
1821
+        $path = trim($path, '/');
1822
+        if (!$path) {
1823
+            return [];
1824
+        }
1825
+
1826
+        $parts = explode('/', $path);
1827
+
1828
+        // remove the single file
1829
+        array_pop($parts);
1830
+        $result = array('/');
1831
+        $resultPath = '';
1832
+        foreach ($parts as $part) {
1833
+            if ($part) {
1834
+                $resultPath .= '/' . $part;
1835
+                $result[] = $resultPath;
1836
+            }
1837
+        }
1838
+        return $result;
1839
+    }
1840
+
1841
+    /**
1842
+     * Returns the mount point for which to lock
1843
+     *
1844
+     * @param string $absolutePath absolute path
1845
+     * @param bool $useParentMount true to return parent mount instead of whatever
1846
+     * is mounted directly on the given path, false otherwise
1847
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1848
+     */
1849
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1850
+        $results = [];
1851
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1852
+        if (!$mount) {
1853
+            return $results;
1854
+        }
1855
+
1856
+        if ($useParentMount) {
1857
+            // find out if something is mounted directly on the path
1858
+            $internalPath = $mount->getInternalPath($absolutePath);
1859
+            if ($internalPath === '') {
1860
+                // resolve the parent mount instead
1861
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1862
+            }
1863
+        }
1864
+
1865
+        return $mount;
1866
+    }
1867
+
1868
+    /**
1869
+     * Lock the given path
1870
+     *
1871
+     * @param string $path the path of the file to lock, relative to the view
1872
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1873
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1874
+     *
1875
+     * @return bool False if the path is excluded from locking, true otherwise
1876
+     * @throws \OCP\Lock\LockedException if the path is already locked
1877
+     */
1878
+    private function lockPath($path, $type, $lockMountPoint = false) {
1879
+        $absolutePath = $this->getAbsolutePath($path);
1880
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1881
+        if (!$this->shouldLockFile($absolutePath)) {
1882
+            return false;
1883
+        }
1884
+
1885
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1886
+        if ($mount) {
1887
+            try {
1888
+                $storage = $mount->getStorage();
1889
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1890
+                    $storage->acquireLock(
1891
+                        $mount->getInternalPath($absolutePath),
1892
+                        $type,
1893
+                        $this->lockingProvider
1894
+                    );
1895
+                }
1896
+            } catch (\OCP\Lock\LockedException $e) {
1897
+                // rethrow with the a human-readable path
1898
+                throw new \OCP\Lock\LockedException(
1899
+                    $this->getPathRelativeToFiles($absolutePath),
1900
+                    $e
1901
+                );
1902
+            }
1903
+        }
1904
+
1905
+        return true;
1906
+    }
1907
+
1908
+    /**
1909
+     * Change the lock type
1910
+     *
1911
+     * @param string $path the path of the file to lock, relative to the view
1912
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1913
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1914
+     *
1915
+     * @return bool False if the path is excluded from locking, true otherwise
1916
+     * @throws \OCP\Lock\LockedException if the path is already locked
1917
+     */
1918
+    public function changeLock($path, $type, $lockMountPoint = false) {
1919
+        $path = Filesystem::normalizePath($path);
1920
+        $absolutePath = $this->getAbsolutePath($path);
1921
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1922
+        if (!$this->shouldLockFile($absolutePath)) {
1923
+            return false;
1924
+        }
1925
+
1926
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1927
+        if ($mount) {
1928
+            try {
1929
+                $storage = $mount->getStorage();
1930
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1931
+                    $storage->changeLock(
1932
+                        $mount->getInternalPath($absolutePath),
1933
+                        $type,
1934
+                        $this->lockingProvider
1935
+                    );
1936
+                }
1937
+            } catch (\OCP\Lock\LockedException $e) {
1938
+                // rethrow with the a human-readable path
1939
+                throw new \OCP\Lock\LockedException(
1940
+                    $this->getPathRelativeToFiles($absolutePath),
1941
+                    $e
1942
+                );
1943
+            }
1944
+        }
1945
+
1946
+        return true;
1947
+    }
1948
+
1949
+    /**
1950
+     * Unlock the given path
1951
+     *
1952
+     * @param string $path the path of the file to unlock, relative to the view
1953
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1954
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1955
+     *
1956
+     * @return bool False if the path is excluded from locking, true otherwise
1957
+     */
1958
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1959
+        $absolutePath = $this->getAbsolutePath($path);
1960
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1961
+        if (!$this->shouldLockFile($absolutePath)) {
1962
+            return false;
1963
+        }
1964
+
1965
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1966
+        if ($mount) {
1967
+            $storage = $mount->getStorage();
1968
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1969
+                $storage->releaseLock(
1970
+                    $mount->getInternalPath($absolutePath),
1971
+                    $type,
1972
+                    $this->lockingProvider
1973
+                );
1974
+            }
1975
+        }
1976
+
1977
+        return true;
1978
+    }
1979
+
1980
+    /**
1981
+     * Lock a path and all its parents up to the root of the view
1982
+     *
1983
+     * @param string $path the path of the file to lock relative to the view
1984
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1985
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1986
+     *
1987
+     * @return bool False if the path is excluded from locking, true otherwise
1988
+     */
1989
+    public function lockFile($path, $type, $lockMountPoint = false) {
1990
+        $absolutePath = $this->getAbsolutePath($path);
1991
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1992
+        if (!$this->shouldLockFile($absolutePath)) {
1993
+            return false;
1994
+        }
1995
+
1996
+        $this->lockPath($path, $type, $lockMountPoint);
1997
+
1998
+        $parents = $this->getParents($path);
1999
+        foreach ($parents as $parent) {
2000
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2001
+        }
2002
+
2003
+        return true;
2004
+    }
2005
+
2006
+    /**
2007
+     * Unlock a path and all its parents up to the root of the view
2008
+     *
2009
+     * @param string $path the path of the file to lock relative to the view
2010
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2011
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2012
+     *
2013
+     * @return bool False if the path is excluded from locking, true otherwise
2014
+     */
2015
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2016
+        $absolutePath = $this->getAbsolutePath($path);
2017
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2018
+        if (!$this->shouldLockFile($absolutePath)) {
2019
+            return false;
2020
+        }
2021
+
2022
+        $this->unlockPath($path, $type, $lockMountPoint);
2023
+
2024
+        $parents = $this->getParents($path);
2025
+        foreach ($parents as $parent) {
2026
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2027
+        }
2028
+
2029
+        return true;
2030
+    }
2031
+
2032
+    /**
2033
+     * Only lock files in data/user/files/
2034
+     *
2035
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2036
+     * @return bool
2037
+     */
2038
+    protected function shouldLockFile($path) {
2039
+        $path = Filesystem::normalizePath($path);
2040
+
2041
+        $pathSegments = explode('/', $path);
2042
+        if (isset($pathSegments[2])) {
2043
+            // E.g.: /username/files/path-to-file
2044
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2045
+        }
2046
+
2047
+        return true;
2048
+    }
2049
+
2050
+    /**
2051
+     * Shortens the given absolute path to be relative to
2052
+     * "$user/files".
2053
+     *
2054
+     * @param string $absolutePath absolute path which is under "files"
2055
+     *
2056
+     * @return string path relative to "files" with trimmed slashes or null
2057
+     * if the path was NOT relative to files
2058
+     *
2059
+     * @throws \InvalidArgumentException if the given path was not under "files"
2060
+     * @since 8.1.0
2061
+     */
2062
+    public function getPathRelativeToFiles($absolutePath) {
2063
+        $path = Filesystem::normalizePath($absolutePath);
2064
+        $parts = explode('/', trim($path, '/'), 3);
2065
+        // "$user", "files", "path/to/dir"
2066
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2067
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2068
+        }
2069
+        if (isset($parts[2])) {
2070
+            return $parts[2];
2071
+        }
2072
+        return '';
2073
+    }
2074
+
2075
+    /**
2076
+     * @param string $filename
2077
+     * @return array
2078
+     * @throws \OC\User\NoUserException
2079
+     * @throws NotFoundException
2080
+     */
2081
+    public function getUidAndFilename($filename) {
2082
+        $info = $this->getFileInfo($filename);
2083
+        if (!$info instanceof \OCP\Files\FileInfo) {
2084
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2085
+        }
2086
+        $uid = $info->getOwner()->getUID();
2087
+        if ($uid != \OCP\User::getUser()) {
2088
+            Filesystem::initMountPoints($uid);
2089
+            $ownerView = new View('/' . $uid . '/files');
2090
+            try {
2091
+                $filename = $ownerView->getPath($info['fileid']);
2092
+            } catch (NotFoundException $e) {
2093
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2094
+            }
2095
+        }
2096
+        return [$uid, $filename];
2097
+    }
2098
+
2099
+    /**
2100
+     * Creates parent non-existing folders
2101
+     *
2102
+     * @param string $filePath
2103
+     * @return bool
2104
+     */
2105
+    private function createParentDirectories($filePath) {
2106
+        $directoryParts = explode('/', $filePath);
2107
+        $directoryParts = array_filter($directoryParts);
2108
+        foreach ($directoryParts as $key => $part) {
2109
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2110
+            $currentPath = '/' . implode('/', $currentPathElements);
2111
+            if ($this->is_file($currentPath)) {
2112
+                return false;
2113
+            }
2114
+            if (!$this->file_exists($currentPath)) {
2115
+                $this->mkdir($currentPath);
2116
+            }
2117
+        }
2118
+
2119
+        return true;
2120
+    }
2121 2121
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
 			$path = '/';
126 126
 		}
127 127
 		if ($path[0] !== '/') {
128
-			$path = '/' . $path;
128
+			$path = '/'.$path;
129 129
 		}
130
-		return $this->fakeRoot . $path;
130
+		return $this->fakeRoot.$path;
131 131
 	}
132 132
 
133 133
 	/**
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	public function chroot($fakeRoot) {
140 140
 		if (!$fakeRoot == '') {
141 141
 			if ($fakeRoot[0] !== '/') {
142
-				$fakeRoot = '/' . $fakeRoot;
142
+				$fakeRoot = '/'.$fakeRoot;
143 143
 			}
144 144
 		}
145 145
 		$this->fakeRoot = $fakeRoot;
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		}
172 172
 
173 173
 		// missing slashes can cause wrong matches!
174
-		$root = rtrim($this->fakeRoot, '/') . '/';
174
+		$root = rtrim($this->fakeRoot, '/').'/';
175 175
 
176 176
 		if (strpos($path, $root) !== 0) {
177 177
 			return null;
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 		if ($mount instanceof MoveableMount) {
278 278
 			// cut of /user/files to get the relative path to data/user/files
279 279
 			$pathParts = explode('/', $path, 4);
280
-			$relPath = '/' . $pathParts[3];
280
+			$relPath = '/'.$pathParts[3];
281 281
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
282 282
 			\OC_Hook::emit(
283 283
 				Filesystem::CLASSNAME, "umount",
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
 		}
689 689
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
690 690
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
691
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
691
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
692 692
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
693 693
 			return $this->removeMount($mount, $absolutePath);
694 694
 		}
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
 				$hooks[] = 'write';
955 955
 				break;
956 956
 			default:
957
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
957
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
958 958
 		}
959 959
 
960 960
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1059 1059
 				);
1060 1060
 			}
1061
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1061
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1062 1062
 			if ($storage) {
1063 1063
 				$result = $storage->hash($type, $internalPath, $raw);
1064 1064
 				return $result;
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 
1110 1110
 			$run = $this->runHooks($hooks, $path);
1111 1111
 			/** @var \OC\Files\Storage\Storage $storage */
1112
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1112
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1113 1113
 			if ($run and $storage) {
1114 1114
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1115 1115
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1148,7 +1148,7 @@  discard block
 block discarded – undo
1148 1148
 					$unlockLater = true;
1149 1149
 					// make sure our unlocking callback will still be called if connection is aborted
1150 1150
 					ignore_user_abort(true);
1151
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1151
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1152 1152
 						if (in_array('write', $hooks)) {
1153 1153
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1154 1154
 						} else if (in_array('read', $hooks)) {
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
 			return true;
1210 1210
 		}
1211 1211
 
1212
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1212
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1213 1213
 	}
1214 1214
 
1215 1215
 	/**
@@ -1228,7 +1228,7 @@  discard block
 block discarded – undo
1228 1228
 				if ($hook != 'read') {
1229 1229
 					\OC_Hook::emit(
1230 1230
 						Filesystem::CLASSNAME,
1231
-						$prefix . $hook,
1231
+						$prefix.$hook,
1232 1232
 						array(
1233 1233
 							Filesystem::signal_param_run => &$run,
1234 1234
 							Filesystem::signal_param_path => $path
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
 				} elseif (!$post) {
1238 1238
 					\OC_Hook::emit(
1239 1239
 						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1240
+						$prefix.$hook,
1241 1241
 						array(
1242 1242
 							Filesystem::signal_param_path => $path
1243 1243
 						)
@@ -1332,7 +1332,7 @@  discard block
 block discarded – undo
1332 1332
 			return $this->getPartFileInfo($path);
1333 1333
 		}
1334 1334
 		$relativePath = $path;
1335
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1335
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1336 1336
 
1337 1337
 		$mount = Filesystem::getMountManager()->find($path);
1338 1338
 		$storage = $mount->getStorage();
@@ -1356,7 +1356,7 @@  discard block
 block discarded – undo
1356 1356
 					//add the sizes of other mount points to the folder
1357 1357
 					$extOnly = ($includeMountPoints === 'ext');
1358 1358
 					$mounts = Filesystem::getMountManager()->findIn($path);
1359
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1359
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1360 1360
 						$subStorage = $mount->getStorage();
1361 1361
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1362 1362
 					}));
@@ -1403,12 +1403,12 @@  discard block
 block discarded – undo
1403 1403
 			/**
1404 1404
 			 * @var \OC\Files\FileInfo[] $files
1405 1405
 			 */
1406
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1406
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1407 1407
 				if ($sharingDisabled) {
1408 1408
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1409 1409
 				}
1410 1410
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1411
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1411
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1412 1412
 			}, $contents);
1413 1413
 
1414 1414
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1433,8 +1433,8 @@  discard block
 block discarded – undo
1433 1433
 							// sometimes when the storage is not available it can be any exception
1434 1434
 							\OCP\Util::writeLog(
1435 1435
 								'core',
1436
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1437
-								get_class($e) . ': ' . $e->getMessage(),
1436
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1437
+								get_class($e).': '.$e->getMessage(),
1438 1438
 								\OCP\Util::ERROR
1439 1439
 							);
1440 1440
 							continue;
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
 									break;
1472 1472
 								}
1473 1473
 							}
1474
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1474
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1475 1475
 
1476 1476
 							// if sharing was disabled for the user we remove the share permissions
1477 1477
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1479,14 +1479,14 @@  discard block
 block discarded – undo
1479 1479
 							}
1480 1480
 
1481 1481
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1482
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1482
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1483 1483
 						}
1484 1484
 					}
1485 1485
 				}
1486 1486
 			}
1487 1487
 
1488 1488
 			if ($mimetype_filter) {
1489
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1489
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1490 1490
 					if (strpos($mimetype_filter, '/')) {
1491 1491
 						return $file->getMimetype() === $mimetype_filter;
1492 1492
 					} else {
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
 		if ($data instanceof FileInfo) {
1516 1516
 			$data = $data->getData();
1517 1517
 		}
1518
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1518
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1519 1519
 		/**
1520 1520
 		 * @var \OC\Files\Storage\Storage $storage
1521 1521
 		 * @var string $internalPath
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
 	 * @return FileInfo[]
1543 1543
 	 */
1544 1544
 	public function search($query) {
1545
-		return $this->searchCommon('search', array('%' . $query . '%'));
1545
+		return $this->searchCommon('search', array('%'.$query.'%'));
1546 1546
 	}
1547 1547
 
1548 1548
 	/**
@@ -1593,10 +1593,10 @@  discard block
 block discarded – undo
1593 1593
 
1594 1594
 			$results = call_user_func_array(array($cache, $method), $args);
1595 1595
 			foreach ($results as $result) {
1596
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1596
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1597 1597
 					$internalPath = $result['path'];
1598
-					$path = $mountPoint . $result['path'];
1599
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1598
+					$path = $mountPoint.$result['path'];
1599
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1600 1600
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1601 1601
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1602 1602
 				}
@@ -1614,8 +1614,8 @@  discard block
 block discarded – undo
1614 1614
 					if ($results) {
1615 1615
 						foreach ($results as $result) {
1616 1616
 							$internalPath = $result['path'];
1617
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1618
-							$path = rtrim($mountPoint . $internalPath, '/');
1617
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1618
+							$path = rtrim($mountPoint.$internalPath, '/');
1619 1619
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1620 1620
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1621 1621
 						}
@@ -1636,7 +1636,7 @@  discard block
 block discarded – undo
1636 1636
 	public function getOwner($path) {
1637 1637
 		$info = $this->getFileInfo($path);
1638 1638
 		if (!$info) {
1639
-			throw new NotFoundException($path . ' not found while trying to get owner');
1639
+			throw new NotFoundException($path.' not found while trying to get owner');
1640 1640
 		}
1641 1641
 		return $info->getOwner()->getUID();
1642 1642
 	}
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
 	 * @return string
1671 1671
 	 */
1672 1672
 	public function getPath($id) {
1673
-		$id = (int)$id;
1673
+		$id = (int) $id;
1674 1674
 		$manager = Filesystem::getMountManager();
1675 1675
 		$mounts = $manager->findIn($this->fakeRoot);
1676 1676
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1685,7 +1685,7 @@  discard block
 block discarded – undo
1685 1685
 				$cache = $mount->getStorage()->getCache();
1686 1686
 				$internalPath = $cache->getPathById($id);
1687 1687
 				if (is_string($internalPath)) {
1688
-					$fullPath = $mount->getMountPoint() . $internalPath;
1688
+					$fullPath = $mount->getMountPoint().$internalPath;
1689 1689
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1690 1690
 						return $path;
1691 1691
 					}
@@ -1728,10 +1728,10 @@  discard block
 block discarded – undo
1728 1728
 		}
1729 1729
 
1730 1730
 		// note: cannot use the view because the target is already locked
1731
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1731
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1732 1732
 		if ($fileId === -1) {
1733 1733
 			// target might not exist, need to check parent instead
1734
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1734
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1735 1735
 		}
1736 1736
 
1737 1737
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1831,7 +1831,7 @@  discard block
 block discarded – undo
1831 1831
 		$resultPath = '';
1832 1832
 		foreach ($parts as $part) {
1833 1833
 			if ($part) {
1834
-				$resultPath .= '/' . $part;
1834
+				$resultPath .= '/'.$part;
1835 1835
 				$result[] = $resultPath;
1836 1836
 			}
1837 1837
 		}
@@ -2081,16 +2081,16 @@  discard block
 block discarded – undo
2081 2081
 	public function getUidAndFilename($filename) {
2082 2082
 		$info = $this->getFileInfo($filename);
2083 2083
 		if (!$info instanceof \OCP\Files\FileInfo) {
2084
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2084
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2085 2085
 		}
2086 2086
 		$uid = $info->getOwner()->getUID();
2087 2087
 		if ($uid != \OCP\User::getUser()) {
2088 2088
 			Filesystem::initMountPoints($uid);
2089
-			$ownerView = new View('/' . $uid . '/files');
2089
+			$ownerView = new View('/'.$uid.'/files');
2090 2090
 			try {
2091 2091
 				$filename = $ownerView->getPath($info['fileid']);
2092 2092
 			} catch (NotFoundException $e) {
2093
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2093
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2094 2094
 			}
2095 2095
 		}
2096 2096
 		return [$uid, $filename];
@@ -2107,7 +2107,7 @@  discard block
 block discarded – undo
2107 2107
 		$directoryParts = array_filter($directoryParts);
2108 2108
 		foreach ($directoryParts as $key => $part) {
2109 2109
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2110
-			$currentPath = '/' . implode('/', $currentPathElements);
2110
+			$currentPath = '/'.implode('/', $currentPathElements);
2111 2111
 			if ($this->is_file($currentPath)) {
2112 2112
 				return false;
2113 2113
 			}
Please login to merge, or discard this patch.
apps/files_sharing/lib/Helper.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -303,6 +303,7 @@
 block discarded – undo
303 303
 	 * get default share folder
304 304
 	 *
305 305
 	 * @param \OC\Files\View
306
+	 * @param View $view
306 307
 	 * @return string
307 308
 	 */
308 309
 	public static function getShareFolder($view = null) {
Please login to merge, or discard this patch.
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
 
37 37
 class Helper {
38 38
 
39
-	public static function registerHooks() {
40
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
-		\OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
-
43
-		\OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
-	}
45
-
46
-	/**
47
-	 * Sets up the filesystem and user for public sharing
48
-	 * @param string $token string share token
49
-	 * @param string $relativePath optional path relative to the share
50
-	 * @param string $password optional password
51
-	 * @return array
52
-	 */
53
-	public static function setupFromToken($token, $relativePath = null, $password = null) {
54
-		\OC_User::setIncognitoMode(true);
55
-
56
-		$shareManager = \OC::$server->getShareManager();
57
-
58
-		try {
59
-			$share = $shareManager->getShareByToken($token);
60
-		} catch (ShareNotFound $e) {
61
-			\OC_Response::setStatus(404);
62
-			\OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
-			exit;
64
-		}
65
-
66
-		\OCP\JSON::checkUserExists($share->getShareOwner());
67
-		\OC_Util::tearDownFS();
68
-		\OC_Util::setupFS($share->getShareOwner());
69
-
70
-
71
-		try {
72
-			$path = Filesystem::getPath($share->getNodeId());
73
-		} catch (NotFoundException $e) {
74
-			\OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
-			\OC_Response::setStatus(404);
76
-			\OCP\JSON::error(array('success' => false));
77
-			exit();
78
-		}
79
-
80
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
-			if (!self::authenticate($share, $password)) {
82
-				\OC_Response::setStatus(403);
83
-				\OCP\JSON::error(array('success' => false));
84
-				exit();
85
-			}
86
-		}
87
-
88
-		$basePath = $path;
89
-
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
-			$path .= Filesystem::normalizePath($relativePath);
92
-		}
93
-
94
-		return array(
95
-			'share' => $share,
96
-			'basePath' => $basePath,
97
-			'realPath' => $path
98
-		);
99
-	}
100
-
101
-	/**
102
-	 * Authenticate link item with the given password
103
-	 * or with the session if no password was given.
104
-	 * @param \OCP\Share\IShare $share
105
-	 * @param string $password optional password
106
-	 *
107
-	 * @return boolean true if authorized, false otherwise
108
-	 */
109
-	public static function authenticate($share, $password = null) {
110
-		$shareManager = \OC::$server->getShareManager();
111
-
112
-		if ($password !== null) {
113
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
-					return true;
117
-				}
118
-			}
119
-		} else {
120
-			// not authenticated ?
121
-			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
-				return true;
124
-			}
125
-		}
126
-		return false;
127
-	}
128
-
129
-	public static function getSharesFromItem($target) {
130
-		$result = array();
131
-		$owner = Filesystem::getOwner($target);
132
-		Filesystem::initMountPoints($owner);
133
-		$info = Filesystem::getFileInfo($target);
134
-		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
136
-			$path = $ownerView->getPath($info['fileid']);
137
-		} else {
138
-			$path = $target;
139
-		}
140
-
141
-
142
-		$ids = array();
143
-		while ($path !== dirname($path)) {
144
-			$info = $ownerView->getFileInfo($path);
145
-			if ($info instanceof \OC\Files\FileInfo) {
146
-				$ids[] = $info['fileid'];
147
-			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
-			}
150
-			$path = dirname($path);
151
-		}
152
-
153
-		if (!empty($ids)) {
154
-
155
-			$idList = array_chunk($ids, 99, true);
156
-
157
-			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
-				$query = \OCP\DB::prepare($statement);
160
-				$r = $query->execute();
161
-				$result = array_merge($result, $r->fetchAll());
162
-			}
163
-		}
164
-
165
-		return $result;
166
-	}
167
-
168
-	/**
169
-	 * get the UID of the owner of the file and the path to the file relative to
170
-	 * owners files folder
171
-	 *
172
-	 * @param $filename
173
-	 * @return array
174
-	 * @throws \OC\User\NoUserException
175
-	 */
176
-	public static function getUidAndFilename($filename) {
177
-		$uid = Filesystem::getOwner($filename);
178
-		$userManager = \OC::$server->getUserManager();
179
-		// if the user with the UID doesn't exists, e.g. because the UID points
180
-		// to a remote user with a federated cloud ID we use the current logged-in
181
-		// user. We need a valid local user to create the share
182
-		if (!$userManager->userExists($uid)) {
183
-			$uid = User::getUser();
184
-		}
185
-		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
187
-			$info = Filesystem::getFileInfo($filename);
188
-			$ownerView = new View('/'.$uid.'/files');
189
-			try {
190
-				$filename = $ownerView->getPath($info['fileid']);
191
-			} catch (NotFoundException $e) {
192
-				$filename = null;
193
-			}
194
-		}
195
-		return [$uid, $filename];
196
-	}
197
-
198
-	/**
199
-	 * Format a path to be relative to the /user/files/ directory
200
-	 * @param string $path the absolute path
201
-	 * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
-	 */
203
-	public static function stripUserFilesPath($path) {
204
-		$trimmed = ltrim($path, '/');
205
-		$split = explode('/', $trimmed);
206
-
207
-		// it is not a file relative to data/user/files
208
-		if (count($split) < 3 || $split[1] !== 'files') {
209
-			return false;
210
-		}
211
-
212
-		$sliced = array_slice($split, 2);
213
-		$relPath = implode('/', $sliced);
214
-
215
-		return $relPath;
216
-	}
217
-
218
-	/**
219
-	 * check if file name already exists and generate unique target
220
-	 *
221
-	 * @param string $path
222
-	 * @param array $excludeList
223
-	 * @param View $view
224
-	 * @return string $path
225
-	 */
226
-	public static function generateUniqueTarget($path, $excludeList, $view) {
227
-		$pathinfo = pathinfo($path);
228
-		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
-		$name = $pathinfo['filename'];
230
-		$dir = $pathinfo['dirname'];
231
-		$i = 2;
232
-		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
-			$i++;
235
-		}
236
-
237
-		return $path;
238
-	}
239
-
240
-	/**
241
-	 * get default share folder
242
-	 *
243
-	 * @param \OC\Files\View
244
-	 * @return string
245
-	 */
246
-	public static function getShareFolder($view = null) {
247
-		if ($view === null) {
248
-			$view = Filesystem::getView();
249
-		}
250
-		$shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
-		$shareFolder = Filesystem::normalizePath($shareFolder);
252
-
253
-		if (!$view->file_exists($shareFolder)) {
254
-			$dir = '';
255
-			$subdirs = explode('/', $shareFolder);
256
-			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
258
-				if (!$view->is_dir($dir)) {
259
-					$view->mkdir($dir);
260
-				}
261
-			}
262
-		}
263
-
264
-		return $shareFolder;
265
-
266
-	}
267
-
268
-	/**
269
-	 * set default share folder
270
-	 *
271
-	 * @param string $shareFolder
272
-	 */
273
-	public static function setShareFolder($shareFolder) {
274
-		\OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
-	}
39
+    public static function registerHooks() {
40
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
+        \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
+
43
+        \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
+    }
45
+
46
+    /**
47
+     * Sets up the filesystem and user for public sharing
48
+     * @param string $token string share token
49
+     * @param string $relativePath optional path relative to the share
50
+     * @param string $password optional password
51
+     * @return array
52
+     */
53
+    public static function setupFromToken($token, $relativePath = null, $password = null) {
54
+        \OC_User::setIncognitoMode(true);
55
+
56
+        $shareManager = \OC::$server->getShareManager();
57
+
58
+        try {
59
+            $share = $shareManager->getShareByToken($token);
60
+        } catch (ShareNotFound $e) {
61
+            \OC_Response::setStatus(404);
62
+            \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
+            exit;
64
+        }
65
+
66
+        \OCP\JSON::checkUserExists($share->getShareOwner());
67
+        \OC_Util::tearDownFS();
68
+        \OC_Util::setupFS($share->getShareOwner());
69
+
70
+
71
+        try {
72
+            $path = Filesystem::getPath($share->getNodeId());
73
+        } catch (NotFoundException $e) {
74
+            \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
+            \OC_Response::setStatus(404);
76
+            \OCP\JSON::error(array('success' => false));
77
+            exit();
78
+        }
79
+
80
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
+            if (!self::authenticate($share, $password)) {
82
+                \OC_Response::setStatus(403);
83
+                \OCP\JSON::error(array('success' => false));
84
+                exit();
85
+            }
86
+        }
87
+
88
+        $basePath = $path;
89
+
90
+        if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
+            $path .= Filesystem::normalizePath($relativePath);
92
+        }
93
+
94
+        return array(
95
+            'share' => $share,
96
+            'basePath' => $basePath,
97
+            'realPath' => $path
98
+        );
99
+    }
100
+
101
+    /**
102
+     * Authenticate link item with the given password
103
+     * or with the session if no password was given.
104
+     * @param \OCP\Share\IShare $share
105
+     * @param string $password optional password
106
+     *
107
+     * @return boolean true if authorized, false otherwise
108
+     */
109
+    public static function authenticate($share, $password = null) {
110
+        $shareManager = \OC::$server->getShareManager();
111
+
112
+        if ($password !== null) {
113
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+                if ($shareManager->checkPassword($share, $password)) {
115
+                    \OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
+                    return true;
117
+                }
118
+            }
119
+        } else {
120
+            // not authenticated ?
121
+            if (\OC::$server->getSession()->exists('public_link_authenticated')
122
+                && \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
+                return true;
124
+            }
125
+        }
126
+        return false;
127
+    }
128
+
129
+    public static function getSharesFromItem($target) {
130
+        $result = array();
131
+        $owner = Filesystem::getOwner($target);
132
+        Filesystem::initMountPoints($owner);
133
+        $info = Filesystem::getFileInfo($target);
134
+        $ownerView = new View('/'.$owner.'/files');
135
+        if ( $owner != User::getUser() ) {
136
+            $path = $ownerView->getPath($info['fileid']);
137
+        } else {
138
+            $path = $target;
139
+        }
140
+
141
+
142
+        $ids = array();
143
+        while ($path !== dirname($path)) {
144
+            $info = $ownerView->getFileInfo($path);
145
+            if ($info instanceof \OC\Files\FileInfo) {
146
+                $ids[] = $info['fileid'];
147
+            } else {
148
+                \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
+            }
150
+            $path = dirname($path);
151
+        }
152
+
153
+        if (!empty($ids)) {
154
+
155
+            $idList = array_chunk($ids, 99, true);
156
+
157
+            foreach ($idList as $subList) {
158
+                $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
+                $query = \OCP\DB::prepare($statement);
160
+                $r = $query->execute();
161
+                $result = array_merge($result, $r->fetchAll());
162
+            }
163
+        }
164
+
165
+        return $result;
166
+    }
167
+
168
+    /**
169
+     * get the UID of the owner of the file and the path to the file relative to
170
+     * owners files folder
171
+     *
172
+     * @param $filename
173
+     * @return array
174
+     * @throws \OC\User\NoUserException
175
+     */
176
+    public static function getUidAndFilename($filename) {
177
+        $uid = Filesystem::getOwner($filename);
178
+        $userManager = \OC::$server->getUserManager();
179
+        // if the user with the UID doesn't exists, e.g. because the UID points
180
+        // to a remote user with a federated cloud ID we use the current logged-in
181
+        // user. We need a valid local user to create the share
182
+        if (!$userManager->userExists($uid)) {
183
+            $uid = User::getUser();
184
+        }
185
+        Filesystem::initMountPoints($uid);
186
+        if ( $uid != User::getUser() ) {
187
+            $info = Filesystem::getFileInfo($filename);
188
+            $ownerView = new View('/'.$uid.'/files');
189
+            try {
190
+                $filename = $ownerView->getPath($info['fileid']);
191
+            } catch (NotFoundException $e) {
192
+                $filename = null;
193
+            }
194
+        }
195
+        return [$uid, $filename];
196
+    }
197
+
198
+    /**
199
+     * Format a path to be relative to the /user/files/ directory
200
+     * @param string $path the absolute path
201
+     * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
+     */
203
+    public static function stripUserFilesPath($path) {
204
+        $trimmed = ltrim($path, '/');
205
+        $split = explode('/', $trimmed);
206
+
207
+        // it is not a file relative to data/user/files
208
+        if (count($split) < 3 || $split[1] !== 'files') {
209
+            return false;
210
+        }
211
+
212
+        $sliced = array_slice($split, 2);
213
+        $relPath = implode('/', $sliced);
214
+
215
+        return $relPath;
216
+    }
217
+
218
+    /**
219
+     * check if file name already exists and generate unique target
220
+     *
221
+     * @param string $path
222
+     * @param array $excludeList
223
+     * @param View $view
224
+     * @return string $path
225
+     */
226
+    public static function generateUniqueTarget($path, $excludeList, $view) {
227
+        $pathinfo = pathinfo($path);
228
+        $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
+        $name = $pathinfo['filename'];
230
+        $dir = $pathinfo['dirname'];
231
+        $i = 2;
232
+        while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
+            $i++;
235
+        }
236
+
237
+        return $path;
238
+    }
239
+
240
+    /**
241
+     * get default share folder
242
+     *
243
+     * @param \OC\Files\View
244
+     * @return string
245
+     */
246
+    public static function getShareFolder($view = null) {
247
+        if ($view === null) {
248
+            $view = Filesystem::getView();
249
+        }
250
+        $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
+        $shareFolder = Filesystem::normalizePath($shareFolder);
252
+
253
+        if (!$view->file_exists($shareFolder)) {
254
+            $dir = '';
255
+            $subdirs = explode('/', $shareFolder);
256
+            foreach ($subdirs as $subdir) {
257
+                $dir = $dir . '/' . $subdir;
258
+                if (!$view->is_dir($dir)) {
259
+                    $view->mkdir($dir);
260
+                }
261
+            }
262
+        }
263
+
264
+        return $shareFolder;
265
+
266
+    }
267
+
268
+    /**
269
+     * set default share folder
270
+     *
271
+     * @param string $shareFolder
272
+     */
273
+    public static function setShareFolder($shareFolder) {
274
+        \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 
88 88
 		$basePath = $path;
89 89
 
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
90
+		if ($relativePath !== null && Filesystem::isReadable($basePath.$relativePath)) {
91 91
 			$path .= Filesystem::normalizePath($relativePath);
92 92
 		}
93 93
 
@@ -112,14 +112,14 @@  discard block
 block discarded – undo
112 112
 		if ($password !== null) {
113 113
 			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114 114
 				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
115
+					\OC::$server->getSession()->set('public_link_authenticated', (string) $share->getId());
116 116
 					return true;
117 117
 				}
118 118
 			}
119 119
 		} else {
120 120
 			// not authenticated ?
121 121
 			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
122
+				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string) $share->getId()) {
123 123
 				return true;
124 124
 			}
125 125
 		}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		Filesystem::initMountPoints($owner);
133 133
 		$info = Filesystem::getFileInfo($target);
134 134
 		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
135
+		if ($owner != User::getUser()) {
136 136
 			$path = $ownerView->getPath($info['fileid']);
137 137
 		} else {
138 138
 			$path = $target;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 			if ($info instanceof \OC\Files\FileInfo) {
146 146
 				$ids[] = $info['fileid'];
147 147
 			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
148
+				\OCP\Util::writeLog('sharing', 'No fileinfo available for: '.$path, \OCP\Util::WARN);
149 149
 			}
150 150
 			$path = dirname($path);
151 151
 		}
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 			$idList = array_chunk($ids, 99, true);
156 156
 
157 157
 			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
158
+				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (".implode(',', $subList).") AND `share_type` IN (0, 1, 2)";
159 159
 				$query = \OCP\DB::prepare($statement);
160 160
 				$r = $query->execute();
161 161
 				$result = array_merge($result, $r->fetchAll());
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 			$uid = User::getUser();
184 184
 		}
185 185
 		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
186
+		if ($uid != User::getUser()) {
187 187
 			$info = Filesystem::getFileInfo($filename);
188 188
 			$ownerView = new View('/'.$uid.'/files');
189 189
 			try {
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		$dir = $pathinfo['dirname'];
231 231
 		$i = 2;
232 232
 		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
233
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
234 234
 			$i++;
235 235
 		}
236 236
 
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 			$dir = '';
255 255
 			$subdirs = explode('/', $shareFolder);
256 256
 			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
257
+				$dir = $dir.'/'.$subdir;
258 258
 				if (!$view->is_dir($dir)) {
259 259
 					$view->mkdir($dir);
260 260
 				}
Please login to merge, or discard this patch.
lib/private/DB/Migrator.php 3 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -273,6 +273,10 @@  discard block
 block discarded – undo
273 273
 		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
274 274
 	}
275 275
 
276
+	/**
277
+	 * @param integer $step
278
+	 * @param integer $max
279
+	 */
276 280
 	protected function emit($sql, $step, $max) {
277 281
 		if ($this->noEmit) {
278 282
 			return;
@@ -283,6 +287,10 @@  discard block
 block discarded – undo
283 287
 		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
284 288
 	}
285 289
 
290
+	/**
291
+	 * @param integer $step
292
+	 * @param integer $max
293
+	 */
286 294
 	private function emitCheckStep($tableName, $step, $max) {
287 295
 		if(is_null($this->dispatcher)) {
288 296
 			return;
Please login to merge, or discard this patch.
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -43,271 +43,271 @@
 block discarded – undo
43 43
 
44 44
 class Migrator {
45 45
 
46
-	/**
47
-	 * @var \Doctrine\DBAL\Connection $connection
48
-	 */
49
-	protected $connection;
50
-
51
-	/**
52
-	 * @var ISecureRandom
53
-	 */
54
-	private $random;
55
-
56
-	/** @var IConfig */
57
-	protected $config;
58
-
59
-	/** @var EventDispatcher  */
60
-	private $dispatcher;
61
-
62
-	/** @var bool */
63
-	private $noEmit = false;
64
-
65
-	/**
66
-	 * @param \Doctrine\DBAL\Connection|Connection $connection
67
-	 * @param ISecureRandom $random
68
-	 * @param IConfig $config
69
-	 * @param EventDispatcher $dispatcher
70
-	 */
71
-	public function __construct(\Doctrine\DBAL\Connection $connection,
72
-								ISecureRandom $random,
73
-								IConfig $config,
74
-								EventDispatcher $dispatcher = null) {
75
-		$this->connection = $connection;
76
-		$this->random = $random;
77
-		$this->config = $config;
78
-		$this->dispatcher = $dispatcher;
79
-	}
80
-
81
-	/**
82
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
83
-	 */
84
-	public function migrate(Schema $targetSchema) {
85
-		$this->noEmit = true;
86
-		$this->applySchema($targetSchema);
87
-	}
88
-
89
-	/**
90
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
91
-	 * @return string
92
-	 */
93
-	public function generateChangeScript(Schema $targetSchema) {
94
-		$schemaDiff = $this->getDiff($targetSchema, $this->connection);
95
-
96
-		$script = '';
97
-		$sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
98
-		foreach ($sqls as $sql) {
99
-			$script .= $this->convertStatementToScript($sql);
100
-		}
101
-
102
-		return $script;
103
-	}
104
-
105
-	/**
106
-	 * @param Schema $targetSchema
107
-	 * @throws \OC\DB\MigrationException
108
-	 */
109
-	public function checkMigrate(Schema $targetSchema) {
110
-		$this->noEmit = true;
111
-		/**@var \Doctrine\DBAL\Schema\Table[] $tables */
112
-		$tables = $targetSchema->getTables();
113
-		$filterExpression = $this->getFilterExpression();
114
-		$this->connection->getConfiguration()->
115
-			setFilterSchemaAssetsExpression($filterExpression);
116
-		$existingTables = $this->connection->getSchemaManager()->listTableNames();
117
-
118
-		$step = 0;
119
-		foreach ($tables as $table) {
120
-			if (strpos($table->getName(), '.')) {
121
-				list(, $tableName) = explode('.', $table->getName());
122
-			} else {
123
-				$tableName = $table->getName();
124
-			}
125
-			$this->emitCheckStep($tableName, $step++, count($tables));
126
-			// don't need to check for new tables
127
-			if (array_search($tableName, $existingTables) !== false) {
128
-				$this->checkTableMigrate($table);
129
-			}
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * Create a unique name for the temporary table
135
-	 *
136
-	 * @param string $name
137
-	 * @return string
138
-	 */
139
-	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
141
-	}
142
-
143
-	/**
144
-	 * Check the migration of a table on a copy so we can detect errors before messing with the real table
145
-	 *
146
-	 * @param \Doctrine\DBAL\Schema\Table $table
147
-	 * @throws \OC\DB\MigrationException
148
-	 */
149
-	protected function checkTableMigrate(Table $table) {
150
-		$name = $table->getName();
151
-		$tmpName = $this->generateTemporaryTableName($name);
152
-
153
-		$this->copyTable($name, $tmpName);
154
-
155
-		//create the migration schema for the temporary table
156
-		$tmpTable = $this->renameTableSchema($table, $tmpName);
157
-		$schemaConfig = new SchemaConfig();
158
-		$schemaConfig->setName($this->connection->getDatabase());
159
-		$schema = new Schema(array($tmpTable), array(), $schemaConfig);
160
-
161
-		try {
162
-			$this->applySchema($schema);
163
-			$this->dropTable($tmpName);
164
-		} catch (DBALException $e) {
165
-			// pgsql needs to commit it's failed transaction before doing anything else
166
-			if ($this->connection->isTransactionActive()) {
167
-				$this->connection->commit();
168
-			}
169
-			$this->dropTable($tmpName);
170
-			throw new MigrationException($table->getName(), $e->getMessage());
171
-		}
172
-	}
173
-
174
-	/**
175
-	 * @param \Doctrine\DBAL\Schema\Table $table
176
-	 * @param string $newName
177
-	 * @return \Doctrine\DBAL\Schema\Table
178
-	 */
179
-	protected function renameTableSchema(Table $table, $newName) {
180
-		/**
181
-		 * @var \Doctrine\DBAL\Schema\Index[] $indexes
182
-		 */
183
-		$indexes = $table->getIndexes();
184
-		$newIndexes = array();
185
-		foreach ($indexes as $index) {
186
-			if ($index->isPrimary()) {
187
-				// do not rename primary key
188
-				$indexName = $index->getName();
189
-			} else {
190
-				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
192
-			}
193
-			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194
-		}
195
-
196
-		// foreign keys are not supported so we just set it to an empty array
197
-		return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
198
-	}
199
-
200
-	/**
201
-	 * @param Schema $targetSchema
202
-	 * @param \Doctrine\DBAL\Connection $connection
203
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
204
-	 * @throws DBALException
205
-	 */
206
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
207
-		// adjust varchar columns with a length higher then getVarcharMaxLength to clob
208
-		foreach ($targetSchema->getTables() as $table) {
209
-			foreach ($table->getColumns() as $column) {
210
-				if ($column->getType() instanceof StringType) {
211
-					if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
212
-						$column->setType(Type::getType('text'));
213
-						$column->setLength(null);
214
-					}
215
-				}
216
-			}
217
-		}
218
-
219
-		$filterExpression = $this->getFilterExpression();
220
-		$this->connection->getConfiguration()->
221
-		setFilterSchemaAssetsExpression($filterExpression);
222
-		$sourceSchema = $connection->getSchemaManager()->createSchema();
223
-
224
-		// remove tables we don't know about
225
-		/** @var $table \Doctrine\DBAL\Schema\Table */
226
-		foreach ($sourceSchema->getTables() as $table) {
227
-			if (!$targetSchema->hasTable($table->getName())) {
228
-				$sourceSchema->dropTable($table->getName());
229
-			}
230
-		}
231
-		// remove sequences we don't know about
232
-		foreach ($sourceSchema->getSequences() as $table) {
233
-			if (!$targetSchema->hasSequence($table->getName())) {
234
-				$sourceSchema->dropSequence($table->getName());
235
-			}
236
-		}
237
-
238
-		$comparator = new Comparator();
239
-		return $comparator->compare($sourceSchema, $targetSchema);
240
-	}
241
-
242
-	/**
243
-	 * @param \Doctrine\DBAL\Schema\Schema $targetSchema
244
-	 * @param \Doctrine\DBAL\Connection $connection
245
-	 */
246
-	protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
247
-		if (is_null($connection)) {
248
-			$connection = $this->connection;
249
-		}
250
-
251
-		$schemaDiff = $this->getDiff($targetSchema, $connection);
252
-
253
-		$connection->beginTransaction();
254
-		$sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
255
-		$step = 0;
256
-		foreach ($sqls as $sql) {
257
-			$this->emit($sql, $step++, count($sqls));
258
-			$connection->query($sql);
259
-		}
260
-		$connection->commit();
261
-	}
262
-
263
-	/**
264
-	 * @param string $sourceName
265
-	 * @param string $targetName
266
-	 */
267
-	protected function copyTable($sourceName, $targetName) {
268
-		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269
-		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270
-
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
273
-	}
274
-
275
-	/**
276
-	 * @param string $name
277
-	 */
278
-	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
280
-	}
281
-
282
-	/**
283
-	 * @param $statement
284
-	 * @return string
285
-	 */
286
-	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
288
-		$script .= PHP_EOL;
289
-		$script .= PHP_EOL;
290
-		return $script;
291
-	}
292
-
293
-	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
295
-	}
296
-
297
-	protected function emit($sql, $step, $max) {
298
-		if ($this->noEmit) {
299
-			return;
300
-		}
301
-		if(is_null($this->dispatcher)) {
302
-			return;
303
-		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
305
-	}
306
-
307
-	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
309
-			return;
310
-		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
312
-	}
46
+    /**
47
+     * @var \Doctrine\DBAL\Connection $connection
48
+     */
49
+    protected $connection;
50
+
51
+    /**
52
+     * @var ISecureRandom
53
+     */
54
+    private $random;
55
+
56
+    /** @var IConfig */
57
+    protected $config;
58
+
59
+    /** @var EventDispatcher  */
60
+    private $dispatcher;
61
+
62
+    /** @var bool */
63
+    private $noEmit = false;
64
+
65
+    /**
66
+     * @param \Doctrine\DBAL\Connection|Connection $connection
67
+     * @param ISecureRandom $random
68
+     * @param IConfig $config
69
+     * @param EventDispatcher $dispatcher
70
+     */
71
+    public function __construct(\Doctrine\DBAL\Connection $connection,
72
+                                ISecureRandom $random,
73
+                                IConfig $config,
74
+                                EventDispatcher $dispatcher = null) {
75
+        $this->connection = $connection;
76
+        $this->random = $random;
77
+        $this->config = $config;
78
+        $this->dispatcher = $dispatcher;
79
+    }
80
+
81
+    /**
82
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
83
+     */
84
+    public function migrate(Schema $targetSchema) {
85
+        $this->noEmit = true;
86
+        $this->applySchema($targetSchema);
87
+    }
88
+
89
+    /**
90
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
91
+     * @return string
92
+     */
93
+    public function generateChangeScript(Schema $targetSchema) {
94
+        $schemaDiff = $this->getDiff($targetSchema, $this->connection);
95
+
96
+        $script = '';
97
+        $sqls = $schemaDiff->toSql($this->connection->getDatabasePlatform());
98
+        foreach ($sqls as $sql) {
99
+            $script .= $this->convertStatementToScript($sql);
100
+        }
101
+
102
+        return $script;
103
+    }
104
+
105
+    /**
106
+     * @param Schema $targetSchema
107
+     * @throws \OC\DB\MigrationException
108
+     */
109
+    public function checkMigrate(Schema $targetSchema) {
110
+        $this->noEmit = true;
111
+        /**@var \Doctrine\DBAL\Schema\Table[] $tables */
112
+        $tables = $targetSchema->getTables();
113
+        $filterExpression = $this->getFilterExpression();
114
+        $this->connection->getConfiguration()->
115
+            setFilterSchemaAssetsExpression($filterExpression);
116
+        $existingTables = $this->connection->getSchemaManager()->listTableNames();
117
+
118
+        $step = 0;
119
+        foreach ($tables as $table) {
120
+            if (strpos($table->getName(), '.')) {
121
+                list(, $tableName) = explode('.', $table->getName());
122
+            } else {
123
+                $tableName = $table->getName();
124
+            }
125
+            $this->emitCheckStep($tableName, $step++, count($tables));
126
+            // don't need to check for new tables
127
+            if (array_search($tableName, $existingTables) !== false) {
128
+                $this->checkTableMigrate($table);
129
+            }
130
+        }
131
+    }
132
+
133
+    /**
134
+     * Create a unique name for the temporary table
135
+     *
136
+     * @param string $name
137
+     * @return string
138
+     */
139
+    protected function generateTemporaryTableName($name) {
140
+        return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
141
+    }
142
+
143
+    /**
144
+     * Check the migration of a table on a copy so we can detect errors before messing with the real table
145
+     *
146
+     * @param \Doctrine\DBAL\Schema\Table $table
147
+     * @throws \OC\DB\MigrationException
148
+     */
149
+    protected function checkTableMigrate(Table $table) {
150
+        $name = $table->getName();
151
+        $tmpName = $this->generateTemporaryTableName($name);
152
+
153
+        $this->copyTable($name, $tmpName);
154
+
155
+        //create the migration schema for the temporary table
156
+        $tmpTable = $this->renameTableSchema($table, $tmpName);
157
+        $schemaConfig = new SchemaConfig();
158
+        $schemaConfig->setName($this->connection->getDatabase());
159
+        $schema = new Schema(array($tmpTable), array(), $schemaConfig);
160
+
161
+        try {
162
+            $this->applySchema($schema);
163
+            $this->dropTable($tmpName);
164
+        } catch (DBALException $e) {
165
+            // pgsql needs to commit it's failed transaction before doing anything else
166
+            if ($this->connection->isTransactionActive()) {
167
+                $this->connection->commit();
168
+            }
169
+            $this->dropTable($tmpName);
170
+            throw new MigrationException($table->getName(), $e->getMessage());
171
+        }
172
+    }
173
+
174
+    /**
175
+     * @param \Doctrine\DBAL\Schema\Table $table
176
+     * @param string $newName
177
+     * @return \Doctrine\DBAL\Schema\Table
178
+     */
179
+    protected function renameTableSchema(Table $table, $newName) {
180
+        /**
181
+         * @var \Doctrine\DBAL\Schema\Index[] $indexes
182
+         */
183
+        $indexes = $table->getIndexes();
184
+        $newIndexes = array();
185
+        foreach ($indexes as $index) {
186
+            if ($index->isPrimary()) {
187
+                // do not rename primary key
188
+                $indexName = $index->getName();
189
+            } else {
190
+                // avoid conflicts in index names
191
+                $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
192
+            }
193
+            $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194
+        }
195
+
196
+        // foreign keys are not supported so we just set it to an empty array
197
+        return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
198
+    }
199
+
200
+    /**
201
+     * @param Schema $targetSchema
202
+     * @param \Doctrine\DBAL\Connection $connection
203
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
204
+     * @throws DBALException
205
+     */
206
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
207
+        // adjust varchar columns with a length higher then getVarcharMaxLength to clob
208
+        foreach ($targetSchema->getTables() as $table) {
209
+            foreach ($table->getColumns() as $column) {
210
+                if ($column->getType() instanceof StringType) {
211
+                    if ($column->getLength() > $connection->getDatabasePlatform()->getVarcharMaxLength()) {
212
+                        $column->setType(Type::getType('text'));
213
+                        $column->setLength(null);
214
+                    }
215
+                }
216
+            }
217
+        }
218
+
219
+        $filterExpression = $this->getFilterExpression();
220
+        $this->connection->getConfiguration()->
221
+        setFilterSchemaAssetsExpression($filterExpression);
222
+        $sourceSchema = $connection->getSchemaManager()->createSchema();
223
+
224
+        // remove tables we don't know about
225
+        /** @var $table \Doctrine\DBAL\Schema\Table */
226
+        foreach ($sourceSchema->getTables() as $table) {
227
+            if (!$targetSchema->hasTable($table->getName())) {
228
+                $sourceSchema->dropTable($table->getName());
229
+            }
230
+        }
231
+        // remove sequences we don't know about
232
+        foreach ($sourceSchema->getSequences() as $table) {
233
+            if (!$targetSchema->hasSequence($table->getName())) {
234
+                $sourceSchema->dropSequence($table->getName());
235
+            }
236
+        }
237
+
238
+        $comparator = new Comparator();
239
+        return $comparator->compare($sourceSchema, $targetSchema);
240
+    }
241
+
242
+    /**
243
+     * @param \Doctrine\DBAL\Schema\Schema $targetSchema
244
+     * @param \Doctrine\DBAL\Connection $connection
245
+     */
246
+    protected function applySchema(Schema $targetSchema, \Doctrine\DBAL\Connection $connection = null) {
247
+        if (is_null($connection)) {
248
+            $connection = $this->connection;
249
+        }
250
+
251
+        $schemaDiff = $this->getDiff($targetSchema, $connection);
252
+
253
+        $connection->beginTransaction();
254
+        $sqls = $schemaDiff->toSql($connection->getDatabasePlatform());
255
+        $step = 0;
256
+        foreach ($sqls as $sql) {
257
+            $this->emit($sql, $step++, count($sqls));
258
+            $connection->query($sql);
259
+        }
260
+        $connection->commit();
261
+    }
262
+
263
+    /**
264
+     * @param string $sourceName
265
+     * @param string $targetName
266
+     */
267
+    protected function copyTable($sourceName, $targetName) {
268
+        $quotedSource = $this->connection->quoteIdentifier($sourceName);
269
+        $quotedTarget = $this->connection->quoteIdentifier($targetName);
270
+
271
+        $this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
+        $this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
273
+    }
274
+
275
+    /**
276
+     * @param string $name
277
+     */
278
+    protected function dropTable($name) {
279
+        $this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
280
+    }
281
+
282
+    /**
283
+     * @param $statement
284
+     * @return string
285
+     */
286
+    protected function convertStatementToScript($statement) {
287
+        $script = $statement . ';';
288
+        $script .= PHP_EOL;
289
+        $script .= PHP_EOL;
290
+        return $script;
291
+    }
292
+
293
+    protected function getFilterExpression() {
294
+        return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
295
+    }
296
+
297
+    protected function emit($sql, $step, $max) {
298
+        if ($this->noEmit) {
299
+            return;
300
+        }
301
+        if(is_null($this->dispatcher)) {
302
+            return;
303
+        }
304
+        $this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
305
+    }
306
+
307
+    private function emitCheckStep($tableName, $step, $max) {
308
+        if(is_null($this->dispatcher)) {
309
+            return;
310
+        }
311
+        $this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
312
+    }
313 313
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return string
138 138
 	 */
139 139
 	protected function generateTemporaryTableName($name) {
140
-		return $this->config->getSystemValue('dbtableprefix', 'oc_') . $name . '_' . $this->random->generate(13, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS);
140
+		return $this->config->getSystemValue('dbtableprefix', 'oc_').$name.'_'.$this->random->generate(13, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
141 141
 	}
142 142
 
143 143
 	/**
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 				$indexName = $index->getName();
189 189
 			} else {
190 190
 				// avoid conflicts in index names
191
-				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
191
+				$indexName = $this->config->getSystemValue('dbtableprefix', 'oc_').$this->random->generate(13, ISecureRandom::CHAR_LOWER);
192 192
 			}
193 193
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
194 194
 		}
@@ -268,15 +268,15 @@  discard block
 block discarded – undo
268 268
 		$quotedSource = $this->connection->quoteIdentifier($sourceName);
269 269
 		$quotedTarget = $this->connection->quoteIdentifier($targetName);
270 270
 
271
-		$this->connection->exec('CREATE TABLE ' . $quotedTarget . ' (LIKE ' . $quotedSource . ')');
272
-		$this->connection->exec('INSERT INTO ' . $quotedTarget . ' SELECT * FROM ' . $quotedSource);
271
+		$this->connection->exec('CREATE TABLE '.$quotedTarget.' (LIKE '.$quotedSource.')');
272
+		$this->connection->exec('INSERT INTO '.$quotedTarget.' SELECT * FROM '.$quotedSource);
273 273
 	}
274 274
 
275 275
 	/**
276 276
 	 * @param string $name
277 277
 	 */
278 278
 	protected function dropTable($name) {
279
-		$this->connection->exec('DROP TABLE ' . $this->connection->quoteIdentifier($name));
279
+		$this->connection->exec('DROP TABLE '.$this->connection->quoteIdentifier($name));
280 280
 	}
281 281
 
282 282
 	/**
@@ -284,30 +284,30 @@  discard block
 block discarded – undo
284 284
 	 * @return string
285 285
 	 */
286 286
 	protected function convertStatementToScript($statement) {
287
-		$script = $statement . ';';
287
+		$script = $statement.';';
288 288
 		$script .= PHP_EOL;
289 289
 		$script .= PHP_EOL;
290 290
 		return $script;
291 291
 	}
292 292
 
293 293
 	protected function getFilterExpression() {
294
-		return '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
294
+		return '/^'.preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')).'/';
295 295
 	}
296 296
 
297 297
 	protected function emit($sql, $step, $max) {
298 298
 		if ($this->noEmit) {
299 299
 			return;
300 300
 		}
301
-		if(is_null($this->dispatcher)) {
301
+		if (is_null($this->dispatcher)) {
302 302
 			return;
303 303
 		}
304
-		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step+1, $max]));
304
+		$this->dispatcher->dispatch('\OC\DB\Migrator::executeSql', new GenericEvent($sql, [$step + 1, $max]));
305 305
 	}
306 306
 
307 307
 	private function emitCheckStep($tableName, $step, $max) {
308
-		if(is_null($this->dispatcher)) {
308
+		if (is_null($this->dispatcher)) {
309 309
 			return;
310 310
 		}
311
-		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step+1, $max]));
311
+		$this->dispatcher->dispatch('\OC\DB\Migrator::checkTable', new GenericEvent($tableName, [$step + 1, $max]));
312 312
 	}
313 313
 }
Please login to merge, or discard this patch.
settings/Controller/CheckSetupController.php 3 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,6 +103,7 @@  discard block
 block discarded – undo
103 103
 
104 104
 	/**
105 105
 	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
106
+	* @param string $sitename
106 107
 	* @return bool
107 108
 	*/
108 109
 	private function isSiteReachable($sitename) {
@@ -285,7 +286,7 @@  discard block
 block discarded – undo
285 286
 
286 287
 	/**
287 288
 	 * @NoCSRFRequired
288
-	 * @return DataResponse
289
+	 * @return DataDisplayResponse
289 290
 	 */
290 291
 	public function getFailedIntegrityCheckFiles() {
291 292
 		if(!$this->checker->isCodeCheckEnforced()) {
Please login to merge, or discard this patch.
Indentation   +357 added lines, -357 removed lines patch added patch discarded remove patch
@@ -46,268 +46,268 @@  discard block
 block discarded – undo
46 46
  * @package OC\Settings\Controller
47 47
  */
48 48
 class CheckSetupController extends Controller {
49
-	/** @var IConfig */
50
-	private $config;
51
-	/** @var IClientService */
52
-	private $clientService;
53
-	/** @var \OC_Util */
54
-	private $util;
55
-	/** @var IURLGenerator */
56
-	private $urlGenerator;
57
-	/** @var IL10N */
58
-	private $l10n;
59
-	/** @var Checker */
60
-	private $checker;
61
-	/** @var ILogger */
62
-	private $logger;
63
-
64
-	/**
65
-	 * @param string $AppName
66
-	 * @param IRequest $request
67
-	 * @param IConfig $config
68
-	 * @param IClientService $clientService
69
-	 * @param IURLGenerator $urlGenerator
70
-	 * @param \OC_Util $util
71
-	 * @param IL10N $l10n
72
-	 * @param Checker $checker
73
-	 * @param ILogger $logger
74
-	 */
75
-	public function __construct($AppName,
76
-								IRequest $request,
77
-								IConfig $config,
78
-								IClientService $clientService,
79
-								IURLGenerator $urlGenerator,
80
-								\OC_Util $util,
81
-								IL10N $l10n,
82
-								Checker $checker,
83
-								ILogger $logger) {
84
-		parent::__construct($AppName, $request);
85
-		$this->config = $config;
86
-		$this->clientService = $clientService;
87
-		$this->util = $util;
88
-		$this->urlGenerator = $urlGenerator;
89
-		$this->l10n = $l10n;
90
-		$this->checker = $checker;
91
-		$this->logger = $logger;
92
-	}
93
-
94
-	/**
95
-	 * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
96
-	 * @return bool
97
-	 */
98
-	private function isInternetConnectionWorking() {
99
-		if ($this->config->getSystemValue('has_internet_connection', true) === false) {
100
-			return false;
101
-		}
102
-
103
-		$siteArray = ['www.nextcloud.com',
104
-						'www.google.com',
105
-						'www.github.com'];
106
-
107
-		foreach($siteArray as $site) {
108
-			if ($this->isSiteReachable($site)) {
109
-				return true;
110
-			}
111
-		}
112
-		return false;
113
-	}
114
-
115
-	/**
116
-	* Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
117
-	* @return bool
118
-	*/
119
-	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
122
-
123
-		try {
124
-			$client = $this->clientService->newClient();
125
-			$client->get($httpSiteName);
126
-			$client->get($httpsSiteName);
127
-		} catch (\Exception $e) {
128
-			$this->logger->logException($e, ['app' => 'internet_connection_check']);
129
-			return false;
130
-		}
131
-		return true;
132
-	}
133
-
134
-	/**
135
-	 * Checks whether a local memcache is installed or not
136
-	 * @return bool
137
-	 */
138
-	private function isMemcacheConfigured() {
139
-		return $this->config->getSystemValue('memcache.local', null) !== null;
140
-	}
141
-
142
-	/**
143
-	 * Whether /dev/urandom is available to the PHP controller
144
-	 *
145
-	 * @return bool
146
-	 */
147
-	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
149
-			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
151
-				fclose($file);
152
-				return true;
153
-			}
154
-		}
155
-
156
-		return false;
157
-	}
158
-
159
-	/**
160
-	 * Public for the sake of unit-testing
161
-	 *
162
-	 * @return array
163
-	 */
164
-	protected function getCurlVersion() {
165
-		return curl_version();
166
-	}
167
-
168
-	/**
169
-	 * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
170
-	 * have multiple bugs which likely lead to problems in combination with
171
-	 * functionality required by ownCloud such as SNI.
172
-	 *
173
-	 * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
174
-	 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
175
-	 * @return string
176
-	 */
177
-	private function isUsedTlsLibOutdated() {
178
-		// Don't run check when:
179
-		// 1. Server has `has_internet_connection` set to false
180
-		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
182
-			return '';
183
-		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
185
-			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186
-			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187
-			return '';
188
-		}
189
-
190
-		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
192
-			$versionString = $versionString['ssl_version'];
193
-		} else {
194
-			return '';
195
-		}
196
-
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
200
-		}
201
-
202
-		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
204
-			$majorVersion = substr($versionString, 8, 5);
205
-			$patchRelease = substr($versionString, 13, 6);
206
-
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208
-				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209
-				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210
-			}
211
-		}
212
-
213
-		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
215
-			try {
216
-				$firstClient = $this->clientService->newClient();
217
-				$firstClient->get('https://www.owncloud.org/');
218
-
219
-				$secondClient = $this->clientService->newClient();
220
-				$secondClient->get('https://owncloud.org/');
221
-			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
223
-					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224
-				}
225
-			}
226
-		}
227
-
228
-		return '';
229
-	}
230
-
231
-	/**
232
-	 * Whether the version is outdated
233
-	 *
234
-	 * @return bool
235
-	 */
236
-	protected function isPhpOutdated() {
237
-		if (version_compare(PHP_VERSION, '5.5.0') === -1) {
238
-			return true;
239
-		}
240
-
241
-		return false;
242
-	}
243
-
244
-	/**
245
-	 * Whether the php version is still supported (at time of release)
246
-	 * according to: https://secure.php.net/supported-versions.php
247
-	 *
248
-	 * @return array
249
-	 */
250
-	private function isPhpSupported() {
251
-		return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
252
-	}
253
-
254
-	/**
255
-	 * Check if the reverse proxy configuration is working as expected
256
-	 *
257
-	 * @return bool
258
-	 */
259
-	private function forwardedForHeadersWorking() {
260
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
261
-		$remoteAddress = $this->request->getRemoteAddress();
262
-
263
-		if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
264
-			return false;
265
-		}
266
-
267
-		// either not enabled or working correctly
268
-		return true;
269
-	}
270
-
271
-	/**
272
-	 * Checks if the correct memcache module for PHP is installed. Only
273
-	 * fails if memcached is configured and the working module is not installed.
274
-	 *
275
-	 * @return bool
276
-	 */
277
-	private function isCorrectMemcachedPHPModuleInstalled() {
278
-		if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
279
-			return true;
280
-		}
281
-
282
-		// there are two different memcached modules for PHP
283
-		// we only support memcached and not memcache
284
-		// https://code.google.com/p/memcached/wiki/PHPClientComparison
285
-		return !(!extension_loaded('memcached') && extension_loaded('memcache'));
286
-	}
287
-
288
-	/**
289
-	 * @return RedirectResponse
290
-	 */
291
-	public function rescanFailedIntegrityCheck() {
292
-		$this->checker->runInstanceVerification();
293
-		return new RedirectResponse(
294
-			$this->urlGenerator->linkToRoute('settings.AdminSettings.index')
295
-		);
296
-	}
297
-
298
-	/**
299
-	 * @NoCSRFRequired
300
-	 * @return DataResponse
301
-	 */
302
-	public function getFailedIntegrityCheckFiles() {
303
-		if(!$this->checker->isCodeCheckEnforced()) {
304
-			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
305
-		}
306
-
307
-		$completeResults = $this->checker->getResults();
308
-
309
-		if(!empty($completeResults)) {
310
-			$formattedTextResponse = 'Technical information
49
+    /** @var IConfig */
50
+    private $config;
51
+    /** @var IClientService */
52
+    private $clientService;
53
+    /** @var \OC_Util */
54
+    private $util;
55
+    /** @var IURLGenerator */
56
+    private $urlGenerator;
57
+    /** @var IL10N */
58
+    private $l10n;
59
+    /** @var Checker */
60
+    private $checker;
61
+    /** @var ILogger */
62
+    private $logger;
63
+
64
+    /**
65
+     * @param string $AppName
66
+     * @param IRequest $request
67
+     * @param IConfig $config
68
+     * @param IClientService $clientService
69
+     * @param IURLGenerator $urlGenerator
70
+     * @param \OC_Util $util
71
+     * @param IL10N $l10n
72
+     * @param Checker $checker
73
+     * @param ILogger $logger
74
+     */
75
+    public function __construct($AppName,
76
+                                IRequest $request,
77
+                                IConfig $config,
78
+                                IClientService $clientService,
79
+                                IURLGenerator $urlGenerator,
80
+                                \OC_Util $util,
81
+                                IL10N $l10n,
82
+                                Checker $checker,
83
+                                ILogger $logger) {
84
+        parent::__construct($AppName, $request);
85
+        $this->config = $config;
86
+        $this->clientService = $clientService;
87
+        $this->util = $util;
88
+        $this->urlGenerator = $urlGenerator;
89
+        $this->l10n = $l10n;
90
+        $this->checker = $checker;
91
+        $this->logger = $logger;
92
+    }
93
+
94
+    /**
95
+     * Checks if the ownCloud server can connect to the internet using HTTPS and HTTP
96
+     * @return bool
97
+     */
98
+    private function isInternetConnectionWorking() {
99
+        if ($this->config->getSystemValue('has_internet_connection', true) === false) {
100
+            return false;
101
+        }
102
+
103
+        $siteArray = ['www.nextcloud.com',
104
+                        'www.google.com',
105
+                        'www.github.com'];
106
+
107
+        foreach($siteArray as $site) {
108
+            if ($this->isSiteReachable($site)) {
109
+                return true;
110
+            }
111
+        }
112
+        return false;
113
+    }
114
+
115
+    /**
116
+     * Chceks if the ownCloud server can connect to a specific URL using both HTTPS and HTTP
117
+     * @return bool
118
+     */
119
+    private function isSiteReachable($sitename) {
120
+        $httpSiteName = 'http://' . $sitename . '/';
121
+        $httpsSiteName = 'https://' . $sitename . '/';
122
+
123
+        try {
124
+            $client = $this->clientService->newClient();
125
+            $client->get($httpSiteName);
126
+            $client->get($httpsSiteName);
127
+        } catch (\Exception $e) {
128
+            $this->logger->logException($e, ['app' => 'internet_connection_check']);
129
+            return false;
130
+        }
131
+        return true;
132
+    }
133
+
134
+    /**
135
+     * Checks whether a local memcache is installed or not
136
+     * @return bool
137
+     */
138
+    private function isMemcacheConfigured() {
139
+        return $this->config->getSystemValue('memcache.local', null) !== null;
140
+    }
141
+
142
+    /**
143
+     * Whether /dev/urandom is available to the PHP controller
144
+     *
145
+     * @return bool
146
+     */
147
+    private function isUrandomAvailable() {
148
+        if(@file_exists('/dev/urandom')) {
149
+            $file = fopen('/dev/urandom', 'rb');
150
+            if($file) {
151
+                fclose($file);
152
+                return true;
153
+            }
154
+        }
155
+
156
+        return false;
157
+    }
158
+
159
+    /**
160
+     * Public for the sake of unit-testing
161
+     *
162
+     * @return array
163
+     */
164
+    protected function getCurlVersion() {
165
+        return curl_version();
166
+    }
167
+
168
+    /**
169
+     * Check if the used  SSL lib is outdated. Older OpenSSL and NSS versions do
170
+     * have multiple bugs which likely lead to problems in combination with
171
+     * functionality required by ownCloud such as SNI.
172
+     *
173
+     * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546
174
+     * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172
175
+     * @return string
176
+     */
177
+    private function isUsedTlsLibOutdated() {
178
+        // Don't run check when:
179
+        // 1. Server has `has_internet_connection` set to false
180
+        // 2. AppStore AND S2S is disabled
181
+        if(!$this->config->getSystemValue('has_internet_connection', true)) {
182
+            return '';
183
+        }
184
+        if(!$this->config->getSystemValue('appstoreenabled', true)
185
+            && $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186
+            && $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187
+            return '';
188
+        }
189
+
190
+        $versionString = $this->getCurlVersion();
191
+        if(isset($versionString['ssl_version'])) {
192
+            $versionString = $versionString['ssl_version'];
193
+        } else {
194
+            return '';
195
+        }
196
+
197
+        $features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+        if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
+            $features = (string)$this->l10n->t('Federated Cloud Sharing');
200
+        }
201
+
202
+        // Check if at least OpenSSL after 1.01d or 1.0.2b
203
+        if(strpos($versionString, 'OpenSSL/') === 0) {
204
+            $majorVersion = substr($versionString, 8, 5);
205
+            $patchRelease = substr($versionString, 13, 6);
206
+
207
+            if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208
+                ($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209
+                return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210
+            }
211
+        }
212
+
213
+        // Check if NSS and perform heuristic check
214
+        if(strpos($versionString, 'NSS/') === 0) {
215
+            try {
216
+                $firstClient = $this->clientService->newClient();
217
+                $firstClient->get('https://www.owncloud.org/');
218
+
219
+                $secondClient = $this->clientService->newClient();
220
+                $secondClient->get('https://owncloud.org/');
221
+            } catch (ClientException $e) {
222
+                if($e->getResponse()->getStatusCode() === 400) {
223
+                    return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224
+                }
225
+            }
226
+        }
227
+
228
+        return '';
229
+    }
230
+
231
+    /**
232
+     * Whether the version is outdated
233
+     *
234
+     * @return bool
235
+     */
236
+    protected function isPhpOutdated() {
237
+        if (version_compare(PHP_VERSION, '5.5.0') === -1) {
238
+            return true;
239
+        }
240
+
241
+        return false;
242
+    }
243
+
244
+    /**
245
+     * Whether the php version is still supported (at time of release)
246
+     * according to: https://secure.php.net/supported-versions.php
247
+     *
248
+     * @return array
249
+     */
250
+    private function isPhpSupported() {
251
+        return ['eol' => $this->isPhpOutdated(), 'version' => PHP_VERSION];
252
+    }
253
+
254
+    /**
255
+     * Check if the reverse proxy configuration is working as expected
256
+     *
257
+     * @return bool
258
+     */
259
+    private function forwardedForHeadersWorking() {
260
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
261
+        $remoteAddress = $this->request->getRemoteAddress();
262
+
263
+        if (is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) {
264
+            return false;
265
+        }
266
+
267
+        // either not enabled or working correctly
268
+        return true;
269
+    }
270
+
271
+    /**
272
+     * Checks if the correct memcache module for PHP is installed. Only
273
+     * fails if memcached is configured and the working module is not installed.
274
+     *
275
+     * @return bool
276
+     */
277
+    private function isCorrectMemcachedPHPModuleInstalled() {
278
+        if ($this->config->getSystemValue('memcache.distributed', null) !== '\OC\Memcache\Memcached') {
279
+            return true;
280
+        }
281
+
282
+        // there are two different memcached modules for PHP
283
+        // we only support memcached and not memcache
284
+        // https://code.google.com/p/memcached/wiki/PHPClientComparison
285
+        return !(!extension_loaded('memcached') && extension_loaded('memcache'));
286
+    }
287
+
288
+    /**
289
+     * @return RedirectResponse
290
+     */
291
+    public function rescanFailedIntegrityCheck() {
292
+        $this->checker->runInstanceVerification();
293
+        return new RedirectResponse(
294
+            $this->urlGenerator->linkToRoute('settings.AdminSettings.index')
295
+        );
296
+    }
297
+
298
+    /**
299
+     * @NoCSRFRequired
300
+     * @return DataResponse
301
+     */
302
+    public function getFailedIntegrityCheckFiles() {
303
+        if(!$this->checker->isCodeCheckEnforced()) {
304
+            return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
305
+        }
306
+
307
+        $completeResults = $this->checker->getResults();
308
+
309
+        if(!empty($completeResults)) {
310
+            $formattedTextResponse = 'Technical information
311 311
 =====================
312 312
 The following list covers which files have failed the integrity check. Please read
313 313
 the previous linked documentation to learn more about the errors and how to fix
@@ -316,102 +316,102 @@  discard block
 block discarded – undo
316 316
 Results
317 317
 =======
318 318
 ';
319
-			foreach($completeResults as $context => $contextResult) {
320
-				$formattedTextResponse .= "- $context\n";
321
-
322
-				foreach($contextResult as $category => $result) {
323
-					$formattedTextResponse .= "\t- $category\n";
324
-					if($category !== 'EXCEPTION') {
325
-						foreach ($result as $key => $results) {
326
-							$formattedTextResponse .= "\t\t- $key\n";
327
-						}
328
-					} else {
329
-						foreach ($result as $key => $results) {
330
-							$formattedTextResponse .= "\t\t- $results\n";
331
-						}
332
-					}
333
-
334
-				}
335
-			}
336
-
337
-			$formattedTextResponse .= '
319
+            foreach($completeResults as $context => $contextResult) {
320
+                $formattedTextResponse .= "- $context\n";
321
+
322
+                foreach($contextResult as $category => $result) {
323
+                    $formattedTextResponse .= "\t- $category\n";
324
+                    if($category !== 'EXCEPTION') {
325
+                        foreach ($result as $key => $results) {
326
+                            $formattedTextResponse .= "\t\t- $key\n";
327
+                        }
328
+                    } else {
329
+                        foreach ($result as $key => $results) {
330
+                            $formattedTextResponse .= "\t\t- $results\n";
331
+                        }
332
+                    }
333
+
334
+                }
335
+            }
336
+
337
+            $formattedTextResponse .= '
338 338
 Raw output
339 339
 ==========
340 340
 ';
341
-			$formattedTextResponse .= print_r($completeResults, true);
342
-		} else {
343
-			$formattedTextResponse = 'No errors have been found.';
344
-		}
345
-
346
-
347
-		$response = new DataDisplayResponse(
348
-			$formattedTextResponse,
349
-			Http::STATUS_OK,
350
-			[
351
-				'Content-Type' => 'text/plain',
352
-			]
353
-		);
354
-
355
-		return $response;
356
-	}
357
-
358
-	/**
359
-	 * Checks whether a PHP opcache is properly set up
360
-	 * @return bool
361
-	 */
362
-	private function isOpcacheProperlySetup() {
363
-		$iniWrapper = new IniGetWrapper();
364
-
365
-		$isOpcacheProperlySetUp = true;
366
-
367
-		if(!$iniWrapper->getBool('opcache.enable')) {
368
-			$isOpcacheProperlySetUp = false;
369
-		}
370
-
371
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
372
-			$isOpcacheProperlySetUp = false;
373
-		}
374
-
375
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
376
-			$isOpcacheProperlySetUp = false;
377
-		}
378
-
379
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
380
-			$isOpcacheProperlySetUp = false;
381
-		}
382
-
383
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
384
-			$isOpcacheProperlySetUp = false;
385
-		}
386
-
387
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
388
-			$isOpcacheProperlySetUp = false;
389
-		}
390
-
391
-		return $isOpcacheProperlySetUp;
392
-	}
393
-
394
-	/**
395
-	 * @return DataResponse
396
-	 */
397
-	public function check() {
398
-		return new DataResponse(
399
-			[
400
-				'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
401
-				'isMemcacheConfigured' => $this->isMemcacheConfigured(),
402
-				'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
403
-				'isUrandomAvailable' => $this->isUrandomAvailable(),
404
-				'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
405
-				'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
406
-				'phpSupported' => $this->isPhpSupported(),
407
-				'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
408
-				'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
409
-				'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
410
-				'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
411
-				'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
412
-				'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
413
-				'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
414
-			]
415
-		);
416
-	}
341
+            $formattedTextResponse .= print_r($completeResults, true);
342
+        } else {
343
+            $formattedTextResponse = 'No errors have been found.';
344
+        }
345
+
346
+
347
+        $response = new DataDisplayResponse(
348
+            $formattedTextResponse,
349
+            Http::STATUS_OK,
350
+            [
351
+                'Content-Type' => 'text/plain',
352
+            ]
353
+        );
354
+
355
+        return $response;
356
+    }
357
+
358
+    /**
359
+     * Checks whether a PHP opcache is properly set up
360
+     * @return bool
361
+     */
362
+    private function isOpcacheProperlySetup() {
363
+        $iniWrapper = new IniGetWrapper();
364
+
365
+        $isOpcacheProperlySetUp = true;
366
+
367
+        if(!$iniWrapper->getBool('opcache.enable')) {
368
+            $isOpcacheProperlySetUp = false;
369
+        }
370
+
371
+        if(!$iniWrapper->getBool('opcache.save_comments')) {
372
+            $isOpcacheProperlySetUp = false;
373
+        }
374
+
375
+        if(!$iniWrapper->getBool('opcache.enable_cli')) {
376
+            $isOpcacheProperlySetUp = false;
377
+        }
378
+
379
+        if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
380
+            $isOpcacheProperlySetUp = false;
381
+        }
382
+
383
+        if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
384
+            $isOpcacheProperlySetUp = false;
385
+        }
386
+
387
+        if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
388
+            $isOpcacheProperlySetUp = false;
389
+        }
390
+
391
+        return $isOpcacheProperlySetUp;
392
+    }
393
+
394
+    /**
395
+     * @return DataResponse
396
+     */
397
+    public function check() {
398
+        return new DataResponse(
399
+            [
400
+                'serverHasInternetConnection' => $this->isInternetConnectionWorking(),
401
+                'isMemcacheConfigured' => $this->isMemcacheConfigured(),
402
+                'memcacheDocs' => $this->urlGenerator->linkToDocs('admin-performance'),
403
+                'isUrandomAvailable' => $this->isUrandomAvailable(),
404
+                'securityDocs' => $this->urlGenerator->linkToDocs('admin-security'),
405
+                'isUsedTlsLibOutdated' => $this->isUsedTlsLibOutdated(),
406
+                'phpSupported' => $this->isPhpSupported(),
407
+                'forwardedForHeadersWorking' => $this->forwardedForHeadersWorking(),
408
+                'reverseProxyDocs' => $this->urlGenerator->linkToDocs('admin-reverse-proxy'),
409
+                'isCorrectMemcachedPHPModuleInstalled' => $this->isCorrectMemcachedPHPModuleInstalled(),
410
+                'hasPassedCodeIntegrityCheck' => $this->checker->hasPassedCheck(),
411
+                'codeIntegrityCheckerDocumentation' => $this->urlGenerator->linkToDocs('admin-code-integrity'),
412
+                'isOpcacheProperlySetup' => $this->isOpcacheProperlySetup(),
413
+                'phpOpcacheDocumentation' => $this->urlGenerator->linkToDocs('admin-php-opcache'),
414
+            ]
415
+        );
416
+    }
417 417
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 						'www.google.com',
105 105
 						'www.github.com'];
106 106
 
107
-		foreach($siteArray as $site) {
107
+		foreach ($siteArray as $site) {
108 108
 			if ($this->isSiteReachable($site)) {
109 109
 				return true;
110 110
 			}
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 	* @return bool
118 118
 	*/
119 119
 	private function isSiteReachable($sitename) {
120
-		$httpSiteName = 'http://' . $sitename . '/';
121
-		$httpsSiteName = 'https://' . $sitename . '/';
120
+		$httpSiteName = 'http://'.$sitename.'/';
121
+		$httpsSiteName = 'https://'.$sitename.'/';
122 122
 
123 123
 		try {
124 124
 			$client = $this->clientService->newClient();
@@ -145,9 +145,9 @@  discard block
 block discarded – undo
145 145
 	 * @return bool
146 146
 	 */
147 147
 	private function isUrandomAvailable() {
148
-		if(@file_exists('/dev/urandom')) {
148
+		if (@file_exists('/dev/urandom')) {
149 149
 			$file = fopen('/dev/urandom', 'rb');
150
-			if($file) {
150
+			if ($file) {
151 151
 				fclose($file);
152 152
 				return true;
153 153
 			}
@@ -178,40 +178,40 @@  discard block
 block discarded – undo
178 178
 		// Don't run check when:
179 179
 		// 1. Server has `has_internet_connection` set to false
180 180
 		// 2. AppStore AND S2S is disabled
181
-		if(!$this->config->getSystemValue('has_internet_connection', true)) {
181
+		if (!$this->config->getSystemValue('has_internet_connection', true)) {
182 182
 			return '';
183 183
 		}
184
-		if(!$this->config->getSystemValue('appstoreenabled', true)
184
+		if (!$this->config->getSystemValue('appstoreenabled', true)
185 185
 			&& $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'no'
186 186
 			&& $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes') === 'no') {
187 187
 			return '';
188 188
 		}
189 189
 
190 190
 		$versionString = $this->getCurlVersion();
191
-		if(isset($versionString['ssl_version'])) {
191
+		if (isset($versionString['ssl_version'])) {
192 192
 			$versionString = $versionString['ssl_version'];
193 193
 		} else {
194 194
 			return '';
195 195
 		}
196 196
 
197
-		$features = (string)$this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
-		if(!$this->config->getSystemValue('appstoreenabled', true)) {
199
-			$features = (string)$this->l10n->t('Federated Cloud Sharing');
197
+		$features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing');
198
+		if (!$this->config->getSystemValue('appstoreenabled', true)) {
199
+			$features = (string) $this->l10n->t('Federated Cloud Sharing');
200 200
 		}
201 201
 
202 202
 		// Check if at least OpenSSL after 1.01d or 1.0.2b
203
-		if(strpos($versionString, 'OpenSSL/') === 0) {
203
+		if (strpos($versionString, 'OpenSSL/') === 0) {
204 204
 			$majorVersion = substr($versionString, 8, 5);
205 205
 			$patchRelease = substr($versionString, 13, 6);
206 206
 
207
-			if(($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
207
+			if (($majorVersion === '1.0.1' && ord($patchRelease) < ord('d')) ||
208 208
 				($majorVersion === '1.0.2' && ord($patchRelease) < ord('b'))) {
209 209
 				return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]);
210 210
 			}
211 211
 		}
212 212
 
213 213
 		// Check if NSS and perform heuristic check
214
-		if(strpos($versionString, 'NSS/') === 0) {
214
+		if (strpos($versionString, 'NSS/') === 0) {
215 215
 			try {
216 216
 				$firstClient = $this->clientService->newClient();
217 217
 				$firstClient->get('https://www.owncloud.org/');
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 				$secondClient = $this->clientService->newClient();
220 220
 				$secondClient->get('https://owncloud.org/');
221 221
 			} catch (ClientException $e) {
222
-				if($e->getResponse()->getStatusCode() === 400) {
222
+				if ($e->getResponse()->getStatusCode() === 400) {
223 223
 					return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]);
224 224
 				}
225 225
 			}
@@ -300,13 +300,13 @@  discard block
 block discarded – undo
300 300
 	 * @return DataResponse
301 301
 	 */
302 302
 	public function getFailedIntegrityCheckFiles() {
303
-		if(!$this->checker->isCodeCheckEnforced()) {
303
+		if (!$this->checker->isCodeCheckEnforced()) {
304 304
 			return new DataDisplayResponse('Integrity checker has been disabled. Integrity cannot be verified.');
305 305
 		}
306 306
 
307 307
 		$completeResults = $this->checker->getResults();
308 308
 
309
-		if(!empty($completeResults)) {
309
+		if (!empty($completeResults)) {
310 310
 			$formattedTextResponse = 'Technical information
311 311
 =====================
312 312
 The following list covers which files have failed the integrity check. Please read
@@ -316,12 +316,12 @@  discard block
 block discarded – undo
316 316
 Results
317 317
 =======
318 318
 ';
319
-			foreach($completeResults as $context => $contextResult) {
319
+			foreach ($completeResults as $context => $contextResult) {
320 320
 				$formattedTextResponse .= "- $context\n";
321 321
 
322
-				foreach($contextResult as $category => $result) {
322
+				foreach ($contextResult as $category => $result) {
323 323
 					$formattedTextResponse .= "\t- $category\n";
324
-					if($category !== 'EXCEPTION') {
324
+					if ($category !== 'EXCEPTION') {
325 325
 						foreach ($result as $key => $results) {
326 326
 							$formattedTextResponse .= "\t\t- $key\n";
327 327
 						}
@@ -364,27 +364,27 @@  discard block
 block discarded – undo
364 364
 
365 365
 		$isOpcacheProperlySetUp = true;
366 366
 
367
-		if(!$iniWrapper->getBool('opcache.enable')) {
367
+		if (!$iniWrapper->getBool('opcache.enable')) {
368 368
 			$isOpcacheProperlySetUp = false;
369 369
 		}
370 370
 
371
-		if(!$iniWrapper->getBool('opcache.save_comments')) {
371
+		if (!$iniWrapper->getBool('opcache.save_comments')) {
372 372
 			$isOpcacheProperlySetUp = false;
373 373
 		}
374 374
 
375
-		if(!$iniWrapper->getBool('opcache.enable_cli')) {
375
+		if (!$iniWrapper->getBool('opcache.enable_cli')) {
376 376
 			$isOpcacheProperlySetUp = false;
377 377
 		}
378 378
 
379
-		if($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
379
+		if ($iniWrapper->getNumeric('opcache.max_accelerated_files') < 10000) {
380 380
 			$isOpcacheProperlySetUp = false;
381 381
 		}
382 382
 
383
-		if($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
383
+		if ($iniWrapper->getNumeric('opcache.memory_consumption') < 128) {
384 384
 			$isOpcacheProperlySetUp = false;
385 385
 		}
386 386
 
387
-		if($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
387
+		if ($iniWrapper->getNumeric('opcache.interned_strings_buffer') < 8) {
388 388
 			$isOpcacheProperlySetUp = false;
389 389
 		}
390 390
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Wizard.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1104,7 +1104,7 @@
 block discarded – undo
1104 1104
 	}
1105 1105
 
1106 1106
 	/**
1107
-	 * @param array $reqs
1107
+	 * @param string[] $reqs
1108 1108
 	 * @return bool
1109 1109
 	 */
1110 1110
 	private function checkRequirements($reqs) {
Please login to merge, or discard this patch.
Indentation   +1318 added lines, -1318 removed lines patch added patch discarded remove patch
@@ -37,1324 +37,1324 @@
 block discarded – undo
37 37
 use OC\ServerNotAvailableException;
38 38
 
39 39
 class Wizard extends LDAPUtility {
40
-	/** @var \OCP\IL10N */
41
-	static protected $l;
42
-	protected $access;
43
-	protected $cr;
44
-	protected $configuration;
45
-	protected $result;
46
-	protected $resultCache = array();
47
-
48
-	const LRESULT_PROCESSED_OK = 2;
49
-	const LRESULT_PROCESSED_INVALID = 3;
50
-	const LRESULT_PROCESSED_SKIP = 4;
51
-
52
-	const LFILTER_LOGIN      = 2;
53
-	const LFILTER_USER_LIST  = 3;
54
-	const LFILTER_GROUP_LIST = 4;
55
-
56
-	const LFILTER_MODE_ASSISTED = 2;
57
-	const LFILTER_MODE_RAW = 1;
58
-
59
-	const LDAP_NW_TIMEOUT = 4;
60
-
61
-	/**
62
-	 * Constructor
63
-	 * @param Configuration $configuration an instance of Configuration
64
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
65
-	 * @param Access $access
66
-	 */
67
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
68
-		parent::__construct($ldap);
69
-		$this->configuration = $configuration;
70
-		if(is_null(Wizard::$l)) {
71
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
72
-		}
73
-		$this->access = $access;
74
-		$this->result = new WizardResult();
75
-	}
76
-
77
-	public function  __destruct() {
78
-		if($this->result->hasChanges()) {
79
-			$this->configuration->saveConfiguration();
80
-		}
81
-	}
82
-
83
-	/**
84
-	 * counts entries in the LDAP directory
85
-	 *
86
-	 * @param string $filter the LDAP search filter
87
-	 * @param string $type a string being either 'users' or 'groups';
88
-	 * @return bool|int
89
-	 * @throws \Exception
90
-	 */
91
-	public function countEntries($filter, $type) {
92
-		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
93
-		if($type === 'users') {
94
-			$reqs[] = 'ldapUserFilter';
95
-		}
96
-		if(!$this->checkRequirements($reqs)) {
97
-			throw new \Exception('Requirements not met', 400);
98
-		}
99
-
100
-		$attr = array('dn'); // default
101
-		$limit = 1001;
102
-		if($type === 'groups') {
103
-			$result =  $this->access->countGroups($filter, $attr, $limit);
104
-		} else if($type === 'users') {
105
-			$result = $this->access->countUsers($filter, $attr, $limit);
106
-		} else if ($type === 'objects') {
107
-			$result = $this->access->countObjects($limit);
108
-		} else {
109
-			throw new \Exception('internal error: invalid object type', 500);
110
-		}
111
-
112
-		return $result;
113
-	}
114
-
115
-	/**
116
-	 * formats the return value of a count operation to the string to be
117
-	 * inserted.
118
-	 *
119
-	 * @param bool|int $count
120
-	 * @return int|string
121
-	 */
122
-	private function formatCountResult($count) {
123
-		$formatted = ($count !== false) ? $count : 0;
124
-		if($formatted > 1000) {
125
-			$formatted = '> 1000';
126
-		}
127
-		return $formatted;
128
-	}
129
-
130
-	public function countGroups() {
131
-		$filter = $this->configuration->ldapGroupFilter;
132
-
133
-		if(empty($filter)) {
134
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
135
-			$this->result->addChange('ldap_group_count', $output);
136
-			return $this->result;
137
-		}
138
-
139
-		try {
140
-			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
141
-		} catch (\Exception $e) {
142
-			//400 can be ignored, 500 is forwarded
143
-			if($e->getCode() === 500) {
144
-				throw $e;
145
-			}
146
-			return false;
147
-		}
148
-		$output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
149
-		$this->result->addChange('ldap_group_count', $output);
150
-		return $this->result;
151
-	}
152
-
153
-	/**
154
-	 * @return WizardResult
155
-	 * @throws \Exception
156
-	 */
157
-	public function countUsers() {
158
-		$filter = $this->access->getFilterForUserCount();
159
-
160
-		$usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
161
-		$output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
162
-		$this->result->addChange('ldap_user_count', $output);
163
-		return $this->result;
164
-	}
165
-
166
-	/**
167
-	 * counts any objects in the currently set base dn
168
-	 *
169
-	 * @return WizardResult
170
-	 * @throws \Exception
171
-	 */
172
-	public function countInBaseDN() {
173
-		// we don't need to provide a filter in this case
174
-		$total = $this->countEntries(null, 'objects');
175
-		if($total === false) {
176
-			throw new \Exception('invalid results received');
177
-		}
178
-		$this->result->addChange('ldap_test_base', $total);
179
-		return $this->result;
180
-	}
181
-
182
-	/**
183
-	 * counts users with a specified attribute
184
-	 * @param string $attr
185
-	 * @param bool $existsCheck
186
-	 * @return int|bool
187
-	 */
188
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
189
-		if(!$this->checkRequirements(array('ldapHost',
190
-										   'ldapPort',
191
-										   'ldapBase',
192
-										   'ldapUserFilter',
193
-										   ))) {
194
-			return  false;
195
-		}
196
-
197
-		$filter = $this->access->combineFilterWithAnd(array(
198
-			$this->configuration->ldapUserFilter,
199
-			$attr . '=*'
200
-		));
201
-
202
-		$limit = ($existsCheck === false) ? null : 1;
203
-
204
-		return $this->access->countUsers($filter, array('dn'), $limit);
205
-	}
206
-
207
-	/**
208
-	 * detects the display name attribute. If a setting is already present that
209
-	 * returns at least one hit, the detection will be canceled.
210
-	 * @return WizardResult|bool
211
-	 * @throws \Exception
212
-	 */
213
-	public function detectUserDisplayNameAttribute() {
214
-		if(!$this->checkRequirements(array('ldapHost',
215
-										'ldapPort',
216
-										'ldapBase',
217
-										'ldapUserFilter',
218
-										))) {
219
-			return  false;
220
-		}
221
-
222
-		$attr = $this->configuration->ldapUserDisplayName;
223
-		if ($attr !== '' && $attr !== 'displayName') {
224
-			// most likely not the default value with upper case N,
225
-			// verify it still produces a result
226
-			$count = intval($this->countUsersWithAttribute($attr, true));
227
-			if($count > 0) {
228
-				//no change, but we sent it back to make sure the user interface
229
-				//is still correct, even if the ajax call was cancelled meanwhile
230
-				$this->result->addChange('ldap_display_name', $attr);
231
-				return $this->result;
232
-			}
233
-		}
234
-
235
-		// first attribute that has at least one result wins
236
-		$displayNameAttrs = array('displayname', 'cn');
237
-		foreach ($displayNameAttrs as $attr) {
238
-			$count = intval($this->countUsersWithAttribute($attr, true));
239
-
240
-			if($count > 0) {
241
-				$this->applyFind('ldap_display_name', $attr);
242
-				return $this->result;
243
-			}
244
-		};
245
-
246
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced ldap settings.'));
247
-	}
248
-
249
-	/**
250
-	 * detects the most often used email attribute for users applying to the
251
-	 * user list filter. If a setting is already present that returns at least
252
-	 * one hit, the detection will be canceled.
253
-	 * @return WizardResult|bool
254
-	 */
255
-	public function detectEmailAttribute() {
256
-		if(!$this->checkRequirements(array('ldapHost',
257
-										   'ldapPort',
258
-										   'ldapBase',
259
-										   'ldapUserFilter',
260
-										   ))) {
261
-			return  false;
262
-		}
263
-
264
-		$attr = $this->configuration->ldapEmailAttribute;
265
-		if ($attr !== '') {
266
-			$count = intval($this->countUsersWithAttribute($attr, true));
267
-			if($count > 0) {
268
-				return false;
269
-			}
270
-			$writeLog = true;
271
-		} else {
272
-			$writeLog = false;
273
-		}
274
-
275
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
276
-		$winner = '';
277
-		$maxUsers = 0;
278
-		foreach($emailAttributes as $attr) {
279
-			$count = $this->countUsersWithAttribute($attr);
280
-			if($count > $maxUsers) {
281
-				$maxUsers = $count;
282
-				$winner = $attr;
283
-			}
284
-		}
285
-
286
-		if($winner !== '') {
287
-			$this->applyFind('ldap_email_attr', $winner);
288
-			if($writeLog) {
289
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
290
-					'automatically been reset, because the original value ' .
291
-					'did not return any results.', \OCP\Util::INFO);
292
-			}
293
-		}
294
-
295
-		return $this->result;
296
-	}
297
-
298
-	/**
299
-	 * @return WizardResult
300
-	 * @throws \Exception
301
-	 */
302
-	public function determineAttributes() {
303
-		if(!$this->checkRequirements(array('ldapHost',
304
-										   'ldapPort',
305
-										   'ldapBase',
306
-										   'ldapUserFilter',
307
-										   ))) {
308
-			return  false;
309
-		}
310
-
311
-		$attributes = $this->getUserAttributes();
312
-
313
-		natcasesort($attributes);
314
-		$attributes = array_values($attributes);
315
-
316
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
317
-
318
-		$selected = $this->configuration->ldapLoginFilterAttributes;
319
-		if(is_array($selected) && !empty($selected)) {
320
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
321
-		}
322
-
323
-		return $this->result;
324
-	}
325
-
326
-	/**
327
-	 * detects the available LDAP attributes
328
-	 * @return array|false The instance's WizardResult instance
329
-	 * @throws \Exception
330
-	 */
331
-	private function getUserAttributes() {
332
-		if(!$this->checkRequirements(array('ldapHost',
333
-										   'ldapPort',
334
-										   'ldapBase',
335
-										   'ldapUserFilter',
336
-										   ))) {
337
-			return  false;
338
-		}
339
-		$cr = $this->getConnection();
340
-		if(!$cr) {
341
-			throw new \Exception('Could not connect to LDAP');
342
-		}
343
-
344
-		$base = $this->configuration->ldapBase[0];
345
-		$filter = $this->configuration->ldapUserFilter;
346
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
347
-		if(!$this->ldap->isResource($rr)) {
348
-			return false;
349
-		}
350
-		$er = $this->ldap->firstEntry($cr, $rr);
351
-		$attributes = $this->ldap->getAttributes($cr, $er);
352
-		$pureAttributes = array();
353
-		for($i = 0; $i < $attributes['count']; $i++) {
354
-			$pureAttributes[] = $attributes[$i];
355
-		}
356
-
357
-		return $pureAttributes;
358
-	}
359
-
360
-	/**
361
-	 * detects the available LDAP groups
362
-	 * @return WizardResult|false the instance's WizardResult instance
363
-	 */
364
-	public function determineGroupsForGroups() {
365
-		return $this->determineGroups('ldap_groupfilter_groups',
366
-									  'ldapGroupFilterGroups',
367
-									  false);
368
-	}
369
-
370
-	/**
371
-	 * detects the available LDAP groups
372
-	 * @return WizardResult|false the instance's WizardResult instance
373
-	 */
374
-	public function determineGroupsForUsers() {
375
-		return $this->determineGroups('ldap_userfilter_groups',
376
-									  'ldapUserFilterGroups');
377
-	}
378
-
379
-	/**
380
-	 * detects the available LDAP groups
381
-	 * @param string $dbKey
382
-	 * @param string $confKey
383
-	 * @param bool $testMemberOf
384
-	 * @return WizardResult|false the instance's WizardResult instance
385
-	 * @throws \Exception
386
-	 */
387
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
388
-		if(!$this->checkRequirements(array('ldapHost',
389
-										   'ldapPort',
390
-										   'ldapBase',
391
-										   ))) {
392
-			return  false;
393
-		}
394
-		$cr = $this->getConnection();
395
-		if(!$cr) {
396
-			throw new \Exception('Could not connect to LDAP');
397
-		}
398
-
399
-		$this->fetchGroups($dbKey, $confKey);
400
-
401
-		if($testMemberOf) {
402
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
403
-			$this->result->markChange();
404
-			if(!$this->configuration->hasMemberOfFilterSupport) {
405
-				throw new \Exception('memberOf is not supported by the server');
406
-			}
407
-		}
408
-
409
-		return $this->result;
410
-	}
411
-
412
-	/**
413
-	 * fetches all groups from LDAP and adds them to the result object
414
-	 *
415
-	 * @param string $dbKey
416
-	 * @param string $confKey
417
-	 * @return array $groupEntries
418
-	 * @throws \Exception
419
-	 */
420
-	public function fetchGroups($dbKey, $confKey) {
421
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
422
-
423
-		$filterParts = array();
424
-		foreach($obclasses as $obclass) {
425
-			$filterParts[] = 'objectclass='.$obclass;
426
-		}
427
-		//we filter for everything
428
-		//- that looks like a group and
429
-		//- has the group display name set
430
-		$filter = $this->access->combineFilterWithOr($filterParts);
431
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
432
-
433
-		$groupNames = array();
434
-		$groupEntries = array();
435
-		$limit = 400;
436
-		$offset = 0;
437
-		do {
438
-			// we need to request dn additionally here, otherwise memberOf
439
-			// detection will fail later
440
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
441
-			foreach($result as $item) {
442
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
443
-					// just in case - no issue known
444
-					continue;
445
-				}
446
-				$groupNames[] = $item['cn'][0];
447
-				$groupEntries[] = $item;
448
-			}
449
-			$offset += $limit;
450
-		} while ($this->access->hasMoreResults());
451
-
452
-		if(count($groupNames) > 0) {
453
-			natsort($groupNames);
454
-			$this->result->addOptions($dbKey, array_values($groupNames));
455
-		} else {
456
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
457
-		}
458
-
459
-		$setFeatures = $this->configuration->$confKey;
460
-		if(is_array($setFeatures) && !empty($setFeatures)) {
461
-			//something is already configured? pre-select it.
462
-			$this->result->addChange($dbKey, $setFeatures);
463
-		}
464
-		return $groupEntries;
465
-	}
466
-
467
-	public function determineGroupMemberAssoc() {
468
-		if(!$this->checkRequirements(array('ldapHost',
469
-										   'ldapPort',
470
-										   'ldapGroupFilter',
471
-										   ))) {
472
-			return  false;
473
-		}
474
-		$attribute = $this->detectGroupMemberAssoc();
475
-		if($attribute === false) {
476
-			return false;
477
-		}
478
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
479
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
480
-
481
-		return $this->result;
482
-	}
483
-
484
-	/**
485
-	 * Detects the available object classes
486
-	 * @return WizardResult|false the instance's WizardResult instance
487
-	 * @throws \Exception
488
-	 */
489
-	public function determineGroupObjectClasses() {
490
-		if(!$this->checkRequirements(array('ldapHost',
491
-										   'ldapPort',
492
-										   'ldapBase',
493
-										   ))) {
494
-			return  false;
495
-		}
496
-		$cr = $this->getConnection();
497
-		if(!$cr) {
498
-			throw new \Exception('Could not connect to LDAP');
499
-		}
500
-
501
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
502
-		$this->determineFeature($obclasses,
503
-								'objectclass',
504
-								'ldap_groupfilter_objectclass',
505
-								'ldapGroupFilterObjectclass',
506
-								false);
507
-
508
-		return $this->result;
509
-	}
510
-
511
-	/**
512
-	 * detects the available object classes
513
-	 * @return WizardResult
514
-	 * @throws \Exception
515
-	 */
516
-	public function determineUserObjectClasses() {
517
-		if(!$this->checkRequirements(array('ldapHost',
518
-										   'ldapPort',
519
-										   'ldapBase',
520
-										   ))) {
521
-			return  false;
522
-		}
523
-		$cr = $this->getConnection();
524
-		if(!$cr) {
525
-			throw new \Exception('Could not connect to LDAP');
526
-		}
527
-
528
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
529
-						   'user', 'posixAccount', '*');
530
-		$filter = $this->configuration->ldapUserFilter;
531
-		//if filter is empty, it is probably the first time the wizard is called
532
-		//then, apply suggestions.
533
-		$this->determineFeature($obclasses,
534
-								'objectclass',
535
-								'ldap_userfilter_objectclass',
536
-								'ldapUserFilterObjectclass',
537
-								empty($filter));
538
-
539
-		return $this->result;
540
-	}
541
-
542
-	/**
543
-	 * @return WizardResult|false
544
-	 * @throws \Exception
545
-	 */
546
-	public function getGroupFilter() {
547
-		if(!$this->checkRequirements(array('ldapHost',
548
-										   'ldapPort',
549
-										   'ldapBase',
550
-										   ))) {
551
-			return false;
552
-		}
553
-		//make sure the use display name is set
554
-		$displayName = $this->configuration->ldapGroupDisplayName;
555
-		if ($displayName === '') {
556
-			$d = $this->configuration->getDefaults();
557
-			$this->applyFind('ldap_group_display_name',
558
-							 $d['ldap_group_display_name']);
559
-		}
560
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
561
-
562
-		$this->applyFind('ldap_group_filter', $filter);
563
-		return $this->result;
564
-	}
565
-
566
-	/**
567
-	 * @return WizardResult|false
568
-	 * @throws \Exception
569
-	 */
570
-	public function getUserListFilter() {
571
-		if(!$this->checkRequirements(array('ldapHost',
572
-										   'ldapPort',
573
-										   'ldapBase',
574
-										   ))) {
575
-			return false;
576
-		}
577
-		//make sure the use display name is set
578
-		$displayName = $this->configuration->ldapUserDisplayName;
579
-		if ($displayName === '') {
580
-			$d = $this->configuration->getDefaults();
581
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
582
-		}
583
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
584
-		if(!$filter) {
585
-			throw new \Exception('Cannot create filter');
586
-		}
587
-
588
-		$this->applyFind('ldap_userlist_filter', $filter);
589
-		return $this->result;
590
-	}
591
-
592
-	/**
593
-	 * @return bool|WizardResult
594
-	 * @throws \Exception
595
-	 */
596
-	public function getUserLoginFilter() {
597
-		if(!$this->checkRequirements(array('ldapHost',
598
-										   'ldapPort',
599
-										   'ldapBase',
600
-										   'ldapUserFilter',
601
-										   ))) {
602
-			return false;
603
-		}
604
-
605
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
606
-		if(!$filter) {
607
-			throw new \Exception('Cannot create filter');
608
-		}
609
-
610
-		$this->applyFind('ldap_login_filter', $filter);
611
-		return $this->result;
612
-	}
613
-
614
-	/**
615
-	 * @return bool|WizardResult
616
-	 * @param string $loginName
617
-	 * @throws \Exception
618
-	 */
619
-	public function testLoginName($loginName) {
620
-		if(!$this->checkRequirements(array('ldapHost',
621
-			'ldapPort',
622
-			'ldapBase',
623
-			'ldapLoginFilter',
624
-		))) {
625
-			return false;
626
-		}
627
-
628
-		$cr = $this->access->connection->getConnectionResource();
629
-		if(!$this->ldap->isResource($cr)) {
630
-			throw new \Exception('connection error');
631
-		}
632
-
633
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
-			=== false) {
635
-			throw new \Exception('missing placeholder');
636
-		}
637
-
638
-		$users = $this->access->countUsersByLoginName($loginName);
639
-		if($this->ldap->errno($cr) !== 0) {
640
-			throw new \Exception($this->ldap->error($cr));
641
-		}
642
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
643
-		$this->result->addChange('ldap_test_loginname', $users);
644
-		$this->result->addChange('ldap_test_effective_filter', $filter);
645
-		return $this->result;
646
-	}
647
-
648
-	/**
649
-	 * Tries to determine the port, requires given Host, User DN and Password
650
-	 * @return WizardResult|false WizardResult on success, false otherwise
651
-	 * @throws \Exception
652
-	 */
653
-	public function guessPortAndTLS() {
654
-		if(!$this->checkRequirements(array('ldapHost',
655
-										   ))) {
656
-			return false;
657
-		}
658
-		$this->checkHost();
659
-		$portSettings = $this->getPortSettingsToTry();
660
-
661
-		if(!is_array($portSettings)) {
662
-			throw new \Exception(print_r($portSettings, true));
663
-		}
664
-
665
-		//proceed from the best configuration and return on first success
666
-		foreach($portSettings as $setting) {
667
-			$p = $setting['port'];
668
-			$t = $setting['tls'];
669
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
-			//connectAndBind may throw Exception, it needs to be catched by the
671
-			//callee of this method
672
-
673
-			try {
674
-				$settingsFound = $this->connectAndBind($p, $t);
675
-			} catch (\Exception $e) {
676
-				// any reply other than -1 (= cannot connect) is already okay,
677
-				// because then we found the server
678
-				// unavailable startTLS returns -11
679
-				if($e->getCode() > 0) {
680
-					$settingsFound = true;
681
-				} else {
682
-					throw $e;
683
-				}
684
-			}
685
-
686
-			if ($settingsFound === true) {
687
-				$config = array(
688
-					'ldapPort' => $p,
689
-					'ldapTLS' => intval($t)
690
-				);
691
-				$this->configuration->setConfiguration($config);
692
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
-				$this->result->addChange('ldap_port', $p);
694
-				return $this->result;
695
-			}
696
-		}
697
-
698
-		//custom port, undetected (we do not brute force)
699
-		return false;
700
-	}
701
-
702
-	/**
703
-	 * tries to determine a base dn from User DN or LDAP Host
704
-	 * @return WizardResult|false WizardResult on success, false otherwise
705
-	 */
706
-	public function guessBaseDN() {
707
-		if(!$this->checkRequirements(array('ldapHost',
708
-										   'ldapPort',
709
-										   ))) {
710
-			return false;
711
-		}
712
-
713
-		//check whether a DN is given in the agent name (99.9% of all cases)
714
-		$base = null;
715
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
716
-		if($i !== false) {
717
-			$base = substr($this->configuration->ldapAgentName, $i);
718
-			if($this->testBaseDN($base)) {
719
-				$this->applyFind('ldap_base', $base);
720
-				return $this->result;
721
-			}
722
-		}
723
-
724
-		//this did not help :(
725
-		//Let's see whether we can parse the Host URL and convert the domain to
726
-		//a base DN
727
-		$helper = new Helper(\OC::$server->getConfig());
728
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
729
-		if(!$domain) {
730
-			return false;
731
-		}
732
-
733
-		$dparts = explode('.', $domain);
734
-		while(count($dparts) > 0) {
735
-			$base2 = 'dc=' . implode(',dc=', $dparts);
736
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
737
-				$this->applyFind('ldap_base', $base2);
738
-				return $this->result;
739
-			}
740
-			array_shift($dparts);
741
-		}
742
-
743
-		return false;
744
-	}
745
-
746
-	/**
747
-	 * sets the found value for the configuration key in the WizardResult
748
-	 * as well as in the Configuration instance
749
-	 * @param string $key the configuration key
750
-	 * @param string $value the (detected) value
751
-	 *
752
-	 */
753
-	private function applyFind($key, $value) {
754
-		$this->result->addChange($key, $value);
755
-		$this->configuration->setConfiguration(array($key => $value));
756
-	}
757
-
758
-	/**
759
-	 * Checks, whether a port was entered in the Host configuration
760
-	 * field. In this case the port will be stripped off, but also stored as
761
-	 * setting.
762
-	 */
763
-	private function checkHost() {
764
-		$host = $this->configuration->ldapHost;
765
-		$hostInfo = parse_url($host);
766
-
767
-		//removes Port from Host
768
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
-			$port = $hostInfo['port'];
770
-			$host = str_replace(':'.$port, '', $host);
771
-			$this->applyFind('ldap_host', $host);
772
-			$this->applyFind('ldap_port', $port);
773
-		}
774
-	}
775
-
776
-	/**
777
-	 * tries to detect the group member association attribute which is
778
-	 * one of 'uniqueMember', 'memberUid', 'member'
779
-	 * @return string|false, string with the attribute name, false on error
780
-	 * @throws \Exception
781
-	 */
782
-	private function detectGroupMemberAssoc() {
783
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member');
784
-		$filter = $this->configuration->ldapGroupFilter;
785
-		if(empty($filter)) {
786
-			return false;
787
-		}
788
-		$cr = $this->getConnection();
789
-		if(!$cr) {
790
-			throw new \Exception('Could not connect to LDAP');
791
-		}
792
-		$base = $this->configuration->ldapBase[0];
793
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
794
-		if(!$this->ldap->isResource($rr)) {
795
-			return false;
796
-		}
797
-		$er = $this->ldap->firstEntry($cr, $rr);
798
-		while(is_resource($er)) {
799
-			$this->ldap->getDN($cr, $er);
800
-			$attrs = $this->ldap->getAttributes($cr, $er);
801
-			$result = array();
802
-			$possibleAttrsCount = count($possibleAttrs);
803
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
804
-				if(isset($attrs[$possibleAttrs[$i]])) {
805
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
806
-				}
807
-			}
808
-			if(!empty($result)) {
809
-				natsort($result);
810
-				return key($result);
811
-			}
812
-
813
-			$er = $this->ldap->nextEntry($cr, $er);
814
-		}
815
-
816
-		return false;
817
-	}
818
-
819
-	/**
820
-	 * Checks whether for a given BaseDN results will be returned
821
-	 * @param string $base the BaseDN to test
822
-	 * @return bool true on success, false otherwise
823
-	 * @throws \Exception
824
-	 */
825
-	private function testBaseDN($base) {
826
-		$cr = $this->getConnection();
827
-		if(!$cr) {
828
-			throw new \Exception('Could not connect to LDAP');
829
-		}
830
-
831
-		//base is there, let's validate it. If we search for anything, we should
832
-		//get a result set > 0 on a proper base
833
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
834
-		if(!$this->ldap->isResource($rr)) {
835
-			$errorNo  = $this->ldap->errno($cr);
836
-			$errorMsg = $this->ldap->error($cr);
837
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
838
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
839
-			return false;
840
-		}
841
-		$entries = $this->ldap->countEntries($cr, $rr);
842
-		return ($entries !== false) && ($entries > 0);
843
-	}
844
-
845
-	/**
846
-	 * Checks whether the server supports memberOf in LDAP Filter.
847
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
848
-	 * a configured objectClass. I.e. not necessarily for all available groups
849
-	 * memberOf does work.
850
-	 *
851
-	 * @return bool true if it does, false otherwise
852
-	 * @throws \Exception
853
-	 */
854
-	private function testMemberOf() {
855
-		$cr = $this->getConnection();
856
-		if(!$cr) {
857
-			throw new \Exception('Could not connect to LDAP');
858
-		}
859
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
860
-		if(is_int($result) &&  $result > 0) {
861
-			return true;
862
-		}
863
-		return false;
864
-	}
865
-
866
-	/**
867
-	 * creates an LDAP Filter from given configuration
868
-	 * @param integer $filterType int, for which use case the filter shall be created
869
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
870
-	 * self::LFILTER_GROUP_LIST
871
-	 * @return string|false string with the filter on success, false otherwise
872
-	 * @throws \Exception
873
-	 */
874
-	private function composeLdapFilter($filterType) {
875
-		$filter = '';
876
-		$parts = 0;
877
-		switch ($filterType) {
878
-			case self::LFILTER_USER_LIST:
879
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
880
-				//glue objectclasses
881
-				if(is_array($objcs) && count($objcs) > 0) {
882
-					$filter .= '(|';
883
-					foreach($objcs as $objc) {
884
-						$filter .= '(objectclass=' . $objc . ')';
885
-					}
886
-					$filter .= ')';
887
-					$parts++;
888
-				}
889
-				//glue group memberships
890
-				if($this->configuration->hasMemberOfFilterSupport) {
891
-					$cns = $this->configuration->ldapUserFilterGroups;
892
-					if(is_array($cns) && count($cns) > 0) {
893
-						$filter .= '(|';
894
-						$cr = $this->getConnection();
895
-						if(!$cr) {
896
-							throw new \Exception('Could not connect to LDAP');
897
-						}
898
-						$base = $this->configuration->ldapBase[0];
899
-						foreach($cns as $cn) {
900
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
901
-							if(!$this->ldap->isResource($rr)) {
902
-								continue;
903
-							}
904
-							$er = $this->ldap->firstEntry($cr, $rr);
905
-							$attrs = $this->ldap->getAttributes($cr, $er);
906
-							$dn = $this->ldap->getDN($cr, $er);
907
-							if ($dn == false || $dn === '') {
908
-								continue;
909
-							}
910
-							$filterPart = '(memberof=' . $dn . ')';
911
-							if(isset($attrs['primaryGroupToken'])) {
912
-								$pgt = $attrs['primaryGroupToken'][0];
913
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
914
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
915
-							}
916
-							$filter .= $filterPart;
917
-						}
918
-						$filter .= ')';
919
-					}
920
-					$parts++;
921
-				}
922
-				//wrap parts in AND condition
923
-				if($parts > 1) {
924
-					$filter = '(&' . $filter . ')';
925
-				}
926
-				if ($filter === '') {
927
-					$filter = '(objectclass=*)';
928
-				}
929
-				break;
930
-
931
-			case self::LFILTER_GROUP_LIST:
932
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
933
-				//glue objectclasses
934
-				if(is_array($objcs) && count($objcs) > 0) {
935
-					$filter .= '(|';
936
-					foreach($objcs as $objc) {
937
-						$filter .= '(objectclass=' . $objc . ')';
938
-					}
939
-					$filter .= ')';
940
-					$parts++;
941
-				}
942
-				//glue group memberships
943
-				$cns = $this->configuration->ldapGroupFilterGroups;
944
-				if(is_array($cns) && count($cns) > 0) {
945
-					$filter .= '(|';
946
-					foreach($cns as $cn) {
947
-						$filter .= '(cn=' . $cn . ')';
948
-					}
949
-					$filter .= ')';
950
-				}
951
-				$parts++;
952
-				//wrap parts in AND condition
953
-				if($parts > 1) {
954
-					$filter = '(&' . $filter . ')';
955
-				}
956
-				break;
957
-
958
-			case self::LFILTER_LOGIN:
959
-				$ulf = $this->configuration->ldapUserFilter;
960
-				$loginpart = '=%uid';
961
-				$filterUsername = '';
962
-				$userAttributes = $this->getUserAttributes();
963
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
964
-				$parts = 0;
965
-
966
-				if($this->configuration->ldapLoginFilterUsername === '1') {
967
-					$attr = '';
968
-					if(isset($userAttributes['uid'])) {
969
-						$attr = 'uid';
970
-					} else if(isset($userAttributes['samaccountname'])) {
971
-						$attr = 'samaccountname';
972
-					} else if(isset($userAttributes['cn'])) {
973
-						//fallback
974
-						$attr = 'cn';
975
-					}
976
-					if ($attr !== '') {
977
-						$filterUsername = '(' . $attr . $loginpart . ')';
978
-						$parts++;
979
-					}
980
-				}
981
-
982
-				$filterEmail = '';
983
-				if($this->configuration->ldapLoginFilterEmail === '1') {
984
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
985
-					$parts++;
986
-				}
987
-
988
-				$filterAttributes = '';
989
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
990
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
-					$filterAttributes = '(|';
992
-					foreach($attrsToFilter as $attribute) {
993
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
994
-					}
995
-					$filterAttributes .= ')';
996
-					$parts++;
997
-				}
998
-
999
-				$filterLogin = '';
1000
-				if($parts > 1) {
1001
-					$filterLogin = '(|';
1002
-				}
1003
-				$filterLogin .= $filterUsername;
1004
-				$filterLogin .= $filterEmail;
1005
-				$filterLogin .= $filterAttributes;
1006
-				if($parts > 1) {
1007
-					$filterLogin .= ')';
1008
-				}
1009
-
1010
-				$filter = '(&'.$ulf.$filterLogin.')';
1011
-				break;
1012
-		}
1013
-
1014
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1015
-
1016
-		return $filter;
1017
-	}
1018
-
1019
-	/**
1020
-	 * Connects and Binds to an LDAP Server
1021
-	 * @param int $port the port to connect with
1022
-	 * @param bool $tls whether startTLS is to be used
1023
-	 * @param bool $ncc
1024
-	 * @return bool
1025
-	 * @throws \Exception
1026
-	 */
1027
-	private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1028
-		if($ncc) {
1029
-			//No certificate check
1030
-			//FIXME: undo afterwards
1031
-			putenv('LDAPTLS_REQCERT=never');
1032
-		}
1033
-
1034
-		//connect, does not really trigger any server communication
1035
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1036
-		$host = $this->configuration->ldapHost;
1037
-		$hostInfo = parse_url($host);
1038
-		if(!$hostInfo) {
1039
-			throw new \Exception(self::$l->t('Invalid Host'));
1040
-		}
1041
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1042
-		$cr = $this->ldap->connect($host, $port);
1043
-		if(!is_resource($cr)) {
1044
-			throw new \Exception(self::$l->t('Invalid Host'));
1045
-		}
1046
-
1047
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Setting LDAP Options ', \OCP\Util::DEBUG);
1048
-		//set LDAP options
1049
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1050
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1051
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1052
-
1053
-		try {
1054
-			if($tls) {
1055
-				$isTlsWorking = @$this->ldap->startTls($cr);
1056
-				if(!$isTlsWorking) {
1057
-					return false;
1058
-				}
1059
-			}
1060
-
1061
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1062
-			//interesting part: do the bind!
1063
-			$login = $this->ldap->bind($cr,
1064
-				$this->configuration->ldapAgentName,
1065
-				$this->configuration->ldapAgentPassword
1066
-			);
1067
-			$errNo = $this->ldap->errno($cr);
1068
-			$error = ldap_error($cr);
1069
-			$this->ldap->unbind($cr);
1070
-		} catch(ServerNotAvailableException $e) {
1071
-			return false;
1072
-		}
1073
-
1074
-		if($login === true) {
1075
-			$this->ldap->unbind($cr);
1076
-			if($ncc) {
1077
-				throw new \Exception('Certificate cannot be validated.');
1078
-			}
1079
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1080
-			return true;
1081
-		}
1082
-
1083
-		if($errNo === -1 || ($errNo === 2 && $ncc)) {
1084
-			//host, port or TLS wrong
1085
-			return false;
1086
-		} else if ($errNo === 2) {
1087
-			return $this->connectAndBind($port, $tls, true);
1088
-		}
1089
-		throw new \Exception($error, $errNo);
1090
-	}
1091
-
1092
-	/**
1093
-	 * checks whether a valid combination of agent and password has been
1094
-	 * provided (either two values or nothing for anonymous connect)
1095
-	 * @return bool, true if everything is fine, false otherwise
1096
-	 */
1097
-	private function checkAgentRequirements() {
1098
-		$agent = $this->configuration->ldapAgentName;
1099
-		$pwd = $this->configuration->ldapAgentPassword;
1100
-
1101
-		return
1102
-			($agent !== '' && $pwd !== '')
1103
-			||  ($agent === '' && $pwd === '')
1104
-		;
1105
-	}
1106
-
1107
-	/**
1108
-	 * @param array $reqs
1109
-	 * @return bool
1110
-	 */
1111
-	private function checkRequirements($reqs) {
1112
-		$this->checkAgentRequirements();
1113
-		foreach($reqs as $option) {
1114
-			$value = $this->configuration->$option;
1115
-			if(empty($value)) {
1116
-				return false;
1117
-			}
1118
-		}
1119
-		return true;
1120
-	}
1121
-
1122
-	/**
1123
-	 * does a cumulativeSearch on LDAP to get different values of a
1124
-	 * specified attribute
1125
-	 * @param string[] $filters array, the filters that shall be used in the search
1126
-	 * @param string $attr the attribute of which a list of values shall be returned
1127
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1128
-	 * The lower, the faster
1129
-	 * @param string $maxF string. if not null, this variable will have the filter that
1130
-	 * yields most result entries
1131
-	 * @return array|false an array with the values on success, false otherwise
1132
-	 */
1133
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1134
-		$dnRead = array();
1135
-		$foundItems = array();
1136
-		$maxEntries = 0;
1137
-		if(!is_array($this->configuration->ldapBase)
1138
-		   || !isset($this->configuration->ldapBase[0])) {
1139
-			return false;
1140
-		}
1141
-		$base = $this->configuration->ldapBase[0];
1142
-		$cr = $this->getConnection();
1143
-		if(!$this->ldap->isResource($cr)) {
1144
-			return false;
1145
-		}
1146
-		$lastFilter = null;
1147
-		if(isset($filters[count($filters)-1])) {
1148
-			$lastFilter = $filters[count($filters)-1];
1149
-		}
1150
-		foreach($filters as $filter) {
1151
-			if($lastFilter === $filter && count($foundItems) > 0) {
1152
-				//skip when the filter is a wildcard and results were found
1153
-				continue;
1154
-			}
1155
-			// 20k limit for performance and reason
1156
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
-			if(!$this->ldap->isResource($rr)) {
1158
-				continue;
1159
-			}
1160
-			$entries = $this->ldap->countEntries($cr, $rr);
1161
-			$getEntryFunc = 'firstEntry';
1162
-			if(($entries !== false) && ($entries > 0)) {
1163
-				if(!is_null($maxF) && $entries > $maxEntries) {
1164
-					$maxEntries = $entries;
1165
-					$maxF = $filter;
1166
-				}
1167
-				$dnReadCount = 0;
1168
-				do {
1169
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1170
-					$getEntryFunc = 'nextEntry';
1171
-					if(!$this->ldap->isResource($entry)) {
1172
-						continue 2;
1173
-					}
1174
-					$rr = $entry; //will be expected by nextEntry next round
1175
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1176
-					$dn = $this->ldap->getDN($cr, $entry);
1177
-					if($dn === false || in_array($dn, $dnRead)) {
1178
-						continue;
1179
-					}
1180
-					$newItems = array();
1181
-					$state = $this->getAttributeValuesFromEntry($attributes,
1182
-																$attr,
1183
-																$newItems);
1184
-					$dnReadCount++;
1185
-					$foundItems = array_merge($foundItems, $newItems);
1186
-					$this->resultCache[$dn][$attr] = $newItems;
1187
-					$dnRead[] = $dn;
1188
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1189
-						|| $this->ldap->isResource($entry))
1190
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191
-			}
1192
-		}
1193
-
1194
-		return array_unique($foundItems);
1195
-	}
1196
-
1197
-	/**
1198
-	 * determines if and which $attr are available on the LDAP server
1199
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1200
-	 * @param string $attr the attribute to look for
1201
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1202
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1203
-	 * Configuration class
1204
-	 * @param bool $po whether the objectClass with most result entries
1205
-	 * shall be pre-selected via the result
1206
-	 * @return array|false list of found items.
1207
-	 * @throws \Exception
1208
-	 */
1209
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210
-		$cr = $this->getConnection();
1211
-		if(!$cr) {
1212
-			throw new \Exception('Could not connect to LDAP');
1213
-		}
1214
-		$p = 'objectclass=';
1215
-		foreach($objectclasses as $key => $value) {
1216
-			$objectclasses[$key] = $p.$value;
1217
-		}
1218
-		$maxEntryObjC = '';
1219
-
1220
-		//how deep to dig?
1221
-		//When looking for objectclasses, testing few entries is sufficient,
1222
-		$dig = 3;
1223
-
1224
-		$availableFeatures =
1225
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226
-											   $dig, $maxEntryObjC);
1227
-		if(is_array($availableFeatures)
1228
-		   && count($availableFeatures) > 0) {
1229
-			natcasesort($availableFeatures);
1230
-			//natcasesort keeps indices, but we must get rid of them for proper
1231
-			//sorting in the web UI. Therefore: array_values
1232
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1233
-		} else {
1234
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1235
-		}
1236
-
1237
-		$setFeatures = $this->configuration->$confkey;
1238
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1239
-			//something is already configured? pre-select it.
1240
-			$this->result->addChange($dbkey, $setFeatures);
1241
-		} else if ($po && $maxEntryObjC !== '') {
1242
-			//pre-select objectclass with most result entries
1243
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1244
-			$this->applyFind($dbkey, $maxEntryObjC);
1245
-			$this->result->addChange($dbkey, $maxEntryObjC);
1246
-		}
1247
-
1248
-		return $availableFeatures;
1249
-	}
1250
-
1251
-	/**
1252
-	 * appends a list of values fr
1253
-	 * @param resource $result the return value from ldap_get_attributes
1254
-	 * @param string $attribute the attribute values to look for
1255
-	 * @param array &$known new values will be appended here
1256
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1257
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258
-	 */
1259
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
-		if(!is_array($result)
1261
-		   || !isset($result['count'])
1262
-		   || !$result['count'] > 0) {
1263
-			return self::LRESULT_PROCESSED_INVALID;
1264
-		}
1265
-
1266
-		// strtolower on all keys for proper comparison
1267
-		$result = \OCP\Util::mb_array_change_key_case($result);
1268
-		$attribute = strtolower($attribute);
1269
-		if(isset($result[$attribute])) {
1270
-			foreach($result[$attribute] as $key => $val) {
1271
-				if($key === 'count') {
1272
-					continue;
1273
-				}
1274
-				if(!in_array($val, $known)) {
1275
-					$known[] = $val;
1276
-				}
1277
-			}
1278
-			return self::LRESULT_PROCESSED_OK;
1279
-		} else {
1280
-			return self::LRESULT_PROCESSED_SKIP;
1281
-		}
1282
-	}
1283
-
1284
-	/**
1285
-	 * @return bool|mixed
1286
-	 */
1287
-	private function getConnection() {
1288
-		if(!is_null($this->cr)) {
1289
-			return $this->cr;
1290
-		}
1291
-
1292
-		$cr = $this->ldap->connect(
1293
-			$this->configuration->ldapHost,
1294
-			$this->configuration->ldapPort
1295
-		);
1296
-
1297
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
-		if($this->configuration->ldapTLS === 1) {
1301
-			$this->ldap->startTls($cr);
1302
-		}
1303
-
1304
-		$lo = @$this->ldap->bind($cr,
1305
-								 $this->configuration->ldapAgentName,
1306
-								 $this->configuration->ldapAgentPassword);
1307
-		if($lo === true) {
1308
-			$this->$cr = $cr;
1309
-			return $cr;
1310
-		}
1311
-
1312
-		return false;
1313
-	}
1314
-
1315
-	/**
1316
-	 * @return array
1317
-	 */
1318
-	private function getDefaultLdapPortSettings() {
1319
-		static $settings = array(
1320
-								array('port' => 7636, 'tls' => false),
1321
-								array('port' =>  636, 'tls' => false),
1322
-								array('port' => 7389, 'tls' => true),
1323
-								array('port' =>  389, 'tls' => true),
1324
-								array('port' => 7389, 'tls' => false),
1325
-								array('port' =>  389, 'tls' => false),
1326
-						  );
1327
-		return $settings;
1328
-	}
1329
-
1330
-	/**
1331
-	 * @return array
1332
-	 */
1333
-	private function getPortSettingsToTry() {
1334
-		//389 ← LDAP / Unencrypted or StartTLS
1335
-		//636 ← LDAPS / SSL
1336
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1337
-		$host = $this->configuration->ldapHost;
1338
-		$port = intval($this->configuration->ldapPort);
1339
-		$portSettings = array();
1340
-
1341
-		//In case the port is already provided, we will check this first
1342
-		if($port > 0) {
1343
-			$hostInfo = parse_url($host);
1344
-			if(!(is_array($hostInfo)
1345
-				&& isset($hostInfo['scheme'])
1346
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347
-				$portSettings[] = array('port' => $port, 'tls' => true);
1348
-			}
1349
-			$portSettings[] =array('port' => $port, 'tls' => false);
1350
-		}
1351
-
1352
-		//default ports
1353
-		$portSettings = array_merge($portSettings,
1354
-		                            $this->getDefaultLdapPortSettings());
1355
-
1356
-		return $portSettings;
1357
-	}
40
+    /** @var \OCP\IL10N */
41
+    static protected $l;
42
+    protected $access;
43
+    protected $cr;
44
+    protected $configuration;
45
+    protected $result;
46
+    protected $resultCache = array();
47
+
48
+    const LRESULT_PROCESSED_OK = 2;
49
+    const LRESULT_PROCESSED_INVALID = 3;
50
+    const LRESULT_PROCESSED_SKIP = 4;
51
+
52
+    const LFILTER_LOGIN      = 2;
53
+    const LFILTER_USER_LIST  = 3;
54
+    const LFILTER_GROUP_LIST = 4;
55
+
56
+    const LFILTER_MODE_ASSISTED = 2;
57
+    const LFILTER_MODE_RAW = 1;
58
+
59
+    const LDAP_NW_TIMEOUT = 4;
60
+
61
+    /**
62
+     * Constructor
63
+     * @param Configuration $configuration an instance of Configuration
64
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
65
+     * @param Access $access
66
+     */
67
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
68
+        parent::__construct($ldap);
69
+        $this->configuration = $configuration;
70
+        if(is_null(Wizard::$l)) {
71
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
72
+        }
73
+        $this->access = $access;
74
+        $this->result = new WizardResult();
75
+    }
76
+
77
+    public function  __destruct() {
78
+        if($this->result->hasChanges()) {
79
+            $this->configuration->saveConfiguration();
80
+        }
81
+    }
82
+
83
+    /**
84
+     * counts entries in the LDAP directory
85
+     *
86
+     * @param string $filter the LDAP search filter
87
+     * @param string $type a string being either 'users' or 'groups';
88
+     * @return bool|int
89
+     * @throws \Exception
90
+     */
91
+    public function countEntries($filter, $type) {
92
+        $reqs = array('ldapHost', 'ldapPort', 'ldapBase');
93
+        if($type === 'users') {
94
+            $reqs[] = 'ldapUserFilter';
95
+        }
96
+        if(!$this->checkRequirements($reqs)) {
97
+            throw new \Exception('Requirements not met', 400);
98
+        }
99
+
100
+        $attr = array('dn'); // default
101
+        $limit = 1001;
102
+        if($type === 'groups') {
103
+            $result =  $this->access->countGroups($filter, $attr, $limit);
104
+        } else if($type === 'users') {
105
+            $result = $this->access->countUsers($filter, $attr, $limit);
106
+        } else if ($type === 'objects') {
107
+            $result = $this->access->countObjects($limit);
108
+        } else {
109
+            throw new \Exception('internal error: invalid object type', 500);
110
+        }
111
+
112
+        return $result;
113
+    }
114
+
115
+    /**
116
+     * formats the return value of a count operation to the string to be
117
+     * inserted.
118
+     *
119
+     * @param bool|int $count
120
+     * @return int|string
121
+     */
122
+    private function formatCountResult($count) {
123
+        $formatted = ($count !== false) ? $count : 0;
124
+        if($formatted > 1000) {
125
+            $formatted = '> 1000';
126
+        }
127
+        return $formatted;
128
+    }
129
+
130
+    public function countGroups() {
131
+        $filter = $this->configuration->ldapGroupFilter;
132
+
133
+        if(empty($filter)) {
134
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
135
+            $this->result->addChange('ldap_group_count', $output);
136
+            return $this->result;
137
+        }
138
+
139
+        try {
140
+            $groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
141
+        } catch (\Exception $e) {
142
+            //400 can be ignored, 500 is forwarded
143
+            if($e->getCode() === 500) {
144
+                throw $e;
145
+            }
146
+            return false;
147
+        }
148
+        $output = self::$l->n('%s group found', '%s groups found', $groupsTotal, array($groupsTotal));
149
+        $this->result->addChange('ldap_group_count', $output);
150
+        return $this->result;
151
+    }
152
+
153
+    /**
154
+     * @return WizardResult
155
+     * @throws \Exception
156
+     */
157
+    public function countUsers() {
158
+        $filter = $this->access->getFilterForUserCount();
159
+
160
+        $usersTotal = $this->formatCountResult($this->countEntries($filter, 'users'));
161
+        $output = self::$l->n('%s user found', '%s users found', $usersTotal, array($usersTotal));
162
+        $this->result->addChange('ldap_user_count', $output);
163
+        return $this->result;
164
+    }
165
+
166
+    /**
167
+     * counts any objects in the currently set base dn
168
+     *
169
+     * @return WizardResult
170
+     * @throws \Exception
171
+     */
172
+    public function countInBaseDN() {
173
+        // we don't need to provide a filter in this case
174
+        $total = $this->countEntries(null, 'objects');
175
+        if($total === false) {
176
+            throw new \Exception('invalid results received');
177
+        }
178
+        $this->result->addChange('ldap_test_base', $total);
179
+        return $this->result;
180
+    }
181
+
182
+    /**
183
+     * counts users with a specified attribute
184
+     * @param string $attr
185
+     * @param bool $existsCheck
186
+     * @return int|bool
187
+     */
188
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
189
+        if(!$this->checkRequirements(array('ldapHost',
190
+                                            'ldapPort',
191
+                                            'ldapBase',
192
+                                            'ldapUserFilter',
193
+                                            ))) {
194
+            return  false;
195
+        }
196
+
197
+        $filter = $this->access->combineFilterWithAnd(array(
198
+            $this->configuration->ldapUserFilter,
199
+            $attr . '=*'
200
+        ));
201
+
202
+        $limit = ($existsCheck === false) ? null : 1;
203
+
204
+        return $this->access->countUsers($filter, array('dn'), $limit);
205
+    }
206
+
207
+    /**
208
+     * detects the display name attribute. If a setting is already present that
209
+     * returns at least one hit, the detection will be canceled.
210
+     * @return WizardResult|bool
211
+     * @throws \Exception
212
+     */
213
+    public function detectUserDisplayNameAttribute() {
214
+        if(!$this->checkRequirements(array('ldapHost',
215
+                                        'ldapPort',
216
+                                        'ldapBase',
217
+                                        'ldapUserFilter',
218
+                                        ))) {
219
+            return  false;
220
+        }
221
+
222
+        $attr = $this->configuration->ldapUserDisplayName;
223
+        if ($attr !== '' && $attr !== 'displayName') {
224
+            // most likely not the default value with upper case N,
225
+            // verify it still produces a result
226
+            $count = intval($this->countUsersWithAttribute($attr, true));
227
+            if($count > 0) {
228
+                //no change, but we sent it back to make sure the user interface
229
+                //is still correct, even if the ajax call was cancelled meanwhile
230
+                $this->result->addChange('ldap_display_name', $attr);
231
+                return $this->result;
232
+            }
233
+        }
234
+
235
+        // first attribute that has at least one result wins
236
+        $displayNameAttrs = array('displayname', 'cn');
237
+        foreach ($displayNameAttrs as $attr) {
238
+            $count = intval($this->countUsersWithAttribute($attr, true));
239
+
240
+            if($count > 0) {
241
+                $this->applyFind('ldap_display_name', $attr);
242
+                return $this->result;
243
+            }
244
+        };
245
+
246
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced ldap settings.'));
247
+    }
248
+
249
+    /**
250
+     * detects the most often used email attribute for users applying to the
251
+     * user list filter. If a setting is already present that returns at least
252
+     * one hit, the detection will be canceled.
253
+     * @return WizardResult|bool
254
+     */
255
+    public function detectEmailAttribute() {
256
+        if(!$this->checkRequirements(array('ldapHost',
257
+                                            'ldapPort',
258
+                                            'ldapBase',
259
+                                            'ldapUserFilter',
260
+                                            ))) {
261
+            return  false;
262
+        }
263
+
264
+        $attr = $this->configuration->ldapEmailAttribute;
265
+        if ($attr !== '') {
266
+            $count = intval($this->countUsersWithAttribute($attr, true));
267
+            if($count > 0) {
268
+                return false;
269
+            }
270
+            $writeLog = true;
271
+        } else {
272
+            $writeLog = false;
273
+        }
274
+
275
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
276
+        $winner = '';
277
+        $maxUsers = 0;
278
+        foreach($emailAttributes as $attr) {
279
+            $count = $this->countUsersWithAttribute($attr);
280
+            if($count > $maxUsers) {
281
+                $maxUsers = $count;
282
+                $winner = $attr;
283
+            }
284
+        }
285
+
286
+        if($winner !== '') {
287
+            $this->applyFind('ldap_email_attr', $winner);
288
+            if($writeLog) {
289
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
290
+                    'automatically been reset, because the original value ' .
291
+                    'did not return any results.', \OCP\Util::INFO);
292
+            }
293
+        }
294
+
295
+        return $this->result;
296
+    }
297
+
298
+    /**
299
+     * @return WizardResult
300
+     * @throws \Exception
301
+     */
302
+    public function determineAttributes() {
303
+        if(!$this->checkRequirements(array('ldapHost',
304
+                                            'ldapPort',
305
+                                            'ldapBase',
306
+                                            'ldapUserFilter',
307
+                                            ))) {
308
+            return  false;
309
+        }
310
+
311
+        $attributes = $this->getUserAttributes();
312
+
313
+        natcasesort($attributes);
314
+        $attributes = array_values($attributes);
315
+
316
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
317
+
318
+        $selected = $this->configuration->ldapLoginFilterAttributes;
319
+        if(is_array($selected) && !empty($selected)) {
320
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
321
+        }
322
+
323
+        return $this->result;
324
+    }
325
+
326
+    /**
327
+     * detects the available LDAP attributes
328
+     * @return array|false The instance's WizardResult instance
329
+     * @throws \Exception
330
+     */
331
+    private function getUserAttributes() {
332
+        if(!$this->checkRequirements(array('ldapHost',
333
+                                            'ldapPort',
334
+                                            'ldapBase',
335
+                                            'ldapUserFilter',
336
+                                            ))) {
337
+            return  false;
338
+        }
339
+        $cr = $this->getConnection();
340
+        if(!$cr) {
341
+            throw new \Exception('Could not connect to LDAP');
342
+        }
343
+
344
+        $base = $this->configuration->ldapBase[0];
345
+        $filter = $this->configuration->ldapUserFilter;
346
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
347
+        if(!$this->ldap->isResource($rr)) {
348
+            return false;
349
+        }
350
+        $er = $this->ldap->firstEntry($cr, $rr);
351
+        $attributes = $this->ldap->getAttributes($cr, $er);
352
+        $pureAttributes = array();
353
+        for($i = 0; $i < $attributes['count']; $i++) {
354
+            $pureAttributes[] = $attributes[$i];
355
+        }
356
+
357
+        return $pureAttributes;
358
+    }
359
+
360
+    /**
361
+     * detects the available LDAP groups
362
+     * @return WizardResult|false the instance's WizardResult instance
363
+     */
364
+    public function determineGroupsForGroups() {
365
+        return $this->determineGroups('ldap_groupfilter_groups',
366
+                                        'ldapGroupFilterGroups',
367
+                                        false);
368
+    }
369
+
370
+    /**
371
+     * detects the available LDAP groups
372
+     * @return WizardResult|false the instance's WizardResult instance
373
+     */
374
+    public function determineGroupsForUsers() {
375
+        return $this->determineGroups('ldap_userfilter_groups',
376
+                                        'ldapUserFilterGroups');
377
+    }
378
+
379
+    /**
380
+     * detects the available LDAP groups
381
+     * @param string $dbKey
382
+     * @param string $confKey
383
+     * @param bool $testMemberOf
384
+     * @return WizardResult|false the instance's WizardResult instance
385
+     * @throws \Exception
386
+     */
387
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
388
+        if(!$this->checkRequirements(array('ldapHost',
389
+                                            'ldapPort',
390
+                                            'ldapBase',
391
+                                            ))) {
392
+            return  false;
393
+        }
394
+        $cr = $this->getConnection();
395
+        if(!$cr) {
396
+            throw new \Exception('Could not connect to LDAP');
397
+        }
398
+
399
+        $this->fetchGroups($dbKey, $confKey);
400
+
401
+        if($testMemberOf) {
402
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
403
+            $this->result->markChange();
404
+            if(!$this->configuration->hasMemberOfFilterSupport) {
405
+                throw new \Exception('memberOf is not supported by the server');
406
+            }
407
+        }
408
+
409
+        return $this->result;
410
+    }
411
+
412
+    /**
413
+     * fetches all groups from LDAP and adds them to the result object
414
+     *
415
+     * @param string $dbKey
416
+     * @param string $confKey
417
+     * @return array $groupEntries
418
+     * @throws \Exception
419
+     */
420
+    public function fetchGroups($dbKey, $confKey) {
421
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
422
+
423
+        $filterParts = array();
424
+        foreach($obclasses as $obclass) {
425
+            $filterParts[] = 'objectclass='.$obclass;
426
+        }
427
+        //we filter for everything
428
+        //- that looks like a group and
429
+        //- has the group display name set
430
+        $filter = $this->access->combineFilterWithOr($filterParts);
431
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
432
+
433
+        $groupNames = array();
434
+        $groupEntries = array();
435
+        $limit = 400;
436
+        $offset = 0;
437
+        do {
438
+            // we need to request dn additionally here, otherwise memberOf
439
+            // detection will fail later
440
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
441
+            foreach($result as $item) {
442
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
443
+                    // just in case - no issue known
444
+                    continue;
445
+                }
446
+                $groupNames[] = $item['cn'][0];
447
+                $groupEntries[] = $item;
448
+            }
449
+            $offset += $limit;
450
+        } while ($this->access->hasMoreResults());
451
+
452
+        if(count($groupNames) > 0) {
453
+            natsort($groupNames);
454
+            $this->result->addOptions($dbKey, array_values($groupNames));
455
+        } else {
456
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
457
+        }
458
+
459
+        $setFeatures = $this->configuration->$confKey;
460
+        if(is_array($setFeatures) && !empty($setFeatures)) {
461
+            //something is already configured? pre-select it.
462
+            $this->result->addChange($dbKey, $setFeatures);
463
+        }
464
+        return $groupEntries;
465
+    }
466
+
467
+    public function determineGroupMemberAssoc() {
468
+        if(!$this->checkRequirements(array('ldapHost',
469
+                                            'ldapPort',
470
+                                            'ldapGroupFilter',
471
+                                            ))) {
472
+            return  false;
473
+        }
474
+        $attribute = $this->detectGroupMemberAssoc();
475
+        if($attribute === false) {
476
+            return false;
477
+        }
478
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
479
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
480
+
481
+        return $this->result;
482
+    }
483
+
484
+    /**
485
+     * Detects the available object classes
486
+     * @return WizardResult|false the instance's WizardResult instance
487
+     * @throws \Exception
488
+     */
489
+    public function determineGroupObjectClasses() {
490
+        if(!$this->checkRequirements(array('ldapHost',
491
+                                            'ldapPort',
492
+                                            'ldapBase',
493
+                                            ))) {
494
+            return  false;
495
+        }
496
+        $cr = $this->getConnection();
497
+        if(!$cr) {
498
+            throw new \Exception('Could not connect to LDAP');
499
+        }
500
+
501
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
502
+        $this->determineFeature($obclasses,
503
+                                'objectclass',
504
+                                'ldap_groupfilter_objectclass',
505
+                                'ldapGroupFilterObjectclass',
506
+                                false);
507
+
508
+        return $this->result;
509
+    }
510
+
511
+    /**
512
+     * detects the available object classes
513
+     * @return WizardResult
514
+     * @throws \Exception
515
+     */
516
+    public function determineUserObjectClasses() {
517
+        if(!$this->checkRequirements(array('ldapHost',
518
+                                            'ldapPort',
519
+                                            'ldapBase',
520
+                                            ))) {
521
+            return  false;
522
+        }
523
+        $cr = $this->getConnection();
524
+        if(!$cr) {
525
+            throw new \Exception('Could not connect to LDAP');
526
+        }
527
+
528
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
529
+                            'user', 'posixAccount', '*');
530
+        $filter = $this->configuration->ldapUserFilter;
531
+        //if filter is empty, it is probably the first time the wizard is called
532
+        //then, apply suggestions.
533
+        $this->determineFeature($obclasses,
534
+                                'objectclass',
535
+                                'ldap_userfilter_objectclass',
536
+                                'ldapUserFilterObjectclass',
537
+                                empty($filter));
538
+
539
+        return $this->result;
540
+    }
541
+
542
+    /**
543
+     * @return WizardResult|false
544
+     * @throws \Exception
545
+     */
546
+    public function getGroupFilter() {
547
+        if(!$this->checkRequirements(array('ldapHost',
548
+                                            'ldapPort',
549
+                                            'ldapBase',
550
+                                            ))) {
551
+            return false;
552
+        }
553
+        //make sure the use display name is set
554
+        $displayName = $this->configuration->ldapGroupDisplayName;
555
+        if ($displayName === '') {
556
+            $d = $this->configuration->getDefaults();
557
+            $this->applyFind('ldap_group_display_name',
558
+                                $d['ldap_group_display_name']);
559
+        }
560
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
561
+
562
+        $this->applyFind('ldap_group_filter', $filter);
563
+        return $this->result;
564
+    }
565
+
566
+    /**
567
+     * @return WizardResult|false
568
+     * @throws \Exception
569
+     */
570
+    public function getUserListFilter() {
571
+        if(!$this->checkRequirements(array('ldapHost',
572
+                                            'ldapPort',
573
+                                            'ldapBase',
574
+                                            ))) {
575
+            return false;
576
+        }
577
+        //make sure the use display name is set
578
+        $displayName = $this->configuration->ldapUserDisplayName;
579
+        if ($displayName === '') {
580
+            $d = $this->configuration->getDefaults();
581
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
582
+        }
583
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
584
+        if(!$filter) {
585
+            throw new \Exception('Cannot create filter');
586
+        }
587
+
588
+        $this->applyFind('ldap_userlist_filter', $filter);
589
+        return $this->result;
590
+    }
591
+
592
+    /**
593
+     * @return bool|WizardResult
594
+     * @throws \Exception
595
+     */
596
+    public function getUserLoginFilter() {
597
+        if(!$this->checkRequirements(array('ldapHost',
598
+                                            'ldapPort',
599
+                                            'ldapBase',
600
+                                            'ldapUserFilter',
601
+                                            ))) {
602
+            return false;
603
+        }
604
+
605
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
606
+        if(!$filter) {
607
+            throw new \Exception('Cannot create filter');
608
+        }
609
+
610
+        $this->applyFind('ldap_login_filter', $filter);
611
+        return $this->result;
612
+    }
613
+
614
+    /**
615
+     * @return bool|WizardResult
616
+     * @param string $loginName
617
+     * @throws \Exception
618
+     */
619
+    public function testLoginName($loginName) {
620
+        if(!$this->checkRequirements(array('ldapHost',
621
+            'ldapPort',
622
+            'ldapBase',
623
+            'ldapLoginFilter',
624
+        ))) {
625
+            return false;
626
+        }
627
+
628
+        $cr = $this->access->connection->getConnectionResource();
629
+        if(!$this->ldap->isResource($cr)) {
630
+            throw new \Exception('connection error');
631
+        }
632
+
633
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634
+            === false) {
635
+            throw new \Exception('missing placeholder');
636
+        }
637
+
638
+        $users = $this->access->countUsersByLoginName($loginName);
639
+        if($this->ldap->errno($cr) !== 0) {
640
+            throw new \Exception($this->ldap->error($cr));
641
+        }
642
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
643
+        $this->result->addChange('ldap_test_loginname', $users);
644
+        $this->result->addChange('ldap_test_effective_filter', $filter);
645
+        return $this->result;
646
+    }
647
+
648
+    /**
649
+     * Tries to determine the port, requires given Host, User DN and Password
650
+     * @return WizardResult|false WizardResult on success, false otherwise
651
+     * @throws \Exception
652
+     */
653
+    public function guessPortAndTLS() {
654
+        if(!$this->checkRequirements(array('ldapHost',
655
+                                            ))) {
656
+            return false;
657
+        }
658
+        $this->checkHost();
659
+        $portSettings = $this->getPortSettingsToTry();
660
+
661
+        if(!is_array($portSettings)) {
662
+            throw new \Exception(print_r($portSettings, true));
663
+        }
664
+
665
+        //proceed from the best configuration and return on first success
666
+        foreach($portSettings as $setting) {
667
+            $p = $setting['port'];
668
+            $t = $setting['tls'];
669
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
670
+            //connectAndBind may throw Exception, it needs to be catched by the
671
+            //callee of this method
672
+
673
+            try {
674
+                $settingsFound = $this->connectAndBind($p, $t);
675
+            } catch (\Exception $e) {
676
+                // any reply other than -1 (= cannot connect) is already okay,
677
+                // because then we found the server
678
+                // unavailable startTLS returns -11
679
+                if($e->getCode() > 0) {
680
+                    $settingsFound = true;
681
+                } else {
682
+                    throw $e;
683
+                }
684
+            }
685
+
686
+            if ($settingsFound === true) {
687
+                $config = array(
688
+                    'ldapPort' => $p,
689
+                    'ldapTLS' => intval($t)
690
+                );
691
+                $this->configuration->setConfiguration($config);
692
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
693
+                $this->result->addChange('ldap_port', $p);
694
+                return $this->result;
695
+            }
696
+        }
697
+
698
+        //custom port, undetected (we do not brute force)
699
+        return false;
700
+    }
701
+
702
+    /**
703
+     * tries to determine a base dn from User DN or LDAP Host
704
+     * @return WizardResult|false WizardResult on success, false otherwise
705
+     */
706
+    public function guessBaseDN() {
707
+        if(!$this->checkRequirements(array('ldapHost',
708
+                                            'ldapPort',
709
+                                            ))) {
710
+            return false;
711
+        }
712
+
713
+        //check whether a DN is given in the agent name (99.9% of all cases)
714
+        $base = null;
715
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
716
+        if($i !== false) {
717
+            $base = substr($this->configuration->ldapAgentName, $i);
718
+            if($this->testBaseDN($base)) {
719
+                $this->applyFind('ldap_base', $base);
720
+                return $this->result;
721
+            }
722
+        }
723
+
724
+        //this did not help :(
725
+        //Let's see whether we can parse the Host URL and convert the domain to
726
+        //a base DN
727
+        $helper = new Helper(\OC::$server->getConfig());
728
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
729
+        if(!$domain) {
730
+            return false;
731
+        }
732
+
733
+        $dparts = explode('.', $domain);
734
+        while(count($dparts) > 0) {
735
+            $base2 = 'dc=' . implode(',dc=', $dparts);
736
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
737
+                $this->applyFind('ldap_base', $base2);
738
+                return $this->result;
739
+            }
740
+            array_shift($dparts);
741
+        }
742
+
743
+        return false;
744
+    }
745
+
746
+    /**
747
+     * sets the found value for the configuration key in the WizardResult
748
+     * as well as in the Configuration instance
749
+     * @param string $key the configuration key
750
+     * @param string $value the (detected) value
751
+     *
752
+     */
753
+    private function applyFind($key, $value) {
754
+        $this->result->addChange($key, $value);
755
+        $this->configuration->setConfiguration(array($key => $value));
756
+    }
757
+
758
+    /**
759
+     * Checks, whether a port was entered in the Host configuration
760
+     * field. In this case the port will be stripped off, but also stored as
761
+     * setting.
762
+     */
763
+    private function checkHost() {
764
+        $host = $this->configuration->ldapHost;
765
+        $hostInfo = parse_url($host);
766
+
767
+        //removes Port from Host
768
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
769
+            $port = $hostInfo['port'];
770
+            $host = str_replace(':'.$port, '', $host);
771
+            $this->applyFind('ldap_host', $host);
772
+            $this->applyFind('ldap_port', $port);
773
+        }
774
+    }
775
+
776
+    /**
777
+     * tries to detect the group member association attribute which is
778
+     * one of 'uniqueMember', 'memberUid', 'member'
779
+     * @return string|false, string with the attribute name, false on error
780
+     * @throws \Exception
781
+     */
782
+    private function detectGroupMemberAssoc() {
783
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member');
784
+        $filter = $this->configuration->ldapGroupFilter;
785
+        if(empty($filter)) {
786
+            return false;
787
+        }
788
+        $cr = $this->getConnection();
789
+        if(!$cr) {
790
+            throw new \Exception('Could not connect to LDAP');
791
+        }
792
+        $base = $this->configuration->ldapBase[0];
793
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
794
+        if(!$this->ldap->isResource($rr)) {
795
+            return false;
796
+        }
797
+        $er = $this->ldap->firstEntry($cr, $rr);
798
+        while(is_resource($er)) {
799
+            $this->ldap->getDN($cr, $er);
800
+            $attrs = $this->ldap->getAttributes($cr, $er);
801
+            $result = array();
802
+            $possibleAttrsCount = count($possibleAttrs);
803
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
804
+                if(isset($attrs[$possibleAttrs[$i]])) {
805
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
806
+                }
807
+            }
808
+            if(!empty($result)) {
809
+                natsort($result);
810
+                return key($result);
811
+            }
812
+
813
+            $er = $this->ldap->nextEntry($cr, $er);
814
+        }
815
+
816
+        return false;
817
+    }
818
+
819
+    /**
820
+     * Checks whether for a given BaseDN results will be returned
821
+     * @param string $base the BaseDN to test
822
+     * @return bool true on success, false otherwise
823
+     * @throws \Exception
824
+     */
825
+    private function testBaseDN($base) {
826
+        $cr = $this->getConnection();
827
+        if(!$cr) {
828
+            throw new \Exception('Could not connect to LDAP');
829
+        }
830
+
831
+        //base is there, let's validate it. If we search for anything, we should
832
+        //get a result set > 0 on a proper base
833
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
834
+        if(!$this->ldap->isResource($rr)) {
835
+            $errorNo  = $this->ldap->errno($cr);
836
+            $errorMsg = $this->ldap->error($cr);
837
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
838
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
839
+            return false;
840
+        }
841
+        $entries = $this->ldap->countEntries($cr, $rr);
842
+        return ($entries !== false) && ($entries > 0);
843
+    }
844
+
845
+    /**
846
+     * Checks whether the server supports memberOf in LDAP Filter.
847
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
848
+     * a configured objectClass. I.e. not necessarily for all available groups
849
+     * memberOf does work.
850
+     *
851
+     * @return bool true if it does, false otherwise
852
+     * @throws \Exception
853
+     */
854
+    private function testMemberOf() {
855
+        $cr = $this->getConnection();
856
+        if(!$cr) {
857
+            throw new \Exception('Could not connect to LDAP');
858
+        }
859
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
860
+        if(is_int($result) &&  $result > 0) {
861
+            return true;
862
+        }
863
+        return false;
864
+    }
865
+
866
+    /**
867
+     * creates an LDAP Filter from given configuration
868
+     * @param integer $filterType int, for which use case the filter shall be created
869
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
870
+     * self::LFILTER_GROUP_LIST
871
+     * @return string|false string with the filter on success, false otherwise
872
+     * @throws \Exception
873
+     */
874
+    private function composeLdapFilter($filterType) {
875
+        $filter = '';
876
+        $parts = 0;
877
+        switch ($filterType) {
878
+            case self::LFILTER_USER_LIST:
879
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
880
+                //glue objectclasses
881
+                if(is_array($objcs) && count($objcs) > 0) {
882
+                    $filter .= '(|';
883
+                    foreach($objcs as $objc) {
884
+                        $filter .= '(objectclass=' . $objc . ')';
885
+                    }
886
+                    $filter .= ')';
887
+                    $parts++;
888
+                }
889
+                //glue group memberships
890
+                if($this->configuration->hasMemberOfFilterSupport) {
891
+                    $cns = $this->configuration->ldapUserFilterGroups;
892
+                    if(is_array($cns) && count($cns) > 0) {
893
+                        $filter .= '(|';
894
+                        $cr = $this->getConnection();
895
+                        if(!$cr) {
896
+                            throw new \Exception('Could not connect to LDAP');
897
+                        }
898
+                        $base = $this->configuration->ldapBase[0];
899
+                        foreach($cns as $cn) {
900
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
901
+                            if(!$this->ldap->isResource($rr)) {
902
+                                continue;
903
+                            }
904
+                            $er = $this->ldap->firstEntry($cr, $rr);
905
+                            $attrs = $this->ldap->getAttributes($cr, $er);
906
+                            $dn = $this->ldap->getDN($cr, $er);
907
+                            if ($dn == false || $dn === '') {
908
+                                continue;
909
+                            }
910
+                            $filterPart = '(memberof=' . $dn . ')';
911
+                            if(isset($attrs['primaryGroupToken'])) {
912
+                                $pgt = $attrs['primaryGroupToken'][0];
913
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
914
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
915
+                            }
916
+                            $filter .= $filterPart;
917
+                        }
918
+                        $filter .= ')';
919
+                    }
920
+                    $parts++;
921
+                }
922
+                //wrap parts in AND condition
923
+                if($parts > 1) {
924
+                    $filter = '(&' . $filter . ')';
925
+                }
926
+                if ($filter === '') {
927
+                    $filter = '(objectclass=*)';
928
+                }
929
+                break;
930
+
931
+            case self::LFILTER_GROUP_LIST:
932
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
933
+                //glue objectclasses
934
+                if(is_array($objcs) && count($objcs) > 0) {
935
+                    $filter .= '(|';
936
+                    foreach($objcs as $objc) {
937
+                        $filter .= '(objectclass=' . $objc . ')';
938
+                    }
939
+                    $filter .= ')';
940
+                    $parts++;
941
+                }
942
+                //glue group memberships
943
+                $cns = $this->configuration->ldapGroupFilterGroups;
944
+                if(is_array($cns) && count($cns) > 0) {
945
+                    $filter .= '(|';
946
+                    foreach($cns as $cn) {
947
+                        $filter .= '(cn=' . $cn . ')';
948
+                    }
949
+                    $filter .= ')';
950
+                }
951
+                $parts++;
952
+                //wrap parts in AND condition
953
+                if($parts > 1) {
954
+                    $filter = '(&' . $filter . ')';
955
+                }
956
+                break;
957
+
958
+            case self::LFILTER_LOGIN:
959
+                $ulf = $this->configuration->ldapUserFilter;
960
+                $loginpart = '=%uid';
961
+                $filterUsername = '';
962
+                $userAttributes = $this->getUserAttributes();
963
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
964
+                $parts = 0;
965
+
966
+                if($this->configuration->ldapLoginFilterUsername === '1') {
967
+                    $attr = '';
968
+                    if(isset($userAttributes['uid'])) {
969
+                        $attr = 'uid';
970
+                    } else if(isset($userAttributes['samaccountname'])) {
971
+                        $attr = 'samaccountname';
972
+                    } else if(isset($userAttributes['cn'])) {
973
+                        //fallback
974
+                        $attr = 'cn';
975
+                    }
976
+                    if ($attr !== '') {
977
+                        $filterUsername = '(' . $attr . $loginpart . ')';
978
+                        $parts++;
979
+                    }
980
+                }
981
+
982
+                $filterEmail = '';
983
+                if($this->configuration->ldapLoginFilterEmail === '1') {
984
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
985
+                    $parts++;
986
+                }
987
+
988
+                $filterAttributes = '';
989
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
990
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991
+                    $filterAttributes = '(|';
992
+                    foreach($attrsToFilter as $attribute) {
993
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
994
+                    }
995
+                    $filterAttributes .= ')';
996
+                    $parts++;
997
+                }
998
+
999
+                $filterLogin = '';
1000
+                if($parts > 1) {
1001
+                    $filterLogin = '(|';
1002
+                }
1003
+                $filterLogin .= $filterUsername;
1004
+                $filterLogin .= $filterEmail;
1005
+                $filterLogin .= $filterAttributes;
1006
+                if($parts > 1) {
1007
+                    $filterLogin .= ')';
1008
+                }
1009
+
1010
+                $filter = '(&'.$ulf.$filterLogin.')';
1011
+                break;
1012
+        }
1013
+
1014
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1015
+
1016
+        return $filter;
1017
+    }
1018
+
1019
+    /**
1020
+     * Connects and Binds to an LDAP Server
1021
+     * @param int $port the port to connect with
1022
+     * @param bool $tls whether startTLS is to be used
1023
+     * @param bool $ncc
1024
+     * @return bool
1025
+     * @throws \Exception
1026
+     */
1027
+    private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1028
+        if($ncc) {
1029
+            //No certificate check
1030
+            //FIXME: undo afterwards
1031
+            putenv('LDAPTLS_REQCERT=never');
1032
+        }
1033
+
1034
+        //connect, does not really trigger any server communication
1035
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1036
+        $host = $this->configuration->ldapHost;
1037
+        $hostInfo = parse_url($host);
1038
+        if(!$hostInfo) {
1039
+            throw new \Exception(self::$l->t('Invalid Host'));
1040
+        }
1041
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1042
+        $cr = $this->ldap->connect($host, $port);
1043
+        if(!is_resource($cr)) {
1044
+            throw new \Exception(self::$l->t('Invalid Host'));
1045
+        }
1046
+
1047
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Setting LDAP Options ', \OCP\Util::DEBUG);
1048
+        //set LDAP options
1049
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1050
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1051
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1052
+
1053
+        try {
1054
+            if($tls) {
1055
+                $isTlsWorking = @$this->ldap->startTls($cr);
1056
+                if(!$isTlsWorking) {
1057
+                    return false;
1058
+                }
1059
+            }
1060
+
1061
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1062
+            //interesting part: do the bind!
1063
+            $login = $this->ldap->bind($cr,
1064
+                $this->configuration->ldapAgentName,
1065
+                $this->configuration->ldapAgentPassword
1066
+            );
1067
+            $errNo = $this->ldap->errno($cr);
1068
+            $error = ldap_error($cr);
1069
+            $this->ldap->unbind($cr);
1070
+        } catch(ServerNotAvailableException $e) {
1071
+            return false;
1072
+        }
1073
+
1074
+        if($login === true) {
1075
+            $this->ldap->unbind($cr);
1076
+            if($ncc) {
1077
+                throw new \Exception('Certificate cannot be validated.');
1078
+            }
1079
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1080
+            return true;
1081
+        }
1082
+
1083
+        if($errNo === -1 || ($errNo === 2 && $ncc)) {
1084
+            //host, port or TLS wrong
1085
+            return false;
1086
+        } else if ($errNo === 2) {
1087
+            return $this->connectAndBind($port, $tls, true);
1088
+        }
1089
+        throw new \Exception($error, $errNo);
1090
+    }
1091
+
1092
+    /**
1093
+     * checks whether a valid combination of agent and password has been
1094
+     * provided (either two values or nothing for anonymous connect)
1095
+     * @return bool, true if everything is fine, false otherwise
1096
+     */
1097
+    private function checkAgentRequirements() {
1098
+        $agent = $this->configuration->ldapAgentName;
1099
+        $pwd = $this->configuration->ldapAgentPassword;
1100
+
1101
+        return
1102
+            ($agent !== '' && $pwd !== '')
1103
+            ||  ($agent === '' && $pwd === '')
1104
+        ;
1105
+    }
1106
+
1107
+    /**
1108
+     * @param array $reqs
1109
+     * @return bool
1110
+     */
1111
+    private function checkRequirements($reqs) {
1112
+        $this->checkAgentRequirements();
1113
+        foreach($reqs as $option) {
1114
+            $value = $this->configuration->$option;
1115
+            if(empty($value)) {
1116
+                return false;
1117
+            }
1118
+        }
1119
+        return true;
1120
+    }
1121
+
1122
+    /**
1123
+     * does a cumulativeSearch on LDAP to get different values of a
1124
+     * specified attribute
1125
+     * @param string[] $filters array, the filters that shall be used in the search
1126
+     * @param string $attr the attribute of which a list of values shall be returned
1127
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1128
+     * The lower, the faster
1129
+     * @param string $maxF string. if not null, this variable will have the filter that
1130
+     * yields most result entries
1131
+     * @return array|false an array with the values on success, false otherwise
1132
+     */
1133
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1134
+        $dnRead = array();
1135
+        $foundItems = array();
1136
+        $maxEntries = 0;
1137
+        if(!is_array($this->configuration->ldapBase)
1138
+           || !isset($this->configuration->ldapBase[0])) {
1139
+            return false;
1140
+        }
1141
+        $base = $this->configuration->ldapBase[0];
1142
+        $cr = $this->getConnection();
1143
+        if(!$this->ldap->isResource($cr)) {
1144
+            return false;
1145
+        }
1146
+        $lastFilter = null;
1147
+        if(isset($filters[count($filters)-1])) {
1148
+            $lastFilter = $filters[count($filters)-1];
1149
+        }
1150
+        foreach($filters as $filter) {
1151
+            if($lastFilter === $filter && count($foundItems) > 0) {
1152
+                //skip when the filter is a wildcard and results were found
1153
+                continue;
1154
+            }
1155
+            // 20k limit for performance and reason
1156
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
+            if(!$this->ldap->isResource($rr)) {
1158
+                continue;
1159
+            }
1160
+            $entries = $this->ldap->countEntries($cr, $rr);
1161
+            $getEntryFunc = 'firstEntry';
1162
+            if(($entries !== false) && ($entries > 0)) {
1163
+                if(!is_null($maxF) && $entries > $maxEntries) {
1164
+                    $maxEntries = $entries;
1165
+                    $maxF = $filter;
1166
+                }
1167
+                $dnReadCount = 0;
1168
+                do {
1169
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1170
+                    $getEntryFunc = 'nextEntry';
1171
+                    if(!$this->ldap->isResource($entry)) {
1172
+                        continue 2;
1173
+                    }
1174
+                    $rr = $entry; //will be expected by nextEntry next round
1175
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1176
+                    $dn = $this->ldap->getDN($cr, $entry);
1177
+                    if($dn === false || in_array($dn, $dnRead)) {
1178
+                        continue;
1179
+                    }
1180
+                    $newItems = array();
1181
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1182
+                                                                $attr,
1183
+                                                                $newItems);
1184
+                    $dnReadCount++;
1185
+                    $foundItems = array_merge($foundItems, $newItems);
1186
+                    $this->resultCache[$dn][$attr] = $newItems;
1187
+                    $dnRead[] = $dn;
1188
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1189
+                        || $this->ldap->isResource($entry))
1190
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191
+            }
1192
+        }
1193
+
1194
+        return array_unique($foundItems);
1195
+    }
1196
+
1197
+    /**
1198
+     * determines if and which $attr are available on the LDAP server
1199
+     * @param string[] $objectclasses the objectclasses to use as search filter
1200
+     * @param string $attr the attribute to look for
1201
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1202
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1203
+     * Configuration class
1204
+     * @param bool $po whether the objectClass with most result entries
1205
+     * shall be pre-selected via the result
1206
+     * @return array|false list of found items.
1207
+     * @throws \Exception
1208
+     */
1209
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210
+        $cr = $this->getConnection();
1211
+        if(!$cr) {
1212
+            throw new \Exception('Could not connect to LDAP');
1213
+        }
1214
+        $p = 'objectclass=';
1215
+        foreach($objectclasses as $key => $value) {
1216
+            $objectclasses[$key] = $p.$value;
1217
+        }
1218
+        $maxEntryObjC = '';
1219
+
1220
+        //how deep to dig?
1221
+        //When looking for objectclasses, testing few entries is sufficient,
1222
+        $dig = 3;
1223
+
1224
+        $availableFeatures =
1225
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226
+                                                $dig, $maxEntryObjC);
1227
+        if(is_array($availableFeatures)
1228
+           && count($availableFeatures) > 0) {
1229
+            natcasesort($availableFeatures);
1230
+            //natcasesort keeps indices, but we must get rid of them for proper
1231
+            //sorting in the web UI. Therefore: array_values
1232
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1233
+        } else {
1234
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1235
+        }
1236
+
1237
+        $setFeatures = $this->configuration->$confkey;
1238
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1239
+            //something is already configured? pre-select it.
1240
+            $this->result->addChange($dbkey, $setFeatures);
1241
+        } else if ($po && $maxEntryObjC !== '') {
1242
+            //pre-select objectclass with most result entries
1243
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1244
+            $this->applyFind($dbkey, $maxEntryObjC);
1245
+            $this->result->addChange($dbkey, $maxEntryObjC);
1246
+        }
1247
+
1248
+        return $availableFeatures;
1249
+    }
1250
+
1251
+    /**
1252
+     * appends a list of values fr
1253
+     * @param resource $result the return value from ldap_get_attributes
1254
+     * @param string $attribute the attribute values to look for
1255
+     * @param array &$known new values will be appended here
1256
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1257
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258
+     */
1259
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
+        if(!is_array($result)
1261
+           || !isset($result['count'])
1262
+           || !$result['count'] > 0) {
1263
+            return self::LRESULT_PROCESSED_INVALID;
1264
+        }
1265
+
1266
+        // strtolower on all keys for proper comparison
1267
+        $result = \OCP\Util::mb_array_change_key_case($result);
1268
+        $attribute = strtolower($attribute);
1269
+        if(isset($result[$attribute])) {
1270
+            foreach($result[$attribute] as $key => $val) {
1271
+                if($key === 'count') {
1272
+                    continue;
1273
+                }
1274
+                if(!in_array($val, $known)) {
1275
+                    $known[] = $val;
1276
+                }
1277
+            }
1278
+            return self::LRESULT_PROCESSED_OK;
1279
+        } else {
1280
+            return self::LRESULT_PROCESSED_SKIP;
1281
+        }
1282
+    }
1283
+
1284
+    /**
1285
+     * @return bool|mixed
1286
+     */
1287
+    private function getConnection() {
1288
+        if(!is_null($this->cr)) {
1289
+            return $this->cr;
1290
+        }
1291
+
1292
+        $cr = $this->ldap->connect(
1293
+            $this->configuration->ldapHost,
1294
+            $this->configuration->ldapPort
1295
+        );
1296
+
1297
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
+        if($this->configuration->ldapTLS === 1) {
1301
+            $this->ldap->startTls($cr);
1302
+        }
1303
+
1304
+        $lo = @$this->ldap->bind($cr,
1305
+                                    $this->configuration->ldapAgentName,
1306
+                                    $this->configuration->ldapAgentPassword);
1307
+        if($lo === true) {
1308
+            $this->$cr = $cr;
1309
+            return $cr;
1310
+        }
1311
+
1312
+        return false;
1313
+    }
1314
+
1315
+    /**
1316
+     * @return array
1317
+     */
1318
+    private function getDefaultLdapPortSettings() {
1319
+        static $settings = array(
1320
+                                array('port' => 7636, 'tls' => false),
1321
+                                array('port' =>  636, 'tls' => false),
1322
+                                array('port' => 7389, 'tls' => true),
1323
+                                array('port' =>  389, 'tls' => true),
1324
+                                array('port' => 7389, 'tls' => false),
1325
+                                array('port' =>  389, 'tls' => false),
1326
+                            );
1327
+        return $settings;
1328
+    }
1329
+
1330
+    /**
1331
+     * @return array
1332
+     */
1333
+    private function getPortSettingsToTry() {
1334
+        //389 ← LDAP / Unencrypted or StartTLS
1335
+        //636 ← LDAPS / SSL
1336
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1337
+        $host = $this->configuration->ldapHost;
1338
+        $port = intval($this->configuration->ldapPort);
1339
+        $portSettings = array();
1340
+
1341
+        //In case the port is already provided, we will check this first
1342
+        if($port > 0) {
1343
+            $hostInfo = parse_url($host);
1344
+            if(!(is_array($hostInfo)
1345
+                && isset($hostInfo['scheme'])
1346
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347
+                $portSettings[] = array('port' => $port, 'tls' => true);
1348
+            }
1349
+            $portSettings[] =array('port' => $port, 'tls' => false);
1350
+        }
1351
+
1352
+        //default ports
1353
+        $portSettings = array_merge($portSettings,
1354
+                                    $this->getDefaultLdapPortSettings());
1355
+
1356
+        return $portSettings;
1357
+    }
1358 1358
 
1359 1359
 
1360 1360
 }
Please login to merge, or discard this patch.
Spacing   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
68 68
 		parent::__construct($ldap);
69 69
 		$this->configuration = $configuration;
70
-		if(is_null(Wizard::$l)) {
70
+		if (is_null(Wizard::$l)) {
71 71
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
72 72
 		}
73 73
 		$this->access = $access;
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 	}
76 76
 
77 77
 	public function  __destruct() {
78
-		if($this->result->hasChanges()) {
78
+		if ($this->result->hasChanges()) {
79 79
 			$this->configuration->saveConfiguration();
80 80
 		}
81 81
 	}
@@ -90,18 +90,18 @@  discard block
 block discarded – undo
90 90
 	 */
91 91
 	public function countEntries($filter, $type) {
92 92
 		$reqs = array('ldapHost', 'ldapPort', 'ldapBase');
93
-		if($type === 'users') {
93
+		if ($type === 'users') {
94 94
 			$reqs[] = 'ldapUserFilter';
95 95
 		}
96
-		if(!$this->checkRequirements($reqs)) {
96
+		if (!$this->checkRequirements($reqs)) {
97 97
 			throw new \Exception('Requirements not met', 400);
98 98
 		}
99 99
 
100 100
 		$attr = array('dn'); // default
101 101
 		$limit = 1001;
102
-		if($type === 'groups') {
103
-			$result =  $this->access->countGroups($filter, $attr, $limit);
104
-		} else if($type === 'users') {
102
+		if ($type === 'groups') {
103
+			$result = $this->access->countGroups($filter, $attr, $limit);
104
+		} else if ($type === 'users') {
105 105
 			$result = $this->access->countUsers($filter, $attr, $limit);
106 106
 		} else if ($type === 'objects') {
107 107
 			$result = $this->access->countObjects($limit);
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	 */
122 122
 	private function formatCountResult($count) {
123 123
 		$formatted = ($count !== false) ? $count : 0;
124
-		if($formatted > 1000) {
124
+		if ($formatted > 1000) {
125 125
 			$formatted = '> 1000';
126 126
 		}
127 127
 		return $formatted;
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 	public function countGroups() {
131 131
 		$filter = $this->configuration->ldapGroupFilter;
132 132
 
133
-		if(empty($filter)) {
133
+		if (empty($filter)) {
134 134
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
135 135
 			$this->result->addChange('ldap_group_count', $output);
136 136
 			return $this->result;
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 			$groupsTotal = $this->formatCountResult($this->countEntries($filter, 'groups'));
141 141
 		} catch (\Exception $e) {
142 142
 			//400 can be ignored, 500 is forwarded
143
-			if($e->getCode() === 500) {
143
+			if ($e->getCode() === 500) {
144 144
 				throw $e;
145 145
 			}
146 146
 			return false;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 	public function countInBaseDN() {
173 173
 		// we don't need to provide a filter in this case
174 174
 		$total = $this->countEntries(null, 'objects');
175
-		if($total === false) {
175
+		if ($total === false) {
176 176
 			throw new \Exception('invalid results received');
177 177
 		}
178 178
 		$this->result->addChange('ldap_test_base', $total);
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 	 * @return int|bool
187 187
 	 */
188 188
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
189
-		if(!$this->checkRequirements(array('ldapHost',
189
+		if (!$this->checkRequirements(array('ldapHost',
190 190
 										   'ldapPort',
191 191
 										   'ldapBase',
192 192
 										   'ldapUserFilter',
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 
197 197
 		$filter = $this->access->combineFilterWithAnd(array(
198 198
 			$this->configuration->ldapUserFilter,
199
-			$attr . '=*'
199
+			$attr.'=*'
200 200
 		));
201 201
 
202 202
 		$limit = ($existsCheck === false) ? null : 1;
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 	 * @throws \Exception
212 212
 	 */
213 213
 	public function detectUserDisplayNameAttribute() {
214
-		if(!$this->checkRequirements(array('ldapHost',
214
+		if (!$this->checkRequirements(array('ldapHost',
215 215
 										'ldapPort',
216 216
 										'ldapBase',
217 217
 										'ldapUserFilter',
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 			// most likely not the default value with upper case N,
225 225
 			// verify it still produces a result
226 226
 			$count = intval($this->countUsersWithAttribute($attr, true));
227
-			if($count > 0) {
227
+			if ($count > 0) {
228 228
 				//no change, but we sent it back to make sure the user interface
229 229
 				//is still correct, even if the ajax call was cancelled meanwhile
230 230
 				$this->result->addChange('ldap_display_name', $attr);
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 		foreach ($displayNameAttrs as $attr) {
238 238
 			$count = intval($this->countUsersWithAttribute($attr, true));
239 239
 
240
-			if($count > 0) {
240
+			if ($count > 0) {
241 241
 				$this->applyFind('ldap_display_name', $attr);
242 242
 				return $this->result;
243 243
 			}
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 	 * @return WizardResult|bool
254 254
 	 */
255 255
 	public function detectEmailAttribute() {
256
-		if(!$this->checkRequirements(array('ldapHost',
256
+		if (!$this->checkRequirements(array('ldapHost',
257 257
 										   'ldapPort',
258 258
 										   'ldapBase',
259 259
 										   'ldapUserFilter',
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 		$attr = $this->configuration->ldapEmailAttribute;
265 265
 		if ($attr !== '') {
266 266
 			$count = intval($this->countUsersWithAttribute($attr, true));
267
-			if($count > 0) {
267
+			if ($count > 0) {
268 268
 				return false;
269 269
 			}
270 270
 			$writeLog = true;
@@ -275,19 +275,19 @@  discard block
 block discarded – undo
275 275
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
276 276
 		$winner = '';
277 277
 		$maxUsers = 0;
278
-		foreach($emailAttributes as $attr) {
278
+		foreach ($emailAttributes as $attr) {
279 279
 			$count = $this->countUsersWithAttribute($attr);
280
-			if($count > $maxUsers) {
280
+			if ($count > $maxUsers) {
281 281
 				$maxUsers = $count;
282 282
 				$winner = $attr;
283 283
 			}
284 284
 		}
285 285
 
286
-		if($winner !== '') {
286
+		if ($winner !== '') {
287 287
 			$this->applyFind('ldap_email_attr', $winner);
288
-			if($writeLog) {
289
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
290
-					'automatically been reset, because the original value ' .
288
+			if ($writeLog) {
289
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
290
+					'automatically been reset, because the original value '.
291 291
 					'did not return any results.', \OCP\Util::INFO);
292 292
 			}
293 293
 		}
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 	 * @throws \Exception
301 301
 	 */
302 302
 	public function determineAttributes() {
303
-		if(!$this->checkRequirements(array('ldapHost',
303
+		if (!$this->checkRequirements(array('ldapHost',
304 304
 										   'ldapPort',
305 305
 										   'ldapBase',
306 306
 										   'ldapUserFilter',
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
317 317
 
318 318
 		$selected = $this->configuration->ldapLoginFilterAttributes;
319
-		if(is_array($selected) && !empty($selected)) {
319
+		if (is_array($selected) && !empty($selected)) {
320 320
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
321 321
 		}
322 322
 
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 	 * @throws \Exception
330 330
 	 */
331 331
 	private function getUserAttributes() {
332
-		if(!$this->checkRequirements(array('ldapHost',
332
+		if (!$this->checkRequirements(array('ldapHost',
333 333
 										   'ldapPort',
334 334
 										   'ldapBase',
335 335
 										   'ldapUserFilter',
@@ -337,20 +337,20 @@  discard block
 block discarded – undo
337 337
 			return  false;
338 338
 		}
339 339
 		$cr = $this->getConnection();
340
-		if(!$cr) {
340
+		if (!$cr) {
341 341
 			throw new \Exception('Could not connect to LDAP');
342 342
 		}
343 343
 
344 344
 		$base = $this->configuration->ldapBase[0];
345 345
 		$filter = $this->configuration->ldapUserFilter;
346 346
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
347
-		if(!$this->ldap->isResource($rr)) {
347
+		if (!$this->ldap->isResource($rr)) {
348 348
 			return false;
349 349
 		}
350 350
 		$er = $this->ldap->firstEntry($cr, $rr);
351 351
 		$attributes = $this->ldap->getAttributes($cr, $er);
352 352
 		$pureAttributes = array();
353
-		for($i = 0; $i < $attributes['count']; $i++) {
353
+		for ($i = 0; $i < $attributes['count']; $i++) {
354 354
 			$pureAttributes[] = $attributes[$i];
355 355
 		}
356 356
 
@@ -385,23 +385,23 @@  discard block
 block discarded – undo
385 385
 	 * @throws \Exception
386 386
 	 */
387 387
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
388
-		if(!$this->checkRequirements(array('ldapHost',
388
+		if (!$this->checkRequirements(array('ldapHost',
389 389
 										   'ldapPort',
390 390
 										   'ldapBase',
391 391
 										   ))) {
392 392
 			return  false;
393 393
 		}
394 394
 		$cr = $this->getConnection();
395
-		if(!$cr) {
395
+		if (!$cr) {
396 396
 			throw new \Exception('Could not connect to LDAP');
397 397
 		}
398 398
 
399 399
 		$this->fetchGroups($dbKey, $confKey);
400 400
 
401
-		if($testMemberOf) {
401
+		if ($testMemberOf) {
402 402
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
403 403
 			$this->result->markChange();
404
-			if(!$this->configuration->hasMemberOfFilterSupport) {
404
+			if (!$this->configuration->hasMemberOfFilterSupport) {
405 405
 				throw new \Exception('memberOf is not supported by the server');
406 406
 			}
407 407
 		}
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames');
422 422
 
423 423
 		$filterParts = array();
424
-		foreach($obclasses as $obclass) {
424
+		foreach ($obclasses as $obclass) {
425 425
 			$filterParts[] = 'objectclass='.$obclass;
426 426
 		}
427 427
 		//we filter for everything
@@ -438,8 +438,8 @@  discard block
 block discarded – undo
438 438
 			// we need to request dn additionally here, otherwise memberOf
439 439
 			// detection will fail later
440 440
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
441
-			foreach($result as $item) {
442
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
441
+			foreach ($result as $item) {
442
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
443 443
 					// just in case - no issue known
444 444
 					continue;
445 445
 				}
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
 			$offset += $limit;
450 450
 		} while ($this->access->hasMoreResults());
451 451
 
452
-		if(count($groupNames) > 0) {
452
+		if (count($groupNames) > 0) {
453 453
 			natsort($groupNames);
454 454
 			$this->result->addOptions($dbKey, array_values($groupNames));
455 455
 		} else {
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
 		}
458 458
 
459 459
 		$setFeatures = $this->configuration->$confKey;
460
-		if(is_array($setFeatures) && !empty($setFeatures)) {
460
+		if (is_array($setFeatures) && !empty($setFeatures)) {
461 461
 			//something is already configured? pre-select it.
462 462
 			$this->result->addChange($dbKey, $setFeatures);
463 463
 		}
@@ -465,14 +465,14 @@  discard block
 block discarded – undo
465 465
 	}
466 466
 
467 467
 	public function determineGroupMemberAssoc() {
468
-		if(!$this->checkRequirements(array('ldapHost',
468
+		if (!$this->checkRequirements(array('ldapHost',
469 469
 										   'ldapPort',
470 470
 										   'ldapGroupFilter',
471 471
 										   ))) {
472 472
 			return  false;
473 473
 		}
474 474
 		$attribute = $this->detectGroupMemberAssoc();
475
-		if($attribute === false) {
475
+		if ($attribute === false) {
476 476
 			return false;
477 477
 		}
478 478
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -487,14 +487,14 @@  discard block
 block discarded – undo
487 487
 	 * @throws \Exception
488 488
 	 */
489 489
 	public function determineGroupObjectClasses() {
490
-		if(!$this->checkRequirements(array('ldapHost',
490
+		if (!$this->checkRequirements(array('ldapHost',
491 491
 										   'ldapPort',
492 492
 										   'ldapBase',
493 493
 										   ))) {
494 494
 			return  false;
495 495
 		}
496 496
 		$cr = $this->getConnection();
497
-		if(!$cr) {
497
+		if (!$cr) {
498 498
 			throw new \Exception('Could not connect to LDAP');
499 499
 		}
500 500
 
@@ -514,14 +514,14 @@  discard block
 block discarded – undo
514 514
 	 * @throws \Exception
515 515
 	 */
516 516
 	public function determineUserObjectClasses() {
517
-		if(!$this->checkRequirements(array('ldapHost',
517
+		if (!$this->checkRequirements(array('ldapHost',
518 518
 										   'ldapPort',
519 519
 										   'ldapBase',
520 520
 										   ))) {
521 521
 			return  false;
522 522
 		}
523 523
 		$cr = $this->getConnection();
524
-		if(!$cr) {
524
+		if (!$cr) {
525 525
 			throw new \Exception('Could not connect to LDAP');
526 526
 		}
527 527
 
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 	 * @throws \Exception
545 545
 	 */
546 546
 	public function getGroupFilter() {
547
-		if(!$this->checkRequirements(array('ldapHost',
547
+		if (!$this->checkRequirements(array('ldapHost',
548 548
 										   'ldapPort',
549 549
 										   'ldapBase',
550 550
 										   ))) {
@@ -568,7 +568,7 @@  discard block
 block discarded – undo
568 568
 	 * @throws \Exception
569 569
 	 */
570 570
 	public function getUserListFilter() {
571
-		if(!$this->checkRequirements(array('ldapHost',
571
+		if (!$this->checkRequirements(array('ldapHost',
572 572
 										   'ldapPort',
573 573
 										   'ldapBase',
574 574
 										   ))) {
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
582 582
 		}
583 583
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
584
-		if(!$filter) {
584
+		if (!$filter) {
585 585
 			throw new \Exception('Cannot create filter');
586 586
 		}
587 587
 
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 	 * @throws \Exception
595 595
 	 */
596 596
 	public function getUserLoginFilter() {
597
-		if(!$this->checkRequirements(array('ldapHost',
597
+		if (!$this->checkRequirements(array('ldapHost',
598 598
 										   'ldapPort',
599 599
 										   'ldapBase',
600 600
 										   'ldapUserFilter',
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 		}
604 604
 
605 605
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
606
-		if(!$filter) {
606
+		if (!$filter) {
607 607
 			throw new \Exception('Cannot create filter');
608 608
 		}
609 609
 
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 	 * @throws \Exception
618 618
 	 */
619 619
 	public function testLoginName($loginName) {
620
-		if(!$this->checkRequirements(array('ldapHost',
620
+		if (!$this->checkRequirements(array('ldapHost',
621 621
 			'ldapPort',
622 622
 			'ldapBase',
623 623
 			'ldapLoginFilter',
@@ -626,17 +626,17 @@  discard block
 block discarded – undo
626 626
 		}
627 627
 
628 628
 		$cr = $this->access->connection->getConnectionResource();
629
-		if(!$this->ldap->isResource($cr)) {
629
+		if (!$this->ldap->isResource($cr)) {
630 630
 			throw new \Exception('connection error');
631 631
 		}
632 632
 
633
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
633
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
634 634
 			=== false) {
635 635
 			throw new \Exception('missing placeholder');
636 636
 		}
637 637
 
638 638
 		$users = $this->access->countUsersByLoginName($loginName);
639
-		if($this->ldap->errno($cr) !== 0) {
639
+		if ($this->ldap->errno($cr) !== 0) {
640 640
 			throw new \Exception($this->ldap->error($cr));
641 641
 		}
642 642
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -651,22 +651,22 @@  discard block
 block discarded – undo
651 651
 	 * @throws \Exception
652 652
 	 */
653 653
 	public function guessPortAndTLS() {
654
-		if(!$this->checkRequirements(array('ldapHost',
654
+		if (!$this->checkRequirements(array('ldapHost',
655 655
 										   ))) {
656 656
 			return false;
657 657
 		}
658 658
 		$this->checkHost();
659 659
 		$portSettings = $this->getPortSettingsToTry();
660 660
 
661
-		if(!is_array($portSettings)) {
661
+		if (!is_array($portSettings)) {
662 662
 			throw new \Exception(print_r($portSettings, true));
663 663
 		}
664 664
 
665 665
 		//proceed from the best configuration and return on first success
666
-		foreach($portSettings as $setting) {
666
+		foreach ($portSettings as $setting) {
667 667
 			$p = $setting['port'];
668 668
 			$t = $setting['tls'];
669
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
669
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
670 670
 			//connectAndBind may throw Exception, it needs to be catched by the
671 671
 			//callee of this method
672 672
 
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
 				// any reply other than -1 (= cannot connect) is already okay,
677 677
 				// because then we found the server
678 678
 				// unavailable startTLS returns -11
679
-				if($e->getCode() > 0) {
679
+				if ($e->getCode() > 0) {
680 680
 					$settingsFound = true;
681 681
 				} else {
682 682
 					throw $e;
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 					'ldapTLS' => intval($t)
690 690
 				);
691 691
 				$this->configuration->setConfiguration($config);
692
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
692
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
693 693
 				$this->result->addChange('ldap_port', $p);
694 694
 				return $this->result;
695 695
 			}
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
 	 * @return WizardResult|false WizardResult on success, false otherwise
705 705
 	 */
706 706
 	public function guessBaseDN() {
707
-		if(!$this->checkRequirements(array('ldapHost',
707
+		if (!$this->checkRequirements(array('ldapHost',
708 708
 										   'ldapPort',
709 709
 										   ))) {
710 710
 			return false;
@@ -713,9 +713,9 @@  discard block
 block discarded – undo
713 713
 		//check whether a DN is given in the agent name (99.9% of all cases)
714 714
 		$base = null;
715 715
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
716
-		if($i !== false) {
716
+		if ($i !== false) {
717 717
 			$base = substr($this->configuration->ldapAgentName, $i);
718
-			if($this->testBaseDN($base)) {
718
+			if ($this->testBaseDN($base)) {
719 719
 				$this->applyFind('ldap_base', $base);
720 720
 				return $this->result;
721 721
 			}
@@ -726,13 +726,13 @@  discard block
 block discarded – undo
726 726
 		//a base DN
727 727
 		$helper = new Helper(\OC::$server->getConfig());
728 728
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
729
-		if(!$domain) {
729
+		if (!$domain) {
730 730
 			return false;
731 731
 		}
732 732
 
733 733
 		$dparts = explode('.', $domain);
734
-		while(count($dparts) > 0) {
735
-			$base2 = 'dc=' . implode(',dc=', $dparts);
734
+		while (count($dparts) > 0) {
735
+			$base2 = 'dc='.implode(',dc=', $dparts);
736 736
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
737 737
 				$this->applyFind('ldap_base', $base2);
738 738
 				return $this->result;
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
 		$hostInfo = parse_url($host);
766 766
 
767 767
 		//removes Port from Host
768
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
768
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
769 769
 			$port = $hostInfo['port'];
770 770
 			$host = str_replace(':'.$port, '', $host);
771 771
 			$this->applyFind('ldap_host', $host);
@@ -782,30 +782,30 @@  discard block
 block discarded – undo
782 782
 	private function detectGroupMemberAssoc() {
783 783
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member');
784 784
 		$filter = $this->configuration->ldapGroupFilter;
785
-		if(empty($filter)) {
785
+		if (empty($filter)) {
786 786
 			return false;
787 787
 		}
788 788
 		$cr = $this->getConnection();
789
-		if(!$cr) {
789
+		if (!$cr) {
790 790
 			throw new \Exception('Could not connect to LDAP');
791 791
 		}
792 792
 		$base = $this->configuration->ldapBase[0];
793 793
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
794
-		if(!$this->ldap->isResource($rr)) {
794
+		if (!$this->ldap->isResource($rr)) {
795 795
 			return false;
796 796
 		}
797 797
 		$er = $this->ldap->firstEntry($cr, $rr);
798
-		while(is_resource($er)) {
798
+		while (is_resource($er)) {
799 799
 			$this->ldap->getDN($cr, $er);
800 800
 			$attrs = $this->ldap->getAttributes($cr, $er);
801 801
 			$result = array();
802 802
 			$possibleAttrsCount = count($possibleAttrs);
803
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
804
-				if(isset($attrs[$possibleAttrs[$i]])) {
803
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
804
+				if (isset($attrs[$possibleAttrs[$i]])) {
805 805
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
806 806
 				}
807 807
 			}
808
-			if(!empty($result)) {
808
+			if (!empty($result)) {
809 809
 				natsort($result);
810 810
 				return key($result);
811 811
 			}
@@ -824,14 +824,14 @@  discard block
 block discarded – undo
824 824
 	 */
825 825
 	private function testBaseDN($base) {
826 826
 		$cr = $this->getConnection();
827
-		if(!$cr) {
827
+		if (!$cr) {
828 828
 			throw new \Exception('Could not connect to LDAP');
829 829
 		}
830 830
 
831 831
 		//base is there, let's validate it. If we search for anything, we should
832 832
 		//get a result set > 0 on a proper base
833 833
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
834
-		if(!$this->ldap->isResource($rr)) {
834
+		if (!$this->ldap->isResource($rr)) {
835 835
 			$errorNo  = $this->ldap->errno($cr);
836 836
 			$errorMsg = $this->ldap->error($cr);
837 837
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -853,11 +853,11 @@  discard block
 block discarded – undo
853 853
 	 */
854 854
 	private function testMemberOf() {
855 855
 		$cr = $this->getConnection();
856
-		if(!$cr) {
856
+		if (!$cr) {
857 857
 			throw new \Exception('Could not connect to LDAP');
858 858
 		}
859 859
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
860
-		if(is_int($result) &&  $result > 0) {
860
+		if (is_int($result) && $result > 0) {
861 861
 			return true;
862 862
 		}
863 863
 		return false;
@@ -878,27 +878,27 @@  discard block
 block discarded – undo
878 878
 			case self::LFILTER_USER_LIST:
879 879
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
880 880
 				//glue objectclasses
881
-				if(is_array($objcs) && count($objcs) > 0) {
881
+				if (is_array($objcs) && count($objcs) > 0) {
882 882
 					$filter .= '(|';
883
-					foreach($objcs as $objc) {
884
-						$filter .= '(objectclass=' . $objc . ')';
883
+					foreach ($objcs as $objc) {
884
+						$filter .= '(objectclass='.$objc.')';
885 885
 					}
886 886
 					$filter .= ')';
887 887
 					$parts++;
888 888
 				}
889 889
 				//glue group memberships
890
-				if($this->configuration->hasMemberOfFilterSupport) {
890
+				if ($this->configuration->hasMemberOfFilterSupport) {
891 891
 					$cns = $this->configuration->ldapUserFilterGroups;
892
-					if(is_array($cns) && count($cns) > 0) {
892
+					if (is_array($cns) && count($cns) > 0) {
893 893
 						$filter .= '(|';
894 894
 						$cr = $this->getConnection();
895
-						if(!$cr) {
895
+						if (!$cr) {
896 896
 							throw new \Exception('Could not connect to LDAP');
897 897
 						}
898 898
 						$base = $this->configuration->ldapBase[0];
899
-						foreach($cns as $cn) {
900
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
901
-							if(!$this->ldap->isResource($rr)) {
899
+						foreach ($cns as $cn) {
900
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
901
+							if (!$this->ldap->isResource($rr)) {
902 902
 								continue;
903 903
 							}
904 904
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -907,11 +907,11 @@  discard block
 block discarded – undo
907 907
 							if ($dn == false || $dn === '') {
908 908
 								continue;
909 909
 							}
910
-							$filterPart = '(memberof=' . $dn . ')';
911
-							if(isset($attrs['primaryGroupToken'])) {
910
+							$filterPart = '(memberof='.$dn.')';
911
+							if (isset($attrs['primaryGroupToken'])) {
912 912
 								$pgt = $attrs['primaryGroupToken'][0];
913
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
914
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
913
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
914
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
915 915
 							}
916 916
 							$filter .= $filterPart;
917 917
 						}
@@ -920,8 +920,8 @@  discard block
 block discarded – undo
920 920
 					$parts++;
921 921
 				}
922 922
 				//wrap parts in AND condition
923
-				if($parts > 1) {
924
-					$filter = '(&' . $filter . ')';
923
+				if ($parts > 1) {
924
+					$filter = '(&'.$filter.')';
925 925
 				}
926 926
 				if ($filter === '') {
927 927
 					$filter = '(objectclass=*)';
@@ -931,27 +931,27 @@  discard block
 block discarded – undo
931 931
 			case self::LFILTER_GROUP_LIST:
932 932
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
933 933
 				//glue objectclasses
934
-				if(is_array($objcs) && count($objcs) > 0) {
934
+				if (is_array($objcs) && count($objcs) > 0) {
935 935
 					$filter .= '(|';
936
-					foreach($objcs as $objc) {
937
-						$filter .= '(objectclass=' . $objc . ')';
936
+					foreach ($objcs as $objc) {
937
+						$filter .= '(objectclass='.$objc.')';
938 938
 					}
939 939
 					$filter .= ')';
940 940
 					$parts++;
941 941
 				}
942 942
 				//glue group memberships
943 943
 				$cns = $this->configuration->ldapGroupFilterGroups;
944
-				if(is_array($cns) && count($cns) > 0) {
944
+				if (is_array($cns) && count($cns) > 0) {
945 945
 					$filter .= '(|';
946
-					foreach($cns as $cn) {
947
-						$filter .= '(cn=' . $cn . ')';
946
+					foreach ($cns as $cn) {
947
+						$filter .= '(cn='.$cn.')';
948 948
 					}
949 949
 					$filter .= ')';
950 950
 				}
951 951
 				$parts++;
952 952
 				//wrap parts in AND condition
953
-				if($parts > 1) {
954
-					$filter = '(&' . $filter . ')';
953
+				if ($parts > 1) {
954
+					$filter = '(&'.$filter.')';
955 955
 				}
956 956
 				break;
957 957
 
@@ -963,47 +963,47 @@  discard block
 block discarded – undo
963 963
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
964 964
 				$parts = 0;
965 965
 
966
-				if($this->configuration->ldapLoginFilterUsername === '1') {
966
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
967 967
 					$attr = '';
968
-					if(isset($userAttributes['uid'])) {
968
+					if (isset($userAttributes['uid'])) {
969 969
 						$attr = 'uid';
970
-					} else if(isset($userAttributes['samaccountname'])) {
970
+					} else if (isset($userAttributes['samaccountname'])) {
971 971
 						$attr = 'samaccountname';
972
-					} else if(isset($userAttributes['cn'])) {
972
+					} else if (isset($userAttributes['cn'])) {
973 973
 						//fallback
974 974
 						$attr = 'cn';
975 975
 					}
976 976
 					if ($attr !== '') {
977
-						$filterUsername = '(' . $attr . $loginpart . ')';
977
+						$filterUsername = '('.$attr.$loginpart.')';
978 978
 						$parts++;
979 979
 					}
980 980
 				}
981 981
 
982 982
 				$filterEmail = '';
983
-				if($this->configuration->ldapLoginFilterEmail === '1') {
983
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
984 984
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
985 985
 					$parts++;
986 986
 				}
987 987
 
988 988
 				$filterAttributes = '';
989 989
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
990
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
990
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
991 991
 					$filterAttributes = '(|';
992
-					foreach($attrsToFilter as $attribute) {
993
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
992
+					foreach ($attrsToFilter as $attribute) {
993
+						$filterAttributes .= '('.$attribute.$loginpart.')';
994 994
 					}
995 995
 					$filterAttributes .= ')';
996 996
 					$parts++;
997 997
 				}
998 998
 
999 999
 				$filterLogin = '';
1000
-				if($parts > 1) {
1000
+				if ($parts > 1) {
1001 1001
 					$filterLogin = '(|';
1002 1002
 				}
1003 1003
 				$filterLogin .= $filterUsername;
1004 1004
 				$filterLogin .= $filterEmail;
1005 1005
 				$filterLogin .= $filterAttributes;
1006
-				if($parts > 1) {
1006
+				if ($parts > 1) {
1007 1007
 					$filterLogin .= ')';
1008 1008
 				}
1009 1009
 
@@ -1025,7 +1025,7 @@  discard block
 block discarded – undo
1025 1025
 	 * @throws \Exception
1026 1026
 	 */
1027 1027
 	private function connectAndBind($port = 389, $tls = false, $ncc = false) {
1028
-		if($ncc) {
1028
+		if ($ncc) {
1029 1029
 			//No certificate check
1030 1030
 			//FIXME: undo afterwards
1031 1031
 			putenv('LDAPTLS_REQCERT=never');
@@ -1035,12 +1035,12 @@  discard block
 block discarded – undo
1035 1035
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Checking Host Info ', \OCP\Util::DEBUG);
1036 1036
 		$host = $this->configuration->ldapHost;
1037 1037
 		$hostInfo = parse_url($host);
1038
-		if(!$hostInfo) {
1038
+		if (!$hostInfo) {
1039 1039
 			throw new \Exception(self::$l->t('Invalid Host'));
1040 1040
 		}
1041 1041
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1042 1042
 		$cr = $this->ldap->connect($host, $port);
1043
-		if(!is_resource($cr)) {
1043
+		if (!is_resource($cr)) {
1044 1044
 			throw new \Exception(self::$l->t('Invalid Host'));
1045 1045
 		}
1046 1046
 
@@ -1051,9 +1051,9 @@  discard block
 block discarded – undo
1051 1051
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1052 1052
 
1053 1053
 		try {
1054
-			if($tls) {
1054
+			if ($tls) {
1055 1055
 				$isTlsWorking = @$this->ldap->startTls($cr);
1056
-				if(!$isTlsWorking) {
1056
+				if (!$isTlsWorking) {
1057 1057
 					return false;
1058 1058
 				}
1059 1059
 			}
@@ -1067,20 +1067,20 @@  discard block
 block discarded – undo
1067 1067
 			$errNo = $this->ldap->errno($cr);
1068 1068
 			$error = ldap_error($cr);
1069 1069
 			$this->ldap->unbind($cr);
1070
-		} catch(ServerNotAvailableException $e) {
1070
+		} catch (ServerNotAvailableException $e) {
1071 1071
 			return false;
1072 1072
 		}
1073 1073
 
1074
-		if($login === true) {
1074
+		if ($login === true) {
1075 1075
 			$this->ldap->unbind($cr);
1076
-			if($ncc) {
1076
+			if ($ncc) {
1077 1077
 				throw new \Exception('Certificate cannot be validated.');
1078 1078
 			}
1079
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . intval($tls), \OCP\Util::DEBUG);
1079
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.intval($tls), \OCP\Util::DEBUG);
1080 1080
 			return true;
1081 1081
 		}
1082 1082
 
1083
-		if($errNo === -1 || ($errNo === 2 && $ncc)) {
1083
+		if ($errNo === -1 || ($errNo === 2 && $ncc)) {
1084 1084
 			//host, port or TLS wrong
1085 1085
 			return false;
1086 1086
 		} else if ($errNo === 2) {
@@ -1110,9 +1110,9 @@  discard block
 block discarded – undo
1110 1110
 	 */
1111 1111
 	private function checkRequirements($reqs) {
1112 1112
 		$this->checkAgentRequirements();
1113
-		foreach($reqs as $option) {
1113
+		foreach ($reqs as $option) {
1114 1114
 			$value = $this->configuration->$option;
1115
-			if(empty($value)) {
1115
+			if (empty($value)) {
1116 1116
 				return false;
1117 1117
 			}
1118 1118
 		}
@@ -1134,33 +1134,33 @@  discard block
 block discarded – undo
1134 1134
 		$dnRead = array();
1135 1135
 		$foundItems = array();
1136 1136
 		$maxEntries = 0;
1137
-		if(!is_array($this->configuration->ldapBase)
1137
+		if (!is_array($this->configuration->ldapBase)
1138 1138
 		   || !isset($this->configuration->ldapBase[0])) {
1139 1139
 			return false;
1140 1140
 		}
1141 1141
 		$base = $this->configuration->ldapBase[0];
1142 1142
 		$cr = $this->getConnection();
1143
-		if(!$this->ldap->isResource($cr)) {
1143
+		if (!$this->ldap->isResource($cr)) {
1144 1144
 			return false;
1145 1145
 		}
1146 1146
 		$lastFilter = null;
1147
-		if(isset($filters[count($filters)-1])) {
1148
-			$lastFilter = $filters[count($filters)-1];
1147
+		if (isset($filters[count($filters) - 1])) {
1148
+			$lastFilter = $filters[count($filters) - 1];
1149 1149
 		}
1150
-		foreach($filters as $filter) {
1151
-			if($lastFilter === $filter && count($foundItems) > 0) {
1150
+		foreach ($filters as $filter) {
1151
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1152 1152
 				//skip when the filter is a wildcard and results were found
1153 1153
 				continue;
1154 1154
 			}
1155 1155
 			// 20k limit for performance and reason
1156 1156
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
-			if(!$this->ldap->isResource($rr)) {
1157
+			if (!$this->ldap->isResource($rr)) {
1158 1158
 				continue;
1159 1159
 			}
1160 1160
 			$entries = $this->ldap->countEntries($cr, $rr);
1161 1161
 			$getEntryFunc = 'firstEntry';
1162
-			if(($entries !== false) && ($entries > 0)) {
1163
-				if(!is_null($maxF) && $entries > $maxEntries) {
1162
+			if (($entries !== false) && ($entries > 0)) {
1163
+				if (!is_null($maxF) && $entries > $maxEntries) {
1164 1164
 					$maxEntries = $entries;
1165 1165
 					$maxF = $filter;
1166 1166
 				}
@@ -1168,13 +1168,13 @@  discard block
 block discarded – undo
1168 1168
 				do {
1169 1169
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1170 1170
 					$getEntryFunc = 'nextEntry';
1171
-					if(!$this->ldap->isResource($entry)) {
1171
+					if (!$this->ldap->isResource($entry)) {
1172 1172
 						continue 2;
1173 1173
 					}
1174 1174
 					$rr = $entry; //will be expected by nextEntry next round
1175 1175
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1176 1176
 					$dn = $this->ldap->getDN($cr, $entry);
1177
-					if($dn === false || in_array($dn, $dnRead)) {
1177
+					if ($dn === false || in_array($dn, $dnRead)) {
1178 1178
 						continue;
1179 1179
 					}
1180 1180
 					$newItems = array();
@@ -1185,7 +1185,7 @@  discard block
 block discarded – undo
1185 1185
 					$foundItems = array_merge($foundItems, $newItems);
1186 1186
 					$this->resultCache[$dn][$attr] = $newItems;
1187 1187
 					$dnRead[] = $dn;
1188
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1188
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1189 1189
 						|| $this->ldap->isResource($entry))
1190 1190
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191 1191
 			}
@@ -1208,11 +1208,11 @@  discard block
 block discarded – undo
1208 1208
 	 */
1209 1209
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210 1210
 		$cr = $this->getConnection();
1211
-		if(!$cr) {
1211
+		if (!$cr) {
1212 1212
 			throw new \Exception('Could not connect to LDAP');
1213 1213
 		}
1214 1214
 		$p = 'objectclass=';
1215
-		foreach($objectclasses as $key => $value) {
1215
+		foreach ($objectclasses as $key => $value) {
1216 1216
 			$objectclasses[$key] = $p.$value;
1217 1217
 		}
1218 1218
 		$maxEntryObjC = '';
@@ -1224,7 +1224,7 @@  discard block
 block discarded – undo
1224 1224
 		$availableFeatures =
1225 1225
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226 1226
 											   $dig, $maxEntryObjC);
1227
-		if(is_array($availableFeatures)
1227
+		if (is_array($availableFeatures)
1228 1228
 		   && count($availableFeatures) > 0) {
1229 1229
 			natcasesort($availableFeatures);
1230 1230
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
 		}
1236 1236
 
1237 1237
 		$setFeatures = $this->configuration->$confkey;
1238
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1238
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1239 1239
 			//something is already configured? pre-select it.
1240 1240
 			$this->result->addChange($dbkey, $setFeatures);
1241 1241
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1257,7 +1257,7 @@  discard block
 block discarded – undo
1257 1257
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258 1258
 	 */
1259 1259
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
-		if(!is_array($result)
1260
+		if (!is_array($result)
1261 1261
 		   || !isset($result['count'])
1262 1262
 		   || !$result['count'] > 0) {
1263 1263
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1266,12 +1266,12 @@  discard block
 block discarded – undo
1266 1266
 		// strtolower on all keys for proper comparison
1267 1267
 		$result = \OCP\Util::mb_array_change_key_case($result);
1268 1268
 		$attribute = strtolower($attribute);
1269
-		if(isset($result[$attribute])) {
1270
-			foreach($result[$attribute] as $key => $val) {
1271
-				if($key === 'count') {
1269
+		if (isset($result[$attribute])) {
1270
+			foreach ($result[$attribute] as $key => $val) {
1271
+				if ($key === 'count') {
1272 1272
 					continue;
1273 1273
 				}
1274
-				if(!in_array($val, $known)) {
1274
+				if (!in_array($val, $known)) {
1275 1275
 					$known[] = $val;
1276 1276
 				}
1277 1277
 			}
@@ -1285,7 +1285,7 @@  discard block
 block discarded – undo
1285 1285
 	 * @return bool|mixed
1286 1286
 	 */
1287 1287
 	private function getConnection() {
1288
-		if(!is_null($this->cr)) {
1288
+		if (!is_null($this->cr)) {
1289 1289
 			return $this->cr;
1290 1290
 		}
1291 1291
 
@@ -1297,14 +1297,14 @@  discard block
 block discarded – undo
1297 1297
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298 1298
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299 1299
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
-		if($this->configuration->ldapTLS === 1) {
1300
+		if ($this->configuration->ldapTLS === 1) {
1301 1301
 			$this->ldap->startTls($cr);
1302 1302
 		}
1303 1303
 
1304 1304
 		$lo = @$this->ldap->bind($cr,
1305 1305
 								 $this->configuration->ldapAgentName,
1306 1306
 								 $this->configuration->ldapAgentPassword);
1307
-		if($lo === true) {
1307
+		if ($lo === true) {
1308 1308
 			$this->$cr = $cr;
1309 1309
 			return $cr;
1310 1310
 		}
@@ -1339,14 +1339,14 @@  discard block
 block discarded – undo
1339 1339
 		$portSettings = array();
1340 1340
 
1341 1341
 		//In case the port is already provided, we will check this first
1342
-		if($port > 0) {
1342
+		if ($port > 0) {
1343 1343
 			$hostInfo = parse_url($host);
1344
-			if(!(is_array($hostInfo)
1344
+			if (!(is_array($hostInfo)
1345 1345
 				&& isset($hostInfo['scheme'])
1346 1346
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347 1347
 				$portSettings[] = array('port' => $port, 'tls' => true);
1348 1348
 			}
1349
-			$portSettings[] =array('port' => $port, 'tls' => false);
1349
+			$portSettings[] = array('port' => $port, 'tls' => false);
1350 1350
 		}
1351 1351
 
1352 1352
 		//default ports
Please login to merge, or discard this patch.
lib/private/legacy/db.php 3 patches
Doc Comments   -1 removed lines patch added patch discarded remove patch
@@ -151,7 +151,6 @@
 block discarded – undo
151 151
 	/**
152 152
 	 * saves database schema to xml file
153 153
 	 * @param string $file name of file
154
-	 * @param int $mode
155 154
 	 * @return bool
156 155
 	 *
157 156
 	 * TODO: write more documentation
Please login to merge, or discard this patch.
Indentation   +194 added lines, -194 removed lines patch added patch discarded remove patch
@@ -33,210 +33,210 @@
 block discarded – undo
33 33
  */
34 34
 class OC_DB {
35 35
 
36
-	/**
37
-	 * get MDB2 schema manager
38
-	 *
39
-	 * @return \OC\DB\MDB2SchemaManager
40
-	 */
41
-	private static function getMDB2SchemaManager() {
42
-		return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
43
-	}
36
+    /**
37
+     * get MDB2 schema manager
38
+     *
39
+     * @return \OC\DB\MDB2SchemaManager
40
+     */
41
+    private static function getMDB2SchemaManager() {
42
+        return new \OC\DB\MDB2SchemaManager(\OC::$server->getDatabaseConnection());
43
+    }
44 44
 
45
-	/**
46
-	 * Prepare a SQL query
47
-	 * @param string $query Query string
48
-	 * @param int $limit
49
-	 * @param int $offset
50
-	 * @param bool $isManipulation
51
-	 * @throws \OC\DatabaseException
52
-	 * @return OC_DB_StatementWrapper prepared SQL query
53
-	 *
54
-	 * SQL query via Doctrine prepare(), needs to be execute()'d!
55
-	 */
56
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
57
-		$connection = \OC::$server->getDatabaseConnection();
45
+    /**
46
+     * Prepare a SQL query
47
+     * @param string $query Query string
48
+     * @param int $limit
49
+     * @param int $offset
50
+     * @param bool $isManipulation
51
+     * @throws \OC\DatabaseException
52
+     * @return OC_DB_StatementWrapper prepared SQL query
53
+     *
54
+     * SQL query via Doctrine prepare(), needs to be execute()'d!
55
+     */
56
+    static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
57
+        $connection = \OC::$server->getDatabaseConnection();
58 58
 
59
-		if ($isManipulation === null) {
60
-			//try to guess, so we return the number of rows on manipulations
61
-			$isManipulation = self::isManipulation($query);
62
-		}
59
+        if ($isManipulation === null) {
60
+            //try to guess, so we return the number of rows on manipulations
61
+            $isManipulation = self::isManipulation($query);
62
+        }
63 63
 
64
-		// return the result
65
-		try {
66
-			$result =$connection->prepare($query, $limit, $offset);
67
-		} catch (\Doctrine\DBAL\DBALException $e) {
68
-			throw new \OC\DatabaseException($e->getMessage(), $query);
69
-		}
70
-		// differentiate between query and manipulation
71
-		$result = new OC_DB_StatementWrapper($result, $isManipulation);
72
-		return $result;
73
-	}
64
+        // return the result
65
+        try {
66
+            $result =$connection->prepare($query, $limit, $offset);
67
+        } catch (\Doctrine\DBAL\DBALException $e) {
68
+            throw new \OC\DatabaseException($e->getMessage(), $query);
69
+        }
70
+        // differentiate between query and manipulation
71
+        $result = new OC_DB_StatementWrapper($result, $isManipulation);
72
+        return $result;
73
+    }
74 74
 
75
-	/**
76
-	 * tries to guess the type of statement based on the first 10 characters
77
-	 * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
78
-	 *
79
-	 * @param string $sql
80
-	 * @return bool
81
-	 */
82
-	static public function isManipulation( $sql ) {
83
-		$selectOccurrence = stripos($sql, 'SELECT');
84
-		if ($selectOccurrence !== false && $selectOccurrence < 10) {
85
-			return false;
86
-		}
87
-		$insertOccurrence = stripos($sql, 'INSERT');
88
-		if ($insertOccurrence !== false && $insertOccurrence < 10) {
89
-			return true;
90
-		}
91
-		$updateOccurrence = stripos($sql, 'UPDATE');
92
-		if ($updateOccurrence !== false && $updateOccurrence < 10) {
93
-			return true;
94
-		}
95
-		$deleteOccurrence = stripos($sql, 'DELETE');
96
-		if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
97
-			return true;
98
-		}
99
-		return false;
100
-	}
75
+    /**
76
+     * tries to guess the type of statement based on the first 10 characters
77
+     * the current check allows some whitespace but does not work with IF EXISTS or other more complex statements
78
+     *
79
+     * @param string $sql
80
+     * @return bool
81
+     */
82
+    static public function isManipulation( $sql ) {
83
+        $selectOccurrence = stripos($sql, 'SELECT');
84
+        if ($selectOccurrence !== false && $selectOccurrence < 10) {
85
+            return false;
86
+        }
87
+        $insertOccurrence = stripos($sql, 'INSERT');
88
+        if ($insertOccurrence !== false && $insertOccurrence < 10) {
89
+            return true;
90
+        }
91
+        $updateOccurrence = stripos($sql, 'UPDATE');
92
+        if ($updateOccurrence !== false && $updateOccurrence < 10) {
93
+            return true;
94
+        }
95
+        $deleteOccurrence = stripos($sql, 'DELETE');
96
+        if ($deleteOccurrence !== false && $deleteOccurrence < 10) {
97
+            return true;
98
+        }
99
+        return false;
100
+    }
101 101
 
102
-	/**
103
-	 * execute a prepared statement, on error write log and throw exception
104
-	 * @param mixed $stmt OC_DB_StatementWrapper,
105
-	 *					  an array with 'sql' and optionally 'limit' and 'offset' keys
106
-	 *					.. or a simple sql query string
107
-	 * @param array $parameters
108
-	 * @return OC_DB_StatementWrapper
109
-	 * @throws \OC\DatabaseException
110
-	 */
111
-	static public function executeAudited( $stmt, array $parameters = null) {
112
-		if (is_string($stmt)) {
113
-			// convert to an array with 'sql'
114
-			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
115
-				// TODO try to convert LIMIT OFFSET notation to parameters
116
-				$message = 'LIMIT and OFFSET are forbidden for portability reasons,'
117
-						 . ' pass an array with \'limit\' and \'offset\' instead';
118
-				throw new \OC\DatabaseException($message);
119
-			}
120
-			$stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
121
-		}
122
-		if (is_array($stmt)) {
123
-			// convert to prepared statement
124
-			if ( ! array_key_exists('sql', $stmt) ) {
125
-				$message = 'statement array must at least contain key \'sql\'';
126
-				throw new \OC\DatabaseException($message);
127
-			}
128
-			if ( ! array_key_exists('limit', $stmt) ) {
129
-				$stmt['limit'] = null;
130
-			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
132
-				$stmt['offset'] = null;
133
-			}
134
-			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
135
-		}
136
-		self::raiseExceptionOnError($stmt, 'Could not prepare statement');
137
-		if ($stmt instanceof OC_DB_StatementWrapper) {
138
-			$result = $stmt->execute($parameters);
139
-			self::raiseExceptionOnError($result, 'Could not execute statement');
140
-		} else {
141
-			if (is_object($stmt)) {
142
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
143
-			} else {
144
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
145
-			}
146
-			throw new \OC\DatabaseException($message);
147
-		}
148
-		return $result;
149
-	}
102
+    /**
103
+     * execute a prepared statement, on error write log and throw exception
104
+     * @param mixed $stmt OC_DB_StatementWrapper,
105
+     *					  an array with 'sql' and optionally 'limit' and 'offset' keys
106
+     *					.. or a simple sql query string
107
+     * @param array $parameters
108
+     * @return OC_DB_StatementWrapper
109
+     * @throws \OC\DatabaseException
110
+     */
111
+    static public function executeAudited( $stmt, array $parameters = null) {
112
+        if (is_string($stmt)) {
113
+            // convert to an array with 'sql'
114
+            if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
115
+                // TODO try to convert LIMIT OFFSET notation to parameters
116
+                $message = 'LIMIT and OFFSET are forbidden for portability reasons,'
117
+                            . ' pass an array with \'limit\' and \'offset\' instead';
118
+                throw new \OC\DatabaseException($message);
119
+            }
120
+            $stmt = array('sql' => $stmt, 'limit' => null, 'offset' => null);
121
+        }
122
+        if (is_array($stmt)) {
123
+            // convert to prepared statement
124
+            if ( ! array_key_exists('sql', $stmt) ) {
125
+                $message = 'statement array must at least contain key \'sql\'';
126
+                throw new \OC\DatabaseException($message);
127
+            }
128
+            if ( ! array_key_exists('limit', $stmt) ) {
129
+                $stmt['limit'] = null;
130
+            }
131
+            if ( ! array_key_exists('limit', $stmt) ) {
132
+                $stmt['offset'] = null;
133
+            }
134
+            $stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
135
+        }
136
+        self::raiseExceptionOnError($stmt, 'Could not prepare statement');
137
+        if ($stmt instanceof OC_DB_StatementWrapper) {
138
+            $result = $stmt->execute($parameters);
139
+            self::raiseExceptionOnError($result, 'Could not execute statement');
140
+        } else {
141
+            if (is_object($stmt)) {
142
+                $message = 'Expected a prepared statement or array got ' . get_class($stmt);
143
+            } else {
144
+                $message = 'Expected a prepared statement or array got ' . gettype($stmt);
145
+            }
146
+            throw new \OC\DatabaseException($message);
147
+        }
148
+        return $result;
149
+    }
150 150
 
151
-	/**
152
-	 * saves database schema to xml file
153
-	 * @param string $file name of file
154
-	 * @param int $mode
155
-	 * @return bool
156
-	 *
157
-	 * TODO: write more documentation
158
-	 */
159
-	public static function getDbStructure($file) {
160
-		$schemaManager = self::getMDB2SchemaManager();
161
-		return $schemaManager->getDbStructure($file);
162
-	}
151
+    /**
152
+     * saves database schema to xml file
153
+     * @param string $file name of file
154
+     * @param int $mode
155
+     * @return bool
156
+     *
157
+     * TODO: write more documentation
158
+     */
159
+    public static function getDbStructure($file) {
160
+        $schemaManager = self::getMDB2SchemaManager();
161
+        return $schemaManager->getDbStructure($file);
162
+    }
163 163
 
164
-	/**
165
-	 * Creates tables from XML file
166
-	 * @param string $file file to read structure from
167
-	 * @return bool
168
-	 *
169
-	 * TODO: write more documentation
170
-	 */
171
-	public static function createDbFromStructure( $file ) {
172
-		$schemaManager = self::getMDB2SchemaManager();
173
-		$result = $schemaManager->createDbFromStructure($file);
174
-		return $result;
175
-	}
164
+    /**
165
+     * Creates tables from XML file
166
+     * @param string $file file to read structure from
167
+     * @return bool
168
+     *
169
+     * TODO: write more documentation
170
+     */
171
+    public static function createDbFromStructure( $file ) {
172
+        $schemaManager = self::getMDB2SchemaManager();
173
+        $result = $schemaManager->createDbFromStructure($file);
174
+        return $result;
175
+    }
176 176
 
177
-	/**
178
-	 * update the database schema
179
-	 * @param string $file file to read structure from
180
-	 * @throws Exception
181
-	 * @return string|boolean
182
-	 */
183
-	public static function updateDbFromStructure($file) {
184
-		$schemaManager = self::getMDB2SchemaManager();
185
-		try {
186
-			$result = $schemaManager->updateDbFromStructure($file);
187
-		} catch (Exception $e) {
188
-			\OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
189
-			throw $e;
190
-		}
191
-		return $result;
192
-	}
177
+    /**
178
+     * update the database schema
179
+     * @param string $file file to read structure from
180
+     * @throws Exception
181
+     * @return string|boolean
182
+     */
183
+    public static function updateDbFromStructure($file) {
184
+        $schemaManager = self::getMDB2SchemaManager();
185
+        try {
186
+            $result = $schemaManager->updateDbFromStructure($file);
187
+        } catch (Exception $e) {
188
+            \OCP\Util::writeLog('core', 'Failed to update database structure ('.$e.')', \OCP\Util::FATAL);
189
+            throw $e;
190
+        }
191
+        return $result;
192
+    }
193 193
 
194
-	/**
195
-	 * remove all tables defined in a database structure xml file
196
-	 * @param string $file the xml file describing the tables
197
-	 */
198
-	public static function removeDBStructure($file) {
199
-		$schemaManager = self::getMDB2SchemaManager();
200
-		$schemaManager->removeDBStructure($file);
201
-	}
194
+    /**
195
+     * remove all tables defined in a database structure xml file
196
+     * @param string $file the xml file describing the tables
197
+     */
198
+    public static function removeDBStructure($file) {
199
+        $schemaManager = self::getMDB2SchemaManager();
200
+        $schemaManager->removeDBStructure($file);
201
+    }
202 202
 
203
-	/**
204
-	 * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
205
-	 * @param mixed $result
206
-	 * @param string $message
207
-	 * @return void
208
-	 * @throws \OC\DatabaseException
209
-	 */
210
-	public static function raiseExceptionOnError($result, $message = null) {
211
-		if($result === false) {
212
-			if ($message === null) {
213
-				$message = self::getErrorMessage();
214
-			} else {
215
-				$message .= ', Root cause:' . self::getErrorMessage();
216
-			}
217
-			throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
218
-		}
219
-	}
203
+    /**
204
+     * check if a result is an error and throws an exception, works with \Doctrine\DBAL\DBALException
205
+     * @param mixed $result
206
+     * @param string $message
207
+     * @return void
208
+     * @throws \OC\DatabaseException
209
+     */
210
+    public static function raiseExceptionOnError($result, $message = null) {
211
+        if($result === false) {
212
+            if ($message === null) {
213
+                $message = self::getErrorMessage();
214
+            } else {
215
+                $message .= ', Root cause:' . self::getErrorMessage();
216
+            }
217
+            throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
218
+        }
219
+    }
220 220
 
221
-	/**
222
-	 * returns the error code and message as a string for logging
223
-	 * works with DoctrineException
224
-	 * @return string
225
-	 */
226
-	public static function getErrorMessage() {
227
-		$connection = \OC::$server->getDatabaseConnection();
228
-		return $connection->getError();
229
-	}
221
+    /**
222
+     * returns the error code and message as a string for logging
223
+     * works with DoctrineException
224
+     * @return string
225
+     */
226
+    public static function getErrorMessage() {
227
+        $connection = \OC::$server->getDatabaseConnection();
228
+        return $connection->getError();
229
+    }
230 230
 
231
-	/**
232
-	 * Checks if a table exists in the database - the database prefix will be prepended
233
-	 *
234
-	 * @param string $table
235
-	 * @return bool
236
-	 * @throws \OC\DatabaseException
237
-	 */
238
-	public static function tableExists($table) {
239
-		$connection = \OC::$server->getDatabaseConnection();
240
-		return $connection->tableExists($table);
241
-	}
231
+    /**
232
+     * Checks if a table exists in the database - the database prefix will be prepended
233
+     *
234
+     * @param string $table
235
+     * @return bool
236
+     * @throws \OC\DatabaseException
237
+     */
238
+    public static function tableExists($table) {
239
+        $connection = \OC::$server->getDatabaseConnection();
240
+        return $connection->tableExists($table);
241
+    }
242 242
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 *
54 54
 	 * SQL query via Doctrine prepare(), needs to be execute()'d!
55 55
 	 */
56
-	static public function prepare( $query , $limit = null, $offset = null, $isManipulation = null) {
56
+	static public function prepare($query, $limit = null, $offset = null, $isManipulation = null) {
57 57
 		$connection = \OC::$server->getDatabaseConnection();
58 58
 
59 59
 		if ($isManipulation === null) {
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 
64 64
 		// return the result
65 65
 		try {
66
-			$result =$connection->prepare($query, $limit, $offset);
66
+			$result = $connection->prepare($query, $limit, $offset);
67 67
 		} catch (\Doctrine\DBAL\DBALException $e) {
68 68
 			throw new \OC\DatabaseException($e->getMessage(), $query);
69 69
 		}
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	 * @param string $sql
80 80
 	 * @return bool
81 81
 	 */
82
-	static public function isManipulation( $sql ) {
82
+	static public function isManipulation($sql) {
83 83
 		$selectOccurrence = stripos($sql, 'SELECT');
84 84
 		if ($selectOccurrence !== false && $selectOccurrence < 10) {
85 85
 			return false;
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	 * @return OC_DB_StatementWrapper
109 109
 	 * @throws \OC\DatabaseException
110 110
 	 */
111
-	static public function executeAudited( $stmt, array $parameters = null) {
111
+	static public function executeAudited($stmt, array $parameters = null) {
112 112
 		if (is_string($stmt)) {
113 113
 			// convert to an array with 'sql'
114 114
 			if (stripos($stmt, 'LIMIT') !== false) { //OFFSET requires LIMIT, so we only need to check for LIMIT
@@ -121,14 +121,14 @@  discard block
 block discarded – undo
121 121
 		}
122 122
 		if (is_array($stmt)) {
123 123
 			// convert to prepared statement
124
-			if ( ! array_key_exists('sql', $stmt) ) {
124
+			if (!array_key_exists('sql', $stmt)) {
125 125
 				$message = 'statement array must at least contain key \'sql\'';
126 126
 				throw new \OC\DatabaseException($message);
127 127
 			}
128
-			if ( ! array_key_exists('limit', $stmt) ) {
128
+			if (!array_key_exists('limit', $stmt)) {
129 129
 				$stmt['limit'] = null;
130 130
 			}
131
-			if ( ! array_key_exists('limit', $stmt) ) {
131
+			if (!array_key_exists('limit', $stmt)) {
132 132
 				$stmt['offset'] = null;
133 133
 			}
134 134
 			$stmt = self::prepare($stmt['sql'], $stmt['limit'], $stmt['offset']);
@@ -139,9 +139,9 @@  discard block
 block discarded – undo
139 139
 			self::raiseExceptionOnError($result, 'Could not execute statement');
140 140
 		} else {
141 141
 			if (is_object($stmt)) {
142
-				$message = 'Expected a prepared statement or array got ' . get_class($stmt);
142
+				$message = 'Expected a prepared statement or array got '.get_class($stmt);
143 143
 			} else {
144
-				$message = 'Expected a prepared statement or array got ' . gettype($stmt);
144
+				$message = 'Expected a prepared statement or array got '.gettype($stmt);
145 145
 			}
146 146
 			throw new \OC\DatabaseException($message);
147 147
 		}
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 	 *
169 169
 	 * TODO: write more documentation
170 170
 	 */
171
-	public static function createDbFromStructure( $file ) {
171
+	public static function createDbFromStructure($file) {
172 172
 		$schemaManager = self::getMDB2SchemaManager();
173 173
 		$result = $schemaManager->createDbFromStructure($file);
174 174
 		return $result;
@@ -208,11 +208,11 @@  discard block
 block discarded – undo
208 208
 	 * @throws \OC\DatabaseException
209 209
 	 */
210 210
 	public static function raiseExceptionOnError($result, $message = null) {
211
-		if($result === false) {
211
+		if ($result === false) {
212 212
 			if ($message === null) {
213 213
 				$message = self::getErrorMessage();
214 214
 			} else {
215
-				$message .= ', Root cause:' . self::getErrorMessage();
215
+				$message .= ', Root cause:'.self::getErrorMessage();
216 216
 			}
217 217
 			throw new \OC\DatabaseException($message, \OC::$server->getDatabaseConnection()->errorCode());
218 218
 		}
Please login to merge, or discard this patch.
lib/private/User/User.php 3 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -413,6 +413,10 @@
 block discarded – undo
413 413
 		return $url;
414 414
 	}
415 415
 
416
+	/**
417
+	 * @param string $feature
418
+	 * @param string $value
419
+	 */
416 420
 	public function triggerChange($feature, $value = null) {
417 421
 		if ($this->emitter) {
418 422
 			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
Please login to merge, or discard this patch.
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -42,396 +42,396 @@
 block discarded – undo
42 42
 use \OCP\IUserBackend;
43 43
 
44 44
 class User implements IUser {
45
-	/** @var string $uid */
46
-	private $uid;
47
-
48
-	/** @var string $displayName */
49
-	private $displayName;
50
-
51
-	/** @var UserInterface $backend */
52
-	private $backend;
53
-
54
-	/** @var bool $enabled */
55
-	private $enabled;
56
-
57
-	/** @var Emitter|Manager $emitter */
58
-	private $emitter;
59
-
60
-	/** @var string $home */
61
-	private $home;
62
-
63
-	/** @var int $lastLogin */
64
-	private $lastLogin;
65
-
66
-	/** @var \OCP\IConfig $config */
67
-	private $config;
68
-
69
-	/** @var IAvatarManager */
70
-	private $avatarManager;
71
-
72
-	/** @var IURLGenerator */
73
-	private $urlGenerator;
74
-
75
-	/**
76
-	 * @param string $uid
77
-	 * @param UserInterface $backend
78
-	 * @param \OC\Hooks\Emitter $emitter
79
-	 * @param IConfig|null $config
80
-	 * @param IURLGenerator $urlGenerator
81
-	 */
82
-	public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
83
-		$this->uid = $uid;
84
-		$this->backend = $backend;
85
-		$this->emitter = $emitter;
86
-		if(is_null($config)) {
87
-			$config = \OC::$server->getConfig();
88
-		}
89
-		$this->config = $config;
90
-		$this->urlGenerator = $urlGenerator;
91
-		$enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
92
-		$this->enabled = ($enabled === 'true');
93
-		$this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
94
-		if (is_null($this->urlGenerator)) {
95
-			$this->urlGenerator = \OC::$server->getURLGenerator();
96
-		}
97
-	}
98
-
99
-	/**
100
-	 * get the user id
101
-	 *
102
-	 * @return string
103
-	 */
104
-	public function getUID() {
105
-		return $this->uid;
106
-	}
107
-
108
-	/**
109
-	 * get the display name for the user, if no specific display name is set it will fallback to the user id
110
-	 *
111
-	 * @return string
112
-	 */
113
-	public function getDisplayName() {
114
-		if (!isset($this->displayName)) {
115
-			$displayName = '';
116
-			if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
117
-				// get display name and strip whitespace from the beginning and end of it
118
-				$backendDisplayName = $this->backend->getDisplayName($this->uid);
119
-				if (is_string($backendDisplayName)) {
120
-					$displayName = trim($backendDisplayName);
121
-				}
122
-			}
123
-
124
-			if (!empty($displayName)) {
125
-				$this->displayName = $displayName;
126
-			} else {
127
-				$this->displayName = $this->uid;
128
-			}
129
-		}
130
-		return $this->displayName;
131
-	}
132
-
133
-	/**
134
-	 * set the displayname for the user
135
-	 *
136
-	 * @param string $displayName
137
-	 * @return bool
138
-	 */
139
-	public function setDisplayName($displayName) {
140
-		$displayName = trim($displayName);
141
-		if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) {
142
-			$result = $this->backend->setDisplayName($this->uid, $displayName);
143
-			if ($result) {
144
-				$this->displayName = $displayName;
145
-				$this->triggerChange('displayName', $displayName);
146
-			}
147
-			return $result !== false;
148
-		} else {
149
-			return false;
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * set the email address of the user
155
-	 *
156
-	 * @param string|null $mailAddress
157
-	 * @return void
158
-	 * @since 9.0.0
159
-	 */
160
-	public function setEMailAddress($mailAddress) {
161
-		if($mailAddress === '') {
162
-			$this->config->deleteUserValue($this->uid, 'settings', 'email');
163
-		} else {
164
-			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
165
-		}
166
-		$this->triggerChange('eMailAddress', $mailAddress);
167
-	}
168
-
169
-	/**
170
-	 * returns the timestamp of the user's last login or 0 if the user did never
171
-	 * login
172
-	 *
173
-	 * @return int
174
-	 */
175
-	public function getLastLogin() {
176
-		return $this->lastLogin;
177
-	}
178
-
179
-	/**
180
-	 * updates the timestamp of the most recent login of this user
181
-	 */
182
-	public function updateLastLoginTimestamp() {
183
-		$firstTimeLogin = ($this->lastLogin === 0);
184
-		$this->lastLogin = time();
185
-		$this->config->setUserValue(
186
-			$this->uid, 'login', 'lastLogin', $this->lastLogin);
187
-
188
-		return $firstTimeLogin;
189
-	}
190
-
191
-	/**
192
-	 * Delete the user
193
-	 *
194
-	 * @return bool
195
-	 */
196
-	public function delete() {
197
-		if ($this->emitter) {
198
-			$this->emitter->emit('\OC\User', 'preDelete', array($this));
199
-		}
200
-		// get the home now because it won't return it after user deletion
201
-		$homePath = $this->getHome();
202
-		$result = $this->backend->deleteUser($this->uid);
203
-		if ($result) {
204
-
205
-			// FIXME: Feels like an hack - suggestions?
206
-
207
-			// We have to delete the user from all groups
208
-			foreach (\OC::$server->getGroupManager()->getUserGroupIds($this) as $groupId) {
209
-				\OC_Group::removeFromGroup($this->uid, $groupId);
210
-			}
211
-			// Delete the user's keys in preferences
212
-			\OC::$server->getConfig()->deleteAllUserValues($this->uid);
213
-
214
-			// Delete user files in /data/
215
-			if ($homePath !== false) {
216
-				// FIXME: this operates directly on FS, should use View instead...
217
-				// also this is not testable/mockable...
218
-				\OC_Helper::rmdirr($homePath);
219
-			}
220
-
221
-			// Delete the users entry in the storage table
222
-			Storage::remove('home::' . $this->uid);
223
-
224
-			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
225
-			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
226
-
227
-			$notification = \OC::$server->getNotificationManager()->createNotification();
228
-			$notification->setUser($this->uid);
229
-			\OC::$server->getNotificationManager()->markProcessed($notification);
230
-
231
-			if ($this->emitter) {
232
-				$this->emitter->emit('\OC\User', 'postDelete', array($this));
233
-			}
234
-		}
235
-		return !($result === false);
236
-	}
237
-
238
-	/**
239
-	 * Set the password of the user
240
-	 *
241
-	 * @param string $password
242
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
243
-	 * @return bool
244
-	 */
245
-	public function setPassword($password, $recoveryPassword = null) {
246
-		if ($this->emitter) {
247
-			$this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
248
-		}
249
-		if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
250
-			$result = $this->backend->setPassword($this->uid, $password);
251
-			if ($this->emitter) {
252
-				$this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
253
-			}
254
-			return !($result === false);
255
-		} else {
256
-			return false;
257
-		}
258
-	}
259
-
260
-	/**
261
-	 * get the users home folder to mount
262
-	 *
263
-	 * @return string
264
-	 */
265
-	public function getHome() {
266
-		if (!$this->home) {
267
-			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
268
-				$this->home = $home;
269
-			} elseif ($this->config) {
270
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
271
-			} else {
272
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
273
-			}
274
-		}
275
-		return $this->home;
276
-	}
277
-
278
-	/**
279
-	 * Get the name of the backend class the user is connected with
280
-	 *
281
-	 * @return string
282
-	 */
283
-	public function getBackendClassName() {
284
-		if($this->backend instanceof IUserBackend) {
285
-			return $this->backend->getBackendName();
286
-		}
287
-		return get_class($this->backend);
288
-	}
289
-
290
-	/**
291
-	 * check if the backend allows the user to change his avatar on Personal page
292
-	 *
293
-	 * @return bool
294
-	 */
295
-	public function canChangeAvatar() {
296
-		if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
297
-			return $this->backend->canChangeAvatar($this->uid);
298
-		}
299
-		return true;
300
-	}
301
-
302
-	/**
303
-	 * check if the backend supports changing passwords
304
-	 *
305
-	 * @return bool
306
-	 */
307
-	public function canChangePassword() {
308
-		return $this->backend->implementsActions(Backend::SET_PASSWORD);
309
-	}
310
-
311
-	/**
312
-	 * check if the backend supports changing display names
313
-	 *
314
-	 * @return bool
315
-	 */
316
-	public function canChangeDisplayName() {
317
-		if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
318
-			return false;
319
-		}
320
-		return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
321
-	}
322
-
323
-	/**
324
-	 * check if the user is enabled
325
-	 *
326
-	 * @return bool
327
-	 */
328
-	public function isEnabled() {
329
-		return $this->enabled;
330
-	}
331
-
332
-	/**
333
-	 * set the enabled status for the user
334
-	 *
335
-	 * @param bool $enabled
336
-	 */
337
-	public function setEnabled($enabled) {
338
-		$this->enabled = $enabled;
339
-		$enabled = ($enabled) ? 'true' : 'false';
340
-		$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
341
-	}
342
-
343
-	/**
344
-	 * get the users email address
345
-	 *
346
-	 * @return string|null
347
-	 * @since 9.0.0
348
-	 */
349
-	public function getEMailAddress() {
350
-		return $this->config->getUserValue($this->uid, 'settings', 'email', null);
351
-	}
352
-
353
-	/**
354
-	 * get the users' quota
355
-	 *
356
-	 * @return string
357
-	 * @since 9.0.0
358
-	 */
359
-	public function getQuota() {
360
-		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
361
-		if($quota === 'default') {
362
-			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
363
-		}
364
-		return $quota;
365
-	}
366
-
367
-	/**
368
-	 * set the users' quota
369
-	 *
370
-	 * @param string $quota
371
-	 * @return void
372
-	 * @since 9.0.0
373
-	 */
374
-	public function setQuota($quota) {
375
-		if($quota !== 'none' and $quota !== 'default') {
376
-			$quota = OC_Helper::computerFileSize($quota);
377
-			$quota = OC_Helper::humanFileSize($quota);
378
-		}
379
-		$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
380
-		$this->triggerChange('quota', $quota);
381
-	}
382
-
383
-	/**
384
-	 * get the avatar image if it exists
385
-	 *
386
-	 * @param int $size
387
-	 * @return IImage|null
388
-	 * @since 9.0.0
389
-	 */
390
-	public function getAvatarImage($size) {
391
-		// delay the initialization
392
-		if (is_null($this->avatarManager)) {
393
-			$this->avatarManager = \OC::$server->getAvatarManager();
394
-		}
395
-
396
-		$avatar = $this->avatarManager->getAvatar($this->uid);
397
-		$image = $avatar->get(-1);
398
-		if ($image) {
399
-			return $image;
400
-		}
401
-
402
-		return null;
403
-	}
404
-
405
-	/**
406
-	 * get the federation cloud id
407
-	 *
408
-	 * @return string
409
-	 * @since 9.0.0
410
-	 */
411
-	public function getCloudId() {
412
-		$uid = $this->getUID();
413
-		$server = $this->urlGenerator->getAbsoluteURL('/');
414
-		$server =  rtrim( $this->removeProtocolFromUrl($server), '/');
415
-		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
416
-	}
417
-
418
-	/**
419
-	 * @param string $url
420
-	 * @return string
421
-	 */
422
-	private function removeProtocolFromUrl($url) {
423
-		if (strpos($url, 'https://') === 0) {
424
-			return substr($url, strlen('https://'));
425
-		} else if (strpos($url, 'http://') === 0) {
426
-			return substr($url, strlen('http://'));
427
-		}
428
-
429
-		return $url;
430
-	}
431
-
432
-	public function triggerChange($feature, $value = null) {
433
-		if ($this->emitter) {
434
-			$this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
435
-		}
436
-	}
45
+    /** @var string $uid */
46
+    private $uid;
47
+
48
+    /** @var string $displayName */
49
+    private $displayName;
50
+
51
+    /** @var UserInterface $backend */
52
+    private $backend;
53
+
54
+    /** @var bool $enabled */
55
+    private $enabled;
56
+
57
+    /** @var Emitter|Manager $emitter */
58
+    private $emitter;
59
+
60
+    /** @var string $home */
61
+    private $home;
62
+
63
+    /** @var int $lastLogin */
64
+    private $lastLogin;
65
+
66
+    /** @var \OCP\IConfig $config */
67
+    private $config;
68
+
69
+    /** @var IAvatarManager */
70
+    private $avatarManager;
71
+
72
+    /** @var IURLGenerator */
73
+    private $urlGenerator;
74
+
75
+    /**
76
+     * @param string $uid
77
+     * @param UserInterface $backend
78
+     * @param \OC\Hooks\Emitter $emitter
79
+     * @param IConfig|null $config
80
+     * @param IURLGenerator $urlGenerator
81
+     */
82
+    public function __construct($uid, $backend, $emitter = null, IConfig $config = null, $urlGenerator = null) {
83
+        $this->uid = $uid;
84
+        $this->backend = $backend;
85
+        $this->emitter = $emitter;
86
+        if(is_null($config)) {
87
+            $config = \OC::$server->getConfig();
88
+        }
89
+        $this->config = $config;
90
+        $this->urlGenerator = $urlGenerator;
91
+        $enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true');
92
+        $this->enabled = ($enabled === 'true');
93
+        $this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0);
94
+        if (is_null($this->urlGenerator)) {
95
+            $this->urlGenerator = \OC::$server->getURLGenerator();
96
+        }
97
+    }
98
+
99
+    /**
100
+     * get the user id
101
+     *
102
+     * @return string
103
+     */
104
+    public function getUID() {
105
+        return $this->uid;
106
+    }
107
+
108
+    /**
109
+     * get the display name for the user, if no specific display name is set it will fallback to the user id
110
+     *
111
+     * @return string
112
+     */
113
+    public function getDisplayName() {
114
+        if (!isset($this->displayName)) {
115
+            $displayName = '';
116
+            if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
117
+                // get display name and strip whitespace from the beginning and end of it
118
+                $backendDisplayName = $this->backend->getDisplayName($this->uid);
119
+                if (is_string($backendDisplayName)) {
120
+                    $displayName = trim($backendDisplayName);
121
+                }
122
+            }
123
+
124
+            if (!empty($displayName)) {
125
+                $this->displayName = $displayName;
126
+            } else {
127
+                $this->displayName = $this->uid;
128
+            }
129
+        }
130
+        return $this->displayName;
131
+    }
132
+
133
+    /**
134
+     * set the displayname for the user
135
+     *
136
+     * @param string $displayName
137
+     * @return bool
138
+     */
139
+    public function setDisplayName($displayName) {
140
+        $displayName = trim($displayName);
141
+        if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) {
142
+            $result = $this->backend->setDisplayName($this->uid, $displayName);
143
+            if ($result) {
144
+                $this->displayName = $displayName;
145
+                $this->triggerChange('displayName', $displayName);
146
+            }
147
+            return $result !== false;
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152
+
153
+    /**
154
+     * set the email address of the user
155
+     *
156
+     * @param string|null $mailAddress
157
+     * @return void
158
+     * @since 9.0.0
159
+     */
160
+    public function setEMailAddress($mailAddress) {
161
+        if($mailAddress === '') {
162
+            $this->config->deleteUserValue($this->uid, 'settings', 'email');
163
+        } else {
164
+            $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
165
+        }
166
+        $this->triggerChange('eMailAddress', $mailAddress);
167
+    }
168
+
169
+    /**
170
+     * returns the timestamp of the user's last login or 0 if the user did never
171
+     * login
172
+     *
173
+     * @return int
174
+     */
175
+    public function getLastLogin() {
176
+        return $this->lastLogin;
177
+    }
178
+
179
+    /**
180
+     * updates the timestamp of the most recent login of this user
181
+     */
182
+    public function updateLastLoginTimestamp() {
183
+        $firstTimeLogin = ($this->lastLogin === 0);
184
+        $this->lastLogin = time();
185
+        $this->config->setUserValue(
186
+            $this->uid, 'login', 'lastLogin', $this->lastLogin);
187
+
188
+        return $firstTimeLogin;
189
+    }
190
+
191
+    /**
192
+     * Delete the user
193
+     *
194
+     * @return bool
195
+     */
196
+    public function delete() {
197
+        if ($this->emitter) {
198
+            $this->emitter->emit('\OC\User', 'preDelete', array($this));
199
+        }
200
+        // get the home now because it won't return it after user deletion
201
+        $homePath = $this->getHome();
202
+        $result = $this->backend->deleteUser($this->uid);
203
+        if ($result) {
204
+
205
+            // FIXME: Feels like an hack - suggestions?
206
+
207
+            // We have to delete the user from all groups
208
+            foreach (\OC::$server->getGroupManager()->getUserGroupIds($this) as $groupId) {
209
+                \OC_Group::removeFromGroup($this->uid, $groupId);
210
+            }
211
+            // Delete the user's keys in preferences
212
+            \OC::$server->getConfig()->deleteAllUserValues($this->uid);
213
+
214
+            // Delete user files in /data/
215
+            if ($homePath !== false) {
216
+                // FIXME: this operates directly on FS, should use View instead...
217
+                // also this is not testable/mockable...
218
+                \OC_Helper::rmdirr($homePath);
219
+            }
220
+
221
+            // Delete the users entry in the storage table
222
+            Storage::remove('home::' . $this->uid);
223
+
224
+            \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
225
+            \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
226
+
227
+            $notification = \OC::$server->getNotificationManager()->createNotification();
228
+            $notification->setUser($this->uid);
229
+            \OC::$server->getNotificationManager()->markProcessed($notification);
230
+
231
+            if ($this->emitter) {
232
+                $this->emitter->emit('\OC\User', 'postDelete', array($this));
233
+            }
234
+        }
235
+        return !($result === false);
236
+    }
237
+
238
+    /**
239
+     * Set the password of the user
240
+     *
241
+     * @param string $password
242
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
243
+     * @return bool
244
+     */
245
+    public function setPassword($password, $recoveryPassword = null) {
246
+        if ($this->emitter) {
247
+            $this->emitter->emit('\OC\User', 'preSetPassword', array($this, $password, $recoveryPassword));
248
+        }
249
+        if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
250
+            $result = $this->backend->setPassword($this->uid, $password);
251
+            if ($this->emitter) {
252
+                $this->emitter->emit('\OC\User', 'postSetPassword', array($this, $password, $recoveryPassword));
253
+            }
254
+            return !($result === false);
255
+        } else {
256
+            return false;
257
+        }
258
+    }
259
+
260
+    /**
261
+     * get the users home folder to mount
262
+     *
263
+     * @return string
264
+     */
265
+    public function getHome() {
266
+        if (!$this->home) {
267
+            if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
268
+                $this->home = $home;
269
+            } elseif ($this->config) {
270
+                $this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
271
+            } else {
272
+                $this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
273
+            }
274
+        }
275
+        return $this->home;
276
+    }
277
+
278
+    /**
279
+     * Get the name of the backend class the user is connected with
280
+     *
281
+     * @return string
282
+     */
283
+    public function getBackendClassName() {
284
+        if($this->backend instanceof IUserBackend) {
285
+            return $this->backend->getBackendName();
286
+        }
287
+        return get_class($this->backend);
288
+    }
289
+
290
+    /**
291
+     * check if the backend allows the user to change his avatar on Personal page
292
+     *
293
+     * @return bool
294
+     */
295
+    public function canChangeAvatar() {
296
+        if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
297
+            return $this->backend->canChangeAvatar($this->uid);
298
+        }
299
+        return true;
300
+    }
301
+
302
+    /**
303
+     * check if the backend supports changing passwords
304
+     *
305
+     * @return bool
306
+     */
307
+    public function canChangePassword() {
308
+        return $this->backend->implementsActions(Backend::SET_PASSWORD);
309
+    }
310
+
311
+    /**
312
+     * check if the backend supports changing display names
313
+     *
314
+     * @return bool
315
+     */
316
+    public function canChangeDisplayName() {
317
+        if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) {
318
+            return false;
319
+        }
320
+        return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
321
+    }
322
+
323
+    /**
324
+     * check if the user is enabled
325
+     *
326
+     * @return bool
327
+     */
328
+    public function isEnabled() {
329
+        return $this->enabled;
330
+    }
331
+
332
+    /**
333
+     * set the enabled status for the user
334
+     *
335
+     * @param bool $enabled
336
+     */
337
+    public function setEnabled($enabled) {
338
+        $this->enabled = $enabled;
339
+        $enabled = ($enabled) ? 'true' : 'false';
340
+        $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled);
341
+    }
342
+
343
+    /**
344
+     * get the users email address
345
+     *
346
+     * @return string|null
347
+     * @since 9.0.0
348
+     */
349
+    public function getEMailAddress() {
350
+        return $this->config->getUserValue($this->uid, 'settings', 'email', null);
351
+    }
352
+
353
+    /**
354
+     * get the users' quota
355
+     *
356
+     * @return string
357
+     * @since 9.0.0
358
+     */
359
+    public function getQuota() {
360
+        $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
361
+        if($quota === 'default') {
362
+            $quota = $this->config->getAppValue('files', 'default_quota', 'none');
363
+        }
364
+        return $quota;
365
+    }
366
+
367
+    /**
368
+     * set the users' quota
369
+     *
370
+     * @param string $quota
371
+     * @return void
372
+     * @since 9.0.0
373
+     */
374
+    public function setQuota($quota) {
375
+        if($quota !== 'none' and $quota !== 'default') {
376
+            $quota = OC_Helper::computerFileSize($quota);
377
+            $quota = OC_Helper::humanFileSize($quota);
378
+        }
379
+        $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
380
+        $this->triggerChange('quota', $quota);
381
+    }
382
+
383
+    /**
384
+     * get the avatar image if it exists
385
+     *
386
+     * @param int $size
387
+     * @return IImage|null
388
+     * @since 9.0.0
389
+     */
390
+    public function getAvatarImage($size) {
391
+        // delay the initialization
392
+        if (is_null($this->avatarManager)) {
393
+            $this->avatarManager = \OC::$server->getAvatarManager();
394
+        }
395
+
396
+        $avatar = $this->avatarManager->getAvatar($this->uid);
397
+        $image = $avatar->get(-1);
398
+        if ($image) {
399
+            return $image;
400
+        }
401
+
402
+        return null;
403
+    }
404
+
405
+    /**
406
+     * get the federation cloud id
407
+     *
408
+     * @return string
409
+     * @since 9.0.0
410
+     */
411
+    public function getCloudId() {
412
+        $uid = $this->getUID();
413
+        $server = $this->urlGenerator->getAbsoluteURL('/');
414
+        $server =  rtrim( $this->removeProtocolFromUrl($server), '/');
415
+        return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
416
+    }
417
+
418
+    /**
419
+     * @param string $url
420
+     * @return string
421
+     */
422
+    private function removeProtocolFromUrl($url) {
423
+        if (strpos($url, 'https://') === 0) {
424
+            return substr($url, strlen('https://'));
425
+        } else if (strpos($url, 'http://') === 0) {
426
+            return substr($url, strlen('http://'));
427
+        }
428
+
429
+        return $url;
430
+    }
431
+
432
+    public function triggerChange($feature, $value = null) {
433
+        if ($this->emitter) {
434
+            $this->emitter->emit('\OC\User', 'changeUser', array($this, $feature, $value));
435
+        }
436
+    }
437 437
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 		$this->uid = $uid;
84 84
 		$this->backend = $backend;
85 85
 		$this->emitter = $emitter;
86
-		if(is_null($config)) {
86
+		if (is_null($config)) {
87 87
 			$config = \OC::$server->getConfig();
88 88
 		}
89 89
 		$this->config = $config;
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 * @since 9.0.0
159 159
 	 */
160 160
 	public function setEMailAddress($mailAddress) {
161
-		if($mailAddress === '') {
161
+		if ($mailAddress === '') {
162 162
 			$this->config->deleteUserValue($this->uid, 'settings', 'email');
163 163
 		} else {
164 164
 			$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 			}
220 220
 
221 221
 			// Delete the users entry in the storage table
222
-			Storage::remove('home::' . $this->uid);
222
+			Storage::remove('home::'.$this->uid);
223 223
 
224 224
 			\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
225 225
 			\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
@@ -267,9 +267,9 @@  discard block
 block discarded – undo
267 267
 			if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) {
268 268
 				$this->home = $home;
269 269
 			} elseif ($this->config) {
270
-				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
270
+				$this->home = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/'.$this->uid;
271 271
 			} else {
272
-				$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
272
+				$this->home = \OC::$SERVERROOT.'/data/'.$this->uid;
273 273
 			}
274 274
 		}
275 275
 		return $this->home;
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 	 * @return string
282 282
 	 */
283 283
 	public function getBackendClassName() {
284
-		if($this->backend instanceof IUserBackend) {
284
+		if ($this->backend instanceof IUserBackend) {
285 285
 			return $this->backend->getBackendName();
286 286
 		}
287 287
 		return get_class($this->backend);
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 	 */
359 359
 	public function getQuota() {
360 360
 		$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
361
-		if($quota === 'default') {
361
+		if ($quota === 'default') {
362 362
 			$quota = $this->config->getAppValue('files', 'default_quota', 'none');
363 363
 		}
364 364
 		return $quota;
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
 	 * @since 9.0.0
373 373
 	 */
374 374
 	public function setQuota($quota) {
375
-		if($quota !== 'none' and $quota !== 'default') {
375
+		if ($quota !== 'none' and $quota !== 'default') {
376 376
 			$quota = OC_Helper::computerFileSize($quota);
377 377
 			$quota = OC_Helper::humanFileSize($quota);
378 378
 		}
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 	public function getCloudId() {
412 412
 		$uid = $this->getUID();
413 413
 		$server = $this->urlGenerator->getAbsoluteURL('/');
414
-		$server =  rtrim( $this->removeProtocolFromUrl($server), '/');
414
+		$server = rtrim($this->removeProtocolFromUrl($server), '/');
415 415
 		return \OC::$server->getCloudIdManager()->getCloudId($uid, $server)->getId();
416 416
 	}
417 417
 
Please login to merge, or discard this patch.
lib/private/AllConfig.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -116,8 +116,8 @@
 block discarded – undo
116 116
 	 * Looks up a system wide defined value
117 117
 	 *
118 118
 	 * @param string $key the key of the value, under which it was saved
119
-	 * @param mixed $default the default value to be returned if the value isn't set
120
-	 * @return mixed the value or $default
119
+	 * @param string|false $default the default value to be returned if the value isn't set
120
+	 * @return string the value or $default
121 121
 	 */
122 122
 	public function getSystemValue($key, $default = '') {
123 123
 		return $this->systemConfig->getValue($key, $default);
Please login to merge, or discard this patch.
Indentation   +423 added lines, -423 removed lines patch added patch discarded remove patch
@@ -37,427 +37,427 @@
 block discarded – undo
37 37
  * Class to combine all the configuration options ownCloud offers
38 38
  */
39 39
 class AllConfig implements \OCP\IConfig {
40
-	/** @var SystemConfig */
41
-	private $systemConfig;
42
-
43
-	/** @var IDBConnection */
44
-	private $connection;
45
-
46
-	/**
47
-	 * 3 dimensional array with the following structure:
48
-	 * [ $userId =>
49
-	 *     [ $appId =>
50
-	 *         [ $key => $value ]
51
-	 *     ]
52
-	 * ]
53
-	 *
54
-	 * database table: preferences
55
-	 *
56
-	 * methods that use this:
57
-	 *   - setUserValue
58
-	 *   - getUserValue
59
-	 *   - getUserKeys
60
-	 *   - deleteUserValue
61
-	 *   - deleteAllUserValues
62
-	 *   - deleteAppFromAllUsers
63
-	 *
64
-	 * @var CappedMemoryCache $userCache
65
-	 */
66
-	private $userCache;
67
-
68
-	/**
69
-	 * @param SystemConfig $systemConfig
70
-	 */
71
-	public function __construct(SystemConfig $systemConfig) {
72
-		$this->userCache = new CappedMemoryCache();
73
-		$this->systemConfig = $systemConfig;
74
-	}
75
-
76
-	/**
77
-	 * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
-	 * dependencies, especially with autoconfig setup
79
-	 *
80
-	 * Replace this by properly injected database connection. Currently the
81
-	 * base.php triggers the getDatabaseConnection too early which causes in
82
-	 * autoconfig setup case a too early distributed database connection and
83
-	 * the autoconfig then needs to reinit all already initialized dependencies
84
-	 * that use the database connection.
85
-	 *
86
-	 * otherwise a SQLite database is created in the wrong directory
87
-	 * because the database connection was created with an uninitialized config
88
-	 */
89
-	private function fixDIInit() {
90
-		if($this->connection === null) {
91
-			$this->connection = \OC::$server->getDatabaseConnection();
92
-		}
93
-	}
94
-
95
-	/**
96
-	 * Sets and deletes system wide values
97
-	 *
98
-	 * @param array $configs Associative array with `key => value` pairs
99
-	 *                       If value is null, the config key will be deleted
100
-	 */
101
-	public function setSystemValues(array $configs) {
102
-		$this->systemConfig->setValues($configs);
103
-	}
104
-
105
-	/**
106
-	 * Sets a new system wide value
107
-	 *
108
-	 * @param string $key the key of the value, under which will be saved
109
-	 * @param mixed $value the value that should be stored
110
-	 */
111
-	public function setSystemValue($key, $value) {
112
-		$this->systemConfig->setValue($key, $value);
113
-	}
114
-
115
-	/**
116
-	 * Looks up a system wide defined value
117
-	 *
118
-	 * @param string $key the key of the value, under which it was saved
119
-	 * @param mixed $default the default value to be returned if the value isn't set
120
-	 * @return mixed the value or $default
121
-	 */
122
-	public function getSystemValue($key, $default = '') {
123
-		return $this->systemConfig->getValue($key, $default);
124
-	}
125
-
126
-	/**
127
-	 * Looks up a system wide defined value and filters out sensitive data
128
-	 *
129
-	 * @param string $key the key of the value, under which it was saved
130
-	 * @param mixed $default the default value to be returned if the value isn't set
131
-	 * @return mixed the value or $default
132
-	 */
133
-	public function getFilteredSystemValue($key, $default = '') {
134
-		return $this->systemConfig->getFilteredValue($key, $default);
135
-	}
136
-
137
-	/**
138
-	 * Delete a system wide defined value
139
-	 *
140
-	 * @param string $key the key of the value, under which it was saved
141
-	 */
142
-	public function deleteSystemValue($key) {
143
-		$this->systemConfig->deleteValue($key);
144
-	}
145
-
146
-	/**
147
-	 * Get all keys stored for an app
148
-	 *
149
-	 * @param string $appName the appName that we stored the value under
150
-	 * @return string[] the keys stored for the app
151
-	 */
152
-	public function getAppKeys($appName) {
153
-		return \OC::$server->getAppConfig()->getKeys($appName);
154
-	}
155
-
156
-	/**
157
-	 * Writes a new app wide value
158
-	 *
159
-	 * @param string $appName the appName that we want to store the value under
160
-	 * @param string $key the key of the value, under which will be saved
161
-	 * @param string|float|int $value the value that should be stored
162
-	 */
163
-	public function setAppValue($appName, $key, $value) {
164
-		\OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
-	}
166
-
167
-	/**
168
-	 * Looks up an app wide defined value
169
-	 *
170
-	 * @param string $appName the appName that we stored the value under
171
-	 * @param string $key the key of the value, under which it was saved
172
-	 * @param string $default the default value to be returned if the value isn't set
173
-	 * @return string the saved value
174
-	 */
175
-	public function getAppValue($appName, $key, $default = '') {
176
-		return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
-	}
178
-
179
-	/**
180
-	 * Delete an app wide defined value
181
-	 *
182
-	 * @param string $appName the appName that we stored the value under
183
-	 * @param string $key the key of the value, under which it was saved
184
-	 */
185
-	public function deleteAppValue($appName, $key) {
186
-		\OC::$server->getAppConfig()->deleteKey($appName, $key);
187
-	}
188
-
189
-	/**
190
-	 * Removes all keys in appconfig belonging to the app
191
-	 *
192
-	 * @param string $appName the appName the configs are stored under
193
-	 */
194
-	public function deleteAppValues($appName) {
195
-		\OC::$server->getAppConfig()->deleteApp($appName);
196
-	}
197
-
198
-
199
-	/**
200
-	 * Set a user defined value
201
-	 *
202
-	 * @param string $userId the userId of the user that we want to store the value under
203
-	 * @param string $appName the appName that we want to store the value under
204
-	 * @param string $key the key under which the value is being stored
205
-	 * @param string|float|int $value the value that you want to store
206
-	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
-	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
-	 * @throws \UnexpectedValueException when trying to store an unexpected value
209
-	 */
210
-	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
211
-		if (!is_int($value) && !is_float($value) && !is_string($value)) {
212
-			throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
213
-		}
214
-
215
-		// TODO - FIXME
216
-		$this->fixDIInit();
217
-
218
-		$prevValue = $this->getUserValue($userId, $appName, $key, null);
219
-
220
-		if ($prevValue !== null) {
221
-			if ($prevValue === (string)$value) {
222
-				return;
223
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
224
-				throw new PreConditionNotMetException();
225
-			} else {
226
-				$qb = $this->connection->getQueryBuilder();
227
-				$qb->update('preferences')
228
-					->set('configvalue', $qb->createNamedParameter($value))
229
-					->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
230
-					->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
231
-					->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
232
-				$qb->execute();
233
-
234
-				$this->userCache[$userId][$appName][$key] = $value;
235
-				return;
236
-			}
237
-		}
238
-
239
-		$preconditionArray = [];
240
-		if (isset($preCondition)) {
241
-			$preconditionArray = [
242
-				'configvalue' => $preCondition,
243
-			];
244
-		}
245
-
246
-		$this->connection->setValues('preferences', [
247
-			'userid' => $userId,
248
-			'appid' => $appName,
249
-			'configkey' => $key,
250
-		], [
251
-			'configvalue' => $value,
252
-		], $preconditionArray);
253
-
254
-		// only add to the cache if we already loaded data for the user
255
-		if (isset($this->userCache[$userId])) {
256
-			if (!isset($this->userCache[$userId][$appName])) {
257
-				$this->userCache[$userId][$appName] = array();
258
-			}
259
-			$this->userCache[$userId][$appName][$key] = $value;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * Getting a user defined value
265
-	 *
266
-	 * @param string $userId the userId of the user that we want to store the value under
267
-	 * @param string $appName the appName that we stored the value under
268
-	 * @param string $key the key under which the value is being stored
269
-	 * @param mixed $default the default value to be returned if the value isn't set
270
-	 * @return string
271
-	 */
272
-	public function getUserValue($userId, $appName, $key, $default = '') {
273
-		$data = $this->getUserValues($userId);
274
-		if (isset($data[$appName]) and isset($data[$appName][$key])) {
275
-			return $data[$appName][$key];
276
-		} else {
277
-			return $default;
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * Get the keys of all stored by an app for the user
283
-	 *
284
-	 * @param string $userId the userId of the user that we want to store the value under
285
-	 * @param string $appName the appName that we stored the value under
286
-	 * @return string[]
287
-	 */
288
-	public function getUserKeys($userId, $appName) {
289
-		$data = $this->getUserValues($userId);
290
-		if (isset($data[$appName])) {
291
-			return array_keys($data[$appName]);
292
-		} else {
293
-			return array();
294
-		}
295
-	}
296
-
297
-	/**
298
-	 * Delete a user value
299
-	 *
300
-	 * @param string $userId the userId of the user that we want to store the value under
301
-	 * @param string $appName the appName that we stored the value under
302
-	 * @param string $key the key under which the value is being stored
303
-	 */
304
-	public function deleteUserValue($userId, $appName, $key) {
305
-		// TODO - FIXME
306
-		$this->fixDIInit();
307
-
308
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
309
-				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310
-		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
311
-
312
-		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
313
-			unset($this->userCache[$userId][$appName][$key]);
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * Delete all user values
319
-	 *
320
-	 * @param string $userId the userId of the user that we want to remove all values from
321
-	 */
322
-	public function deleteAllUserValues($userId) {
323
-		// TODO - FIXME
324
-		$this->fixDIInit();
325
-
326
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
327
-			'WHERE `userid` = ?';
328
-		$this->connection->executeUpdate($sql, array($userId));
329
-
330
-		unset($this->userCache[$userId]);
331
-	}
332
-
333
-	/**
334
-	 * Delete all user related values of one app
335
-	 *
336
-	 * @param string $appName the appName of the app that we want to remove all values from
337
-	 */
338
-	public function deleteAppFromAllUsers($appName) {
339
-		// TODO - FIXME
340
-		$this->fixDIInit();
341
-
342
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
343
-				'WHERE `appid` = ?';
344
-		$this->connection->executeUpdate($sql, array($appName));
345
-
346
-		foreach ($this->userCache as &$userCache) {
347
-			unset($userCache[$appName]);
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * Returns all user configs sorted by app of one user
353
-	 *
354
-	 * @param string $userId the user ID to get the app configs from
355
-	 * @return array[] - 2 dimensional array with the following structure:
356
-	 *     [ $appId =>
357
-	 *         [ $key => $value ]
358
-	 *     ]
359
-	 */
360
-	private function getUserValues($userId) {
361
-		if (isset($this->userCache[$userId])) {
362
-			return $this->userCache[$userId];
363
-		}
364
-		if ($userId === null || $userId === '') {
365
-			$this->userCache[$userId]=array();
366
-			return $this->userCache[$userId];
367
-		}
368
-
369
-		// TODO - FIXME
370
-		$this->fixDIInit();
371
-
372
-		$data = array();
373
-		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
374
-		$result = $this->connection->executeQuery($query, array($userId));
375
-		while ($row = $result->fetch()) {
376
-			$appId = $row['appid'];
377
-			if (!isset($data[$appId])) {
378
-				$data[$appId] = array();
379
-			}
380
-			$data[$appId][$row['configkey']] = $row['configvalue'];
381
-		}
382
-		$this->userCache[$userId] = $data;
383
-		return $data;
384
-	}
385
-
386
-	/**
387
-	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
388
-	 *
389
-	 * @param string $appName app to get the value for
390
-	 * @param string $key the key to get the value for
391
-	 * @param array $userIds the user IDs to fetch the values for
392
-	 * @return array Mapped values: userId => value
393
-	 */
394
-	public function getUserValueForUsers($appName, $key, $userIds) {
395
-		// TODO - FIXME
396
-		$this->fixDIInit();
397
-
398
-		if (empty($userIds) || !is_array($userIds)) {
399
-			return array();
400
-		}
401
-
402
-		$chunkedUsers = array_chunk($userIds, 50, true);
403
-		$placeholders50 = implode(',', array_fill(0, 50, '?'));
404
-
405
-		$userValues = array();
406
-		foreach ($chunkedUsers as $chunk) {
407
-			$queryParams = $chunk;
408
-			// create [$app, $key, $chunkedUsers]
409
-			array_unshift($queryParams, $key);
410
-			array_unshift($queryParams, $appName);
411
-
412
-			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
413
-
414
-			$query    = 'SELECT `userid`, `configvalue` ' .
415
-						'FROM `*PREFIX*preferences` ' .
416
-						'WHERE `appid` = ? AND `configkey` = ? ' .
417
-						'AND `userid` IN (' . $placeholders . ')';
418
-			$result = $this->connection->executeQuery($query, $queryParams);
419
-
420
-			while ($row = $result->fetch()) {
421
-				$userValues[$row['userid']] = $row['configvalue'];
422
-			}
423
-		}
424
-
425
-		return $userValues;
426
-	}
427
-
428
-	/**
429
-	 * Determines the users that have the given value set for a specific app-key-pair
430
-	 *
431
-	 * @param string $appName the app to get the user for
432
-	 * @param string $key the key to get the user for
433
-	 * @param string $value the value to get the user for
434
-	 * @return array of user IDs
435
-	 */
436
-	public function getUsersForUserValue($appName, $key, $value) {
437
-		// TODO - FIXME
438
-		$this->fixDIInit();
439
-
440
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
441
-				'WHERE `appid` = ? AND `configkey` = ? ';
442
-
443
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444
-			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
445
-			$sql .= 'AND to_char(`configvalue`) = ?';
446
-		} else {
447
-			$sql .= 'AND `configvalue` = ?';
448
-		}
449
-
450
-		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
451
-
452
-		$userIDs = array();
453
-		while ($row = $result->fetch()) {
454
-			$userIDs[] = $row['userid'];
455
-		}
456
-
457
-		return $userIDs;
458
-	}
459
-
460
-	public function getSystemConfig() {
461
-		return $this->systemConfig;
462
-	}
40
+    /** @var SystemConfig */
41
+    private $systemConfig;
42
+
43
+    /** @var IDBConnection */
44
+    private $connection;
45
+
46
+    /**
47
+     * 3 dimensional array with the following structure:
48
+     * [ $userId =>
49
+     *     [ $appId =>
50
+     *         [ $key => $value ]
51
+     *     ]
52
+     * ]
53
+     *
54
+     * database table: preferences
55
+     *
56
+     * methods that use this:
57
+     *   - setUserValue
58
+     *   - getUserValue
59
+     *   - getUserKeys
60
+     *   - deleteUserValue
61
+     *   - deleteAllUserValues
62
+     *   - deleteAppFromAllUsers
63
+     *
64
+     * @var CappedMemoryCache $userCache
65
+     */
66
+    private $userCache;
67
+
68
+    /**
69
+     * @param SystemConfig $systemConfig
70
+     */
71
+    public function __construct(SystemConfig $systemConfig) {
72
+        $this->userCache = new CappedMemoryCache();
73
+        $this->systemConfig = $systemConfig;
74
+    }
75
+
76
+    /**
77
+     * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
+     * dependencies, especially with autoconfig setup
79
+     *
80
+     * Replace this by properly injected database connection. Currently the
81
+     * base.php triggers the getDatabaseConnection too early which causes in
82
+     * autoconfig setup case a too early distributed database connection and
83
+     * the autoconfig then needs to reinit all already initialized dependencies
84
+     * that use the database connection.
85
+     *
86
+     * otherwise a SQLite database is created in the wrong directory
87
+     * because the database connection was created with an uninitialized config
88
+     */
89
+    private function fixDIInit() {
90
+        if($this->connection === null) {
91
+            $this->connection = \OC::$server->getDatabaseConnection();
92
+        }
93
+    }
94
+
95
+    /**
96
+     * Sets and deletes system wide values
97
+     *
98
+     * @param array $configs Associative array with `key => value` pairs
99
+     *                       If value is null, the config key will be deleted
100
+     */
101
+    public function setSystemValues(array $configs) {
102
+        $this->systemConfig->setValues($configs);
103
+    }
104
+
105
+    /**
106
+     * Sets a new system wide value
107
+     *
108
+     * @param string $key the key of the value, under which will be saved
109
+     * @param mixed $value the value that should be stored
110
+     */
111
+    public function setSystemValue($key, $value) {
112
+        $this->systemConfig->setValue($key, $value);
113
+    }
114
+
115
+    /**
116
+     * Looks up a system wide defined value
117
+     *
118
+     * @param string $key the key of the value, under which it was saved
119
+     * @param mixed $default the default value to be returned if the value isn't set
120
+     * @return mixed the value or $default
121
+     */
122
+    public function getSystemValue($key, $default = '') {
123
+        return $this->systemConfig->getValue($key, $default);
124
+    }
125
+
126
+    /**
127
+     * Looks up a system wide defined value and filters out sensitive data
128
+     *
129
+     * @param string $key the key of the value, under which it was saved
130
+     * @param mixed $default the default value to be returned if the value isn't set
131
+     * @return mixed the value or $default
132
+     */
133
+    public function getFilteredSystemValue($key, $default = '') {
134
+        return $this->systemConfig->getFilteredValue($key, $default);
135
+    }
136
+
137
+    /**
138
+     * Delete a system wide defined value
139
+     *
140
+     * @param string $key the key of the value, under which it was saved
141
+     */
142
+    public function deleteSystemValue($key) {
143
+        $this->systemConfig->deleteValue($key);
144
+    }
145
+
146
+    /**
147
+     * Get all keys stored for an app
148
+     *
149
+     * @param string $appName the appName that we stored the value under
150
+     * @return string[] the keys stored for the app
151
+     */
152
+    public function getAppKeys($appName) {
153
+        return \OC::$server->getAppConfig()->getKeys($appName);
154
+    }
155
+
156
+    /**
157
+     * Writes a new app wide value
158
+     *
159
+     * @param string $appName the appName that we want to store the value under
160
+     * @param string $key the key of the value, under which will be saved
161
+     * @param string|float|int $value the value that should be stored
162
+     */
163
+    public function setAppValue($appName, $key, $value) {
164
+        \OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
+    }
166
+
167
+    /**
168
+     * Looks up an app wide defined value
169
+     *
170
+     * @param string $appName the appName that we stored the value under
171
+     * @param string $key the key of the value, under which it was saved
172
+     * @param string $default the default value to be returned if the value isn't set
173
+     * @return string the saved value
174
+     */
175
+    public function getAppValue($appName, $key, $default = '') {
176
+        return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
+    }
178
+
179
+    /**
180
+     * Delete an app wide defined value
181
+     *
182
+     * @param string $appName the appName that we stored the value under
183
+     * @param string $key the key of the value, under which it was saved
184
+     */
185
+    public function deleteAppValue($appName, $key) {
186
+        \OC::$server->getAppConfig()->deleteKey($appName, $key);
187
+    }
188
+
189
+    /**
190
+     * Removes all keys in appconfig belonging to the app
191
+     *
192
+     * @param string $appName the appName the configs are stored under
193
+     */
194
+    public function deleteAppValues($appName) {
195
+        \OC::$server->getAppConfig()->deleteApp($appName);
196
+    }
197
+
198
+
199
+    /**
200
+     * Set a user defined value
201
+     *
202
+     * @param string $userId the userId of the user that we want to store the value under
203
+     * @param string $appName the appName that we want to store the value under
204
+     * @param string $key the key under which the value is being stored
205
+     * @param string|float|int $value the value that you want to store
206
+     * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
+     * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
+     * @throws \UnexpectedValueException when trying to store an unexpected value
209
+     */
210
+    public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
211
+        if (!is_int($value) && !is_float($value) && !is_string($value)) {
212
+            throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
213
+        }
214
+
215
+        // TODO - FIXME
216
+        $this->fixDIInit();
217
+
218
+        $prevValue = $this->getUserValue($userId, $appName, $key, null);
219
+
220
+        if ($prevValue !== null) {
221
+            if ($prevValue === (string)$value) {
222
+                return;
223
+            } else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
224
+                throw new PreConditionNotMetException();
225
+            } else {
226
+                $qb = $this->connection->getQueryBuilder();
227
+                $qb->update('preferences')
228
+                    ->set('configvalue', $qb->createNamedParameter($value))
229
+                    ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
230
+                    ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
231
+                    ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
232
+                $qb->execute();
233
+
234
+                $this->userCache[$userId][$appName][$key] = $value;
235
+                return;
236
+            }
237
+        }
238
+
239
+        $preconditionArray = [];
240
+        if (isset($preCondition)) {
241
+            $preconditionArray = [
242
+                'configvalue' => $preCondition,
243
+            ];
244
+        }
245
+
246
+        $this->connection->setValues('preferences', [
247
+            'userid' => $userId,
248
+            'appid' => $appName,
249
+            'configkey' => $key,
250
+        ], [
251
+            'configvalue' => $value,
252
+        ], $preconditionArray);
253
+
254
+        // only add to the cache if we already loaded data for the user
255
+        if (isset($this->userCache[$userId])) {
256
+            if (!isset($this->userCache[$userId][$appName])) {
257
+                $this->userCache[$userId][$appName] = array();
258
+            }
259
+            $this->userCache[$userId][$appName][$key] = $value;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * Getting a user defined value
265
+     *
266
+     * @param string $userId the userId of the user that we want to store the value under
267
+     * @param string $appName the appName that we stored the value under
268
+     * @param string $key the key under which the value is being stored
269
+     * @param mixed $default the default value to be returned if the value isn't set
270
+     * @return string
271
+     */
272
+    public function getUserValue($userId, $appName, $key, $default = '') {
273
+        $data = $this->getUserValues($userId);
274
+        if (isset($data[$appName]) and isset($data[$appName][$key])) {
275
+            return $data[$appName][$key];
276
+        } else {
277
+            return $default;
278
+        }
279
+    }
280
+
281
+    /**
282
+     * Get the keys of all stored by an app for the user
283
+     *
284
+     * @param string $userId the userId of the user that we want to store the value under
285
+     * @param string $appName the appName that we stored the value under
286
+     * @return string[]
287
+     */
288
+    public function getUserKeys($userId, $appName) {
289
+        $data = $this->getUserValues($userId);
290
+        if (isset($data[$appName])) {
291
+            return array_keys($data[$appName]);
292
+        } else {
293
+            return array();
294
+        }
295
+    }
296
+
297
+    /**
298
+     * Delete a user value
299
+     *
300
+     * @param string $userId the userId of the user that we want to store the value under
301
+     * @param string $appName the appName that we stored the value under
302
+     * @param string $key the key under which the value is being stored
303
+     */
304
+    public function deleteUserValue($userId, $appName, $key) {
305
+        // TODO - FIXME
306
+        $this->fixDIInit();
307
+
308
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
309
+                'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310
+        $this->connection->executeUpdate($sql, array($userId, $appName, $key));
311
+
312
+        if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
313
+            unset($this->userCache[$userId][$appName][$key]);
314
+        }
315
+    }
316
+
317
+    /**
318
+     * Delete all user values
319
+     *
320
+     * @param string $userId the userId of the user that we want to remove all values from
321
+     */
322
+    public function deleteAllUserValues($userId) {
323
+        // TODO - FIXME
324
+        $this->fixDIInit();
325
+
326
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
327
+            'WHERE `userid` = ?';
328
+        $this->connection->executeUpdate($sql, array($userId));
329
+
330
+        unset($this->userCache[$userId]);
331
+    }
332
+
333
+    /**
334
+     * Delete all user related values of one app
335
+     *
336
+     * @param string $appName the appName of the app that we want to remove all values from
337
+     */
338
+    public function deleteAppFromAllUsers($appName) {
339
+        // TODO - FIXME
340
+        $this->fixDIInit();
341
+
342
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
343
+                'WHERE `appid` = ?';
344
+        $this->connection->executeUpdate($sql, array($appName));
345
+
346
+        foreach ($this->userCache as &$userCache) {
347
+            unset($userCache[$appName]);
348
+        }
349
+    }
350
+
351
+    /**
352
+     * Returns all user configs sorted by app of one user
353
+     *
354
+     * @param string $userId the user ID to get the app configs from
355
+     * @return array[] - 2 dimensional array with the following structure:
356
+     *     [ $appId =>
357
+     *         [ $key => $value ]
358
+     *     ]
359
+     */
360
+    private function getUserValues($userId) {
361
+        if (isset($this->userCache[$userId])) {
362
+            return $this->userCache[$userId];
363
+        }
364
+        if ($userId === null || $userId === '') {
365
+            $this->userCache[$userId]=array();
366
+            return $this->userCache[$userId];
367
+        }
368
+
369
+        // TODO - FIXME
370
+        $this->fixDIInit();
371
+
372
+        $data = array();
373
+        $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
374
+        $result = $this->connection->executeQuery($query, array($userId));
375
+        while ($row = $result->fetch()) {
376
+            $appId = $row['appid'];
377
+            if (!isset($data[$appId])) {
378
+                $data[$appId] = array();
379
+            }
380
+            $data[$appId][$row['configkey']] = $row['configvalue'];
381
+        }
382
+        $this->userCache[$userId] = $data;
383
+        return $data;
384
+    }
385
+
386
+    /**
387
+     * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
388
+     *
389
+     * @param string $appName app to get the value for
390
+     * @param string $key the key to get the value for
391
+     * @param array $userIds the user IDs to fetch the values for
392
+     * @return array Mapped values: userId => value
393
+     */
394
+    public function getUserValueForUsers($appName, $key, $userIds) {
395
+        // TODO - FIXME
396
+        $this->fixDIInit();
397
+
398
+        if (empty($userIds) || !is_array($userIds)) {
399
+            return array();
400
+        }
401
+
402
+        $chunkedUsers = array_chunk($userIds, 50, true);
403
+        $placeholders50 = implode(',', array_fill(0, 50, '?'));
404
+
405
+        $userValues = array();
406
+        foreach ($chunkedUsers as $chunk) {
407
+            $queryParams = $chunk;
408
+            // create [$app, $key, $chunkedUsers]
409
+            array_unshift($queryParams, $key);
410
+            array_unshift($queryParams, $appName);
411
+
412
+            $placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
413
+
414
+            $query    = 'SELECT `userid`, `configvalue` ' .
415
+                        'FROM `*PREFIX*preferences` ' .
416
+                        'WHERE `appid` = ? AND `configkey` = ? ' .
417
+                        'AND `userid` IN (' . $placeholders . ')';
418
+            $result = $this->connection->executeQuery($query, $queryParams);
419
+
420
+            while ($row = $result->fetch()) {
421
+                $userValues[$row['userid']] = $row['configvalue'];
422
+            }
423
+        }
424
+
425
+        return $userValues;
426
+    }
427
+
428
+    /**
429
+     * Determines the users that have the given value set for a specific app-key-pair
430
+     *
431
+     * @param string $appName the app to get the user for
432
+     * @param string $key the key to get the user for
433
+     * @param string $value the value to get the user for
434
+     * @return array of user IDs
435
+     */
436
+    public function getUsersForUserValue($appName, $key, $value) {
437
+        // TODO - FIXME
438
+        $this->fixDIInit();
439
+
440
+        $sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
441
+                'WHERE `appid` = ? AND `configkey` = ? ';
442
+
443
+        if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444
+            //oracle hack: need to explicitly cast CLOB to CHAR for comparison
445
+            $sql .= 'AND to_char(`configvalue`) = ?';
446
+        } else {
447
+            $sql .= 'AND `configvalue` = ?';
448
+        }
449
+
450
+        $result = $this->connection->executeQuery($sql, array($appName, $key, $value));
451
+
452
+        $userIDs = array();
453
+        while ($row = $result->fetch()) {
454
+            $userIDs[] = $row['userid'];
455
+        }
456
+
457
+        return $userIDs;
458
+    }
459
+
460
+    public function getSystemConfig() {
461
+        return $this->systemConfig;
462
+    }
463 463
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	 * because the database connection was created with an uninitialized config
88 88
 	 */
89 89
 	private function fixDIInit() {
90
-		if($this->connection === null) {
90
+		if ($this->connection === null) {
91 91
 			$this->connection = \OC::$server->getDatabaseConnection();
92 92
 		}
93 93
 	}
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 		$prevValue = $this->getUserValue($userId, $appName, $key, null);
219 219
 
220 220
 		if ($prevValue !== null) {
221
-			if ($prevValue === (string)$value) {
221
+			if ($prevValue === (string) $value) {
222 222
 				return;
223
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
223
+			} else if ($preCondition !== null && $prevValue !== (string) $preCondition) {
224 224
 				throw new PreConditionNotMetException();
225 225
 			} else {
226 226
 				$qb = $this->connection->getQueryBuilder();
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 		// TODO - FIXME
306 306
 		$this->fixDIInit();
307 307
 
308
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
308
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
309 309
 				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310 310
 		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
311 311
 
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 		// TODO - FIXME
324 324
 		$this->fixDIInit();
325 325
 
326
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
326
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
327 327
 			'WHERE `userid` = ?';
328 328
 		$this->connection->executeUpdate($sql, array($userId));
329 329
 
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		// TODO - FIXME
340 340
 		$this->fixDIInit();
341 341
 
342
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
342
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
343 343
 				'WHERE `appid` = ?';
344 344
 		$this->connection->executeUpdate($sql, array($appName));
345 345
 
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			return $this->userCache[$userId];
363 363
 		}
364 364
 		if ($userId === null || $userId === '') {
365
-			$this->userCache[$userId]=array();
365
+			$this->userCache[$userId] = array();
366 366
 			return $this->userCache[$userId];
367 367
 		}
368 368
 
@@ -409,12 +409,12 @@  discard block
 block discarded – undo
409 409
 			array_unshift($queryParams, $key);
410 410
 			array_unshift($queryParams, $appName);
411 411
 
412
-			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
412
+			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?'));
413 413
 
414
-			$query    = 'SELECT `userid`, `configvalue` ' .
415
-						'FROM `*PREFIX*preferences` ' .
416
-						'WHERE `appid` = ? AND `configkey` = ? ' .
417
-						'AND `userid` IN (' . $placeholders . ')';
414
+			$query = 'SELECT `userid`, `configvalue` '.
415
+						'FROM `*PREFIX*preferences` '.
416
+						'WHERE `appid` = ? AND `configkey` = ? '.
417
+						'AND `userid` IN ('.$placeholders.')';
418 418
 			$result = $this->connection->executeQuery($query, $queryParams);
419 419
 
420 420
 			while ($row = $result->fetch()) {
@@ -437,10 +437,10 @@  discard block
 block discarded – undo
437 437
 		// TODO - FIXME
438 438
 		$this->fixDIInit();
439 439
 
440
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
440
+		$sql = 'SELECT `userid` FROM `*PREFIX*preferences` '.
441 441
 				'WHERE `appid` = ? AND `configkey` = ? ';
442 442
 
443
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
443
+		if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444 444
 			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
445 445
 			$sql .= 'AND to_char(`configvalue`) = ?';
446 446
 		} else {
Please login to merge, or discard this patch.
lib/private/Lockdown/Filesystem/NullCache.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -22,7 +22,6 @@
 block discarded – undo
22 22
 use OC\Files\Cache\CacheEntry;
23 23
 use OCP\Constants;
24 24
 use OCP\Files\Cache\ICache;
25
-use OCP\Files\Cache\ICacheEntry;
26 25
 use OCP\Files\FileInfo;
27 26
 
28 27
 class NullCache implements ICache {
Please login to merge, or discard this patch.
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -26,97 +26,97 @@
 block discarded – undo
26 26
 use OCP\Files\FileInfo;
27 27
 
28 28
 class NullCache implements ICache {
29
-	public function getNumericStorageId() {
30
-		return -1;
31
-	}
32
-
33
-	public function get($file) {
34
-		return $file !== '' ? null :
35
-			new CacheEntry([
36
-				'fileid' => -1,
37
-				'parent' => -1,
38
-				'name' => '',
39
-				'path' => '',
40
-				'size' => '0',
41
-				'mtime' => time(),
42
-				'storage_mtime' => time(),
43
-				'etag' => '',
44
-				'mimetype' => FileInfo::MIMETYPE_FOLDER,
45
-				'mimepart' => 'httpd',
46
-				'permissions' => Constants::PERMISSION_READ
47
-			]);
48
-	}
49
-
50
-	public function getFolderContents($folder) {
51
-		return [];
52
-	}
53
-
54
-	public function getFolderContentsById($fileId) {
55
-		return [];
56
-	}
57
-
58
-	public function put($file, array $data) {
59
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
60
-	}
61
-
62
-	public function insert($file, array $data) {
63
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
64
-	}
65
-
66
-	public function update($id, array $data) {
67
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
68
-	}
69
-
70
-	public function getId($file) {
71
-		return -1;
72
-	}
73
-
74
-	public function getParentId($file) {
75
-		return -1;
76
-	}
77
-
78
-	public function inCache($file) {
79
-		return $file === '';
80
-	}
81
-
82
-	public function remove($file) {
83
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
84
-	}
85
-
86
-	public function move($source, $target) {
87
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
88
-	}
89
-
90
-	public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
91
-		throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
92
-	}
93
-
94
-	public function getStatus($file) {
95
-		return ICache::COMPLETE;
96
-	}
97
-
98
-	public function search($pattern) {
99
-		return [];
100
-	}
101
-
102
-	public function searchByMime($mimetype) {
103
-		return [];
104
-	}
105
-
106
-	public function searchByTag($tag, $userId) {
107
-		return [];
108
-	}
109
-
110
-	public function getIncomplete() {
111
-		return [];
112
-	}
113
-
114
-	public function getPathById($id) {
115
-		return '';
116
-	}
117
-
118
-	public function normalize($path) {
119
-		return $path;
120
-	}
29
+    public function getNumericStorageId() {
30
+        return -1;
31
+    }
32
+
33
+    public function get($file) {
34
+        return $file !== '' ? null :
35
+            new CacheEntry([
36
+                'fileid' => -1,
37
+                'parent' => -1,
38
+                'name' => '',
39
+                'path' => '',
40
+                'size' => '0',
41
+                'mtime' => time(),
42
+                'storage_mtime' => time(),
43
+                'etag' => '',
44
+                'mimetype' => FileInfo::MIMETYPE_FOLDER,
45
+                'mimepart' => 'httpd',
46
+                'permissions' => Constants::PERMISSION_READ
47
+            ]);
48
+    }
49
+
50
+    public function getFolderContents($folder) {
51
+        return [];
52
+    }
53
+
54
+    public function getFolderContentsById($fileId) {
55
+        return [];
56
+    }
57
+
58
+    public function put($file, array $data) {
59
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
60
+    }
61
+
62
+    public function insert($file, array $data) {
63
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
64
+    }
65
+
66
+    public function update($id, array $data) {
67
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
68
+    }
69
+
70
+    public function getId($file) {
71
+        return -1;
72
+    }
73
+
74
+    public function getParentId($file) {
75
+        return -1;
76
+    }
77
+
78
+    public function inCache($file) {
79
+        return $file === '';
80
+    }
81
+
82
+    public function remove($file) {
83
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
84
+    }
85
+
86
+    public function move($source, $target) {
87
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
88
+    }
89
+
90
+    public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
91
+        throw new \OC\ForbiddenException('This request is not allowed to access the filesystem');
92
+    }
93
+
94
+    public function getStatus($file) {
95
+        return ICache::COMPLETE;
96
+    }
97
+
98
+    public function search($pattern) {
99
+        return [];
100
+    }
101
+
102
+    public function searchByMime($mimetype) {
103
+        return [];
104
+    }
105
+
106
+    public function searchByTag($tag, $userId) {
107
+        return [];
108
+    }
109
+
110
+    public function getIncomplete() {
111
+        return [];
112
+    }
113
+
114
+    public function getPathById($id) {
115
+        return '';
116
+    }
117
+
118
+    public function normalize($path) {
119
+        return $path;
120
+    }
121 121
 
122 122
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -31,8 +31,7 @@
 block discarded – undo
31 31
 	}
32 32
 
33 33
 	public function get($file) {
34
-		return $file !== '' ? null :
35
-			new CacheEntry([
34
+		return $file !== '' ? null : new CacheEntry([
36 35
 				'fileid' => -1,
37 36
 				'parent' => -1,
38 37
 				'name' => '',
Please login to merge, or discard this patch.