Completed
Pull Request — master (#8565)
by Joas
105:07 queued 85:11
created
lib/private/Files/Storage/Wrapper/Encryption.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	/**
985 985
 	 * check if path points to a files version
986 986
 	 *
987
-	 * @param $path
987
+	 * @param string $path
988 988
 	 * @return bool
989 989
 	 */
990 990
 	protected function isVersion($path) {
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 	/**
996 996
 	 * check if the given storage should be encrypted or not
997 997
 	 *
998
-	 * @param $path
998
+	 * @param string $path
999 999
 	 * @return bool
1000 1000
 	 */
1001 1001
 	protected function shouldEncrypt($path) {
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -370,8 +370,8 @@  discard block
 block discarded – undo
370 370
 		// check if the file is stored in the array cache, this means that we
371 371
 		// copy a file over to the versions folder, in this case we don't want to
372 372
 		// decrypt it
373
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
374
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
373
+		if ($this->arrayCache->hasKey('encryption_copy_version_'.$path)) {
374
+			$this->arrayCache->remove('encryption_copy_version_'.$path);
375 375
 			return $this->storage->fopen($path, $mode);
376 376
 		}
377 377
 
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 				}
443 443
 			} catch (ModuleDoesNotExistsException $e) {
444 444
 				$this->logger->logException($e, [
445
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
445
+					'message' => 'Encryption module "'.$encryptionModuleId.'" not found, file will be stored unencrypted',
446 446
 					'level' => \OCP\Util::WARN,
447 447
 					'app' => 'core',
448 448
 				]);
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 				try {
498 498
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
499 499
 				} catch (\Exception $e) {
500
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
500
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
501 501
 					$this->logger->logException($e);
502 502
 				}
503 503
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 
527 527
 		// if we couldn't open the file we return the old unencrypted size
528 528
 		if (!is_resource($stream)) {
529
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
529
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
530 530
 			return $unencryptedSize;
531 531
 		}
532 532
 
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
 		// next highest is end of chunks, one subtracted is last one
552 552
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
553 553
 
554
-		$lastChunkNr = ceil($size/ $blockSize)-1;
554
+		$lastChunkNr = ceil($size / $blockSize) - 1;
555 555
 		// calculate last chunk position
556 556
 		$lastChunkPos = ($lastChunkNr * $blockSize);
557 557
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -559,16 +559,16 @@  discard block
 block discarded – undo
559 559
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
560 560
 		}
561 561
 
562
-		$lastChunkContentEncrypted='';
562
+		$lastChunkContentEncrypted = '';
563 563
 		$count = $blockSize;
564 564
 
565 565
 		while ($count > 0) {
566
-			$data=fread($stream, $blockSize);
567
-			$count=strlen($data);
566
+			$data = fread($stream, $blockSize);
567
+			$count = strlen($data);
568 568
 			$lastChunkContentEncrypted .= $data;
569
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
569
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
570 570
 				$newUnencryptedSize += $unencryptedBlockSize;
571
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
571
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
572 572
 			}
573 573
 		}
574 574
 
@@ -576,8 +576,8 @@  discard block
 block discarded – undo
576 576
 
577 577
 		// we have to decrypt the last chunk to get it actual size
578 578
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
579
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
580
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
579
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
580
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
581 581
 
582 582
 		// calc the real file size with the size of the last chunk
583 583
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -658,9 +658,9 @@  discard block
 block discarded – undo
658 658
 	private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
659 659
 		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
660 660
 		$cacheInformation = [
661
-			'encrypted' => (bool)$isEncrypted,
661
+			'encrypted' => (bool) $isEncrypted,
662 662
 		];
663
-		if($isEncrypted === 1) {
663
+		if ($isEncrypted === 1) {
664 664
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
665 665
 
666 666
 			// In case of a move operation from an unencrypted to an encrypted
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 			// correct value would be "1". Thus we manually set the value to "1"
669 669
 			// for those cases.
670 670
 			// See also https://github.com/owncloud/core/issues/23078
671
-			if($encryptedVersion === 0) {
671
+			if ($encryptedVersion === 0) {
672 672
 				$encryptedVersion = 1;
673 673
 			}
674 674
 
@@ -704,9 +704,9 @@  discard block
 block discarded – undo
704 704
 			// remember that we try to create a version so that we can detect it during
705 705
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
706 706
 			// create a 1:1 copy of the file
707
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
707
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
708 708
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
709
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
709
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
710 710
 			if ($result) {
711 711
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
712 712
 				// make sure that we update the unencrypted size for the version
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
727 727
 		if (count($mount) === 1) {
728 728
 			$mountPoint = $mount[0]->getMountPoint();
729
-			$source = $mountPoint . '/' . $sourceInternalPath;
729
+			$source = $mountPoint.'/'.$sourceInternalPath;
730 730
 			$target = $this->getFullPath($targetInternalPath);
731 731
 			$this->copyKeys($source, $target);
732 732
 		} else {
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
 			if (is_resource($dh)) {
740 740
 				while ($result and ($file = readdir($dh)) !== false) {
741 741
 					if (!Filesystem::isIgnoredDir($file)) {
742
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
742
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
743 743
 					}
744 744
 				}
745 745
 			}
@@ -755,7 +755,7 @@  discard block
 block discarded – undo
755 755
 				fclose($target);
756 756
 				throw $e;
757 757
 			}
758
-			if($result) {
758
+			if ($result) {
759 759
 				if ($preserveMtime) {
760 760
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
761 761
 				}
@@ -767,7 +767,7 @@  discard block
 block discarded – undo
767 767
 				$this->getCache()->remove($targetInternalPath);
768 768
 			}
769 769
 		}
770
-		return (bool)$result;
770
+		return (bool) $result;
771 771
 
772 772
 	}
773 773
 
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
 	 * @return string full path including mount point
839 839
 	 */
840 840
 	protected function getFullPath($path) {
841
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
841
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
842 842
 	}
843 843
 
844 844
 	/**
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
895 895
 
896 896
 				// +1 to not start with an ':' which would result in empty element at the beginning
897
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
897
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
898 898
 
899 899
 				$element = array_shift($exploded);
900 900
 				while ($element !== Util::HEADER_END) {
@@ -957,7 +957,7 @@  discard block
 block discarded – undo
957 957
 			try {
958 958
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
959 959
 			} catch (ModuleDoesNotExistsException $e) {
960
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
960
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
961 961
 				throw $e;
962 962
 			}
963 963
 		}
Please login to merge, or discard this patch.
Indentation   +975 added lines, -975 removed lines patch added patch discarded remove patch
@@ -48,980 +48,980 @@
 block discarded – undo
48 48
 
49 49
 class Encryption extends Wrapper {
50 50
 
51
-	use LocalTempFileTrait;
52
-
53
-	/** @var string */
54
-	private $mountPoint;
55
-
56
-	/** @var \OC\Encryption\Util */
57
-	private $util;
58
-
59
-	/** @var \OCP\Encryption\IManager */
60
-	private $encryptionManager;
61
-
62
-	/** @var \OCP\ILogger */
63
-	private $logger;
64
-
65
-	/** @var string */
66
-	private $uid;
67
-
68
-	/** @var array */
69
-	protected $unencryptedSize;
70
-
71
-	/** @var \OCP\Encryption\IFile */
72
-	private $fileHelper;
73
-
74
-	/** @var IMountPoint */
75
-	private $mount;
76
-
77
-	/** @var IStorage */
78
-	private $keyStorage;
79
-
80
-	/** @var Update */
81
-	private $update;
82
-
83
-	/** @var Manager */
84
-	private $mountManager;
85
-
86
-	/** @var array remember for which path we execute the repair step to avoid recursions */
87
-	private $fixUnencryptedSizeOf = array();
88
-
89
-	/** @var  ArrayCache */
90
-	private $arrayCache;
91
-
92
-	/**
93
-	 * @param array $parameters
94
-	 * @param IManager $encryptionManager
95
-	 * @param Util $util
96
-	 * @param ILogger $logger
97
-	 * @param IFile $fileHelper
98
-	 * @param string $uid
99
-	 * @param IStorage $keyStorage
100
-	 * @param Update $update
101
-	 * @param Manager $mountManager
102
-	 * @param ArrayCache $arrayCache
103
-	 */
104
-	public function __construct(
105
-			$parameters,
106
-			IManager $encryptionManager = null,
107
-			Util $util = null,
108
-			ILogger $logger = null,
109
-			IFile $fileHelper = null,
110
-			$uid = null,
111
-			IStorage $keyStorage = null,
112
-			Update $update = null,
113
-			Manager $mountManager = null,
114
-			ArrayCache $arrayCache = null
115
-		) {
116
-
117
-		$this->mountPoint = $parameters['mountPoint'];
118
-		$this->mount = $parameters['mount'];
119
-		$this->encryptionManager = $encryptionManager;
120
-		$this->util = $util;
121
-		$this->logger = $logger;
122
-		$this->uid = $uid;
123
-		$this->fileHelper = $fileHelper;
124
-		$this->keyStorage = $keyStorage;
125
-		$this->unencryptedSize = array();
126
-		$this->update = $update;
127
-		$this->mountManager = $mountManager;
128
-		$this->arrayCache = $arrayCache;
129
-		parent::__construct($parameters);
130
-	}
131
-
132
-	/**
133
-	 * see http://php.net/manual/en/function.filesize.php
134
-	 * The result for filesize when called on a folder is required to be 0
135
-	 *
136
-	 * @param string $path
137
-	 * @return int
138
-	 */
139
-	public function filesize($path) {
140
-		$fullPath = $this->getFullPath($path);
141
-
142
-		/** @var CacheEntry $info */
143
-		$info = $this->getCache()->get($path);
144
-		if (isset($this->unencryptedSize[$fullPath])) {
145
-			$size = $this->unencryptedSize[$fullPath];
146
-			// update file cache
147
-			if ($info instanceof ICacheEntry) {
148
-				$info = $info->getData();
149
-				$info['encrypted'] = $info['encryptedVersion'];
150
-			} else {
151
-				if (!is_array($info)) {
152
-					$info = [];
153
-				}
154
-				$info['encrypted'] = true;
155
-			}
156
-
157
-			$info['size'] = $size;
158
-			$this->getCache()->put($path, $info);
159
-
160
-			return $size;
161
-		}
162
-
163
-		if (isset($info['fileid']) && $info['encrypted']) {
164
-			return $this->verifyUnencryptedSize($path, $info['size']);
165
-		}
166
-
167
-		return $this->storage->filesize($path);
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @return array
173
-	 */
174
-	public function getMetaData($path) {
175
-		$data = $this->storage->getMetaData($path);
176
-		if (is_null($data)) {
177
-			return null;
178
-		}
179
-		$fullPath = $this->getFullPath($path);
180
-		$info = $this->getCache()->get($path);
181
-
182
-		if (isset($this->unencryptedSize[$fullPath])) {
183
-			$data['encrypted'] = true;
184
-			$data['size'] = $this->unencryptedSize[$fullPath];
185
-		} else {
186
-			if (isset($info['fileid']) && $info['encrypted']) {
187
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
-				$data['encrypted'] = true;
189
-			}
190
-		}
191
-
192
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
-			$data['encryptedVersion'] = $info['encryptedVersion'];
194
-		}
195
-
196
-		return $data;
197
-	}
198
-
199
-	/**
200
-	 * see http://php.net/manual/en/function.file_get_contents.php
201
-	 *
202
-	 * @param string $path
203
-	 * @return string
204
-	 */
205
-	public function file_get_contents($path) {
206
-
207
-		$encryptionModule = $this->getEncryptionModule($path);
208
-
209
-		if ($encryptionModule) {
210
-			$handle = $this->fopen($path, "r");
211
-			if (!$handle) {
212
-				return false;
213
-			}
214
-			$data = stream_get_contents($handle);
215
-			fclose($handle);
216
-			return $data;
217
-		}
218
-		return $this->storage->file_get_contents($path);
219
-	}
220
-
221
-	/**
222
-	 * see http://php.net/manual/en/function.file_put_contents.php
223
-	 *
224
-	 * @param string $path
225
-	 * @param string $data
226
-	 * @return bool
227
-	 */
228
-	public function file_put_contents($path, $data) {
229
-		// file put content will always be translated to a stream write
230
-		$handle = $this->fopen($path, 'w');
231
-		if (is_resource($handle)) {
232
-			$written = fwrite($handle, $data);
233
-			fclose($handle);
234
-			return $written;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * see http://php.net/manual/en/function.unlink.php
242
-	 *
243
-	 * @param string $path
244
-	 * @return bool
245
-	 */
246
-	public function unlink($path) {
247
-		$fullPath = $this->getFullPath($path);
248
-		if ($this->util->isExcluded($fullPath)) {
249
-			return $this->storage->unlink($path);
250
-		}
251
-
252
-		$encryptionModule = $this->getEncryptionModule($path);
253
-		if ($encryptionModule) {
254
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
-		}
256
-
257
-		return $this->storage->unlink($path);
258
-	}
259
-
260
-	/**
261
-	 * see http://php.net/manual/en/function.rename.php
262
-	 *
263
-	 * @param string $path1
264
-	 * @param string $path2
265
-	 * @return bool
266
-	 */
267
-	public function rename($path1, $path2) {
268
-
269
-		$result = $this->storage->rename($path1, $path2);
270
-
271
-		if ($result &&
272
-			// versions always use the keys from the original file, so we can skip
273
-			// this step for versions
274
-			$this->isVersion($path2) === false &&
275
-			$this->encryptionManager->isEnabled()) {
276
-			$source = $this->getFullPath($path1);
277
-			if (!$this->util->isExcluded($source)) {
278
-				$target = $this->getFullPath($path2);
279
-				if (isset($this->unencryptedSize[$source])) {
280
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
-				}
282
-				$this->keyStorage->renameKeys($source, $target);
283
-				$module = $this->getEncryptionModule($path2);
284
-				if ($module) {
285
-					$module->update($target, $this->uid, []);
286
-				}
287
-			}
288
-		}
289
-
290
-		return $result;
291
-	}
292
-
293
-	/**
294
-	 * see http://php.net/manual/en/function.rmdir.php
295
-	 *
296
-	 * @param string $path
297
-	 * @return bool
298
-	 */
299
-	public function rmdir($path) {
300
-		$result = $this->storage->rmdir($path);
301
-		$fullPath = $this->getFullPath($path);
302
-		if ($result &&
303
-			$this->util->isExcluded($fullPath) === false &&
304
-			$this->encryptionManager->isEnabled()
305
-		) {
306
-			$this->keyStorage->deleteAllFileKeys($fullPath);
307
-		}
308
-
309
-		return $result;
310
-	}
311
-
312
-	/**
313
-	 * check if a file can be read
314
-	 *
315
-	 * @param string $path
316
-	 * @return bool
317
-	 */
318
-	public function isReadable($path) {
319
-
320
-		$isReadable = true;
321
-
322
-		$metaData = $this->getMetaData($path);
323
-		if (
324
-			!$this->is_dir($path) &&
325
-			isset($metaData['encrypted']) &&
326
-			$metaData['encrypted'] === true
327
-		) {
328
-			$fullPath = $this->getFullPath($path);
329
-			$module = $this->getEncryptionModule($path);
330
-			$isReadable = $module->isReadable($fullPath, $this->uid);
331
-		}
332
-
333
-		return $this->storage->isReadable($path) && $isReadable;
334
-	}
335
-
336
-	/**
337
-	 * see http://php.net/manual/en/function.copy.php
338
-	 *
339
-	 * @param string $path1
340
-	 * @param string $path2
341
-	 * @return bool
342
-	 */
343
-	public function copy($path1, $path2) {
344
-
345
-		$source = $this->getFullPath($path1);
346
-
347
-		if ($this->util->isExcluded($source)) {
348
-			return $this->storage->copy($path1, $path2);
349
-		}
350
-
351
-		// need to stream copy file by file in case we copy between a encrypted
352
-		// and a unencrypted storage
353
-		$this->unlink($path2);
354
-		return $this->copyFromStorage($this, $path1, $path2);
355
-	}
356
-
357
-	/**
358
-	 * see http://php.net/manual/en/function.fopen.php
359
-	 *
360
-	 * @param string $path
361
-	 * @param string $mode
362
-	 * @return resource|bool
363
-	 * @throws GenericEncryptionException
364
-	 * @throws ModuleDoesNotExistsException
365
-	 */
366
-	public function fopen($path, $mode) {
367
-
368
-		// check if the file is stored in the array cache, this means that we
369
-		// copy a file over to the versions folder, in this case we don't want to
370
-		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
373
-			return $this->storage->fopen($path, $mode);
374
-		}
375
-
376
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
377
-		$shouldEncrypt = false;
378
-		$encryptionModule = null;
379
-		$header = $this->getHeader($path);
380
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
381
-		$fullPath = $this->getFullPath($path);
382
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
-
384
-		if ($this->util->isExcluded($fullPath) === false) {
385
-
386
-			$size = $unencryptedSize = 0;
387
-			$realFile = $this->util->stripPartialFileExtension($path);
388
-			$targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
-			$targetIsEncrypted = false;
390
-			if ($targetExists) {
391
-				// in case the file exists we require the explicit module as
392
-				// specified in the file header - otherwise we need to fail hard to
393
-				// prevent data loss on client side
394
-				if (!empty($encryptionModuleId)) {
395
-					$targetIsEncrypted = true;
396
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
-				}
398
-
399
-				if ($this->file_exists($path)) {
400
-					$size = $this->storage->filesize($path);
401
-					$unencryptedSize = $this->filesize($path);
402
-				} else {
403
-					$size = $unencryptedSize = 0;
404
-				}
405
-			}
406
-
407
-			try {
408
-
409
-				if (
410
-					$mode === 'w'
411
-					|| $mode === 'w+'
412
-					|| $mode === 'wb'
413
-					|| $mode === 'wb+'
414
-				) {
415
-					// don't overwrite encrypted files if encryption is not enabled
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
-					}
419
-					if ($encryptionEnabled) {
420
-						// if $encryptionModuleId is empty, the default module will be used
421
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
-						$signed = true;
424
-					}
425
-				} else {
426
-					$info = $this->getCache()->get($path);
427
-					// only get encryption module if we found one in the header
428
-					// or if file should be encrypted according to the file cache
429
-					if (!empty($encryptionModuleId)) {
430
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
-						$shouldEncrypt = true;
432
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
-						// we come from a old installation. No header and/or no module defined
434
-						// but the file is encrypted. In this case we need to use the
435
-						// OC_DEFAULT_MODULE to read the file
436
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
-						$shouldEncrypt = true;
438
-						$targetIsEncrypted = true;
439
-					}
440
-				}
441
-			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->logException($e, [
443
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
444
-					'level' => \OCP\Util::WARN,
445
-					'app' => 'core',
446
-				]);
447
-			}
448
-
449
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
450
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
451
-				if (!$targetExists || !$targetIsEncrypted) {
452
-					$shouldEncrypt = false;
453
-				}
454
-			}
455
-
456
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
457
-				$headerSize = $this->getHeaderSize($path);
458
-				$source = $this->storage->fopen($path, $mode);
459
-				if (!is_resource($source)) {
460
-					return false;
461
-				}
462
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
463
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
464
-					$size, $unencryptedSize, $headerSize, $signed);
465
-				return $handle;
466
-			}
467
-
468
-		}
469
-
470
-		return $this->storage->fopen($path, $mode);
471
-	}
472
-
473
-
474
-	/**
475
-	 * perform some plausibility checks if the the unencrypted size is correct.
476
-	 * If not, we calculate the correct unencrypted size and return it
477
-	 *
478
-	 * @param string $path internal path relative to the storage root
479
-	 * @param int $unencryptedSize size of the unencrypted file
480
-	 *
481
-	 * @return int unencrypted size
482
-	 */
483
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
484
-
485
-		$size = $this->storage->filesize($path);
486
-		$result = $unencryptedSize;
487
-
488
-		if ($unencryptedSize < 0 ||
489
-			($size > 0 && $unencryptedSize === $size)
490
-		) {
491
-			// check if we already calculate the unencrypted size for the
492
-			// given path to avoid recursions
493
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
494
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
495
-				try {
496
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
497
-				} catch (\Exception $e) {
498
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
499
-					$this->logger->logException($e);
500
-				}
501
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
502
-			}
503
-		}
504
-
505
-		return $result;
506
-	}
507
-
508
-	/**
509
-	 * calculate the unencrypted size
510
-	 *
511
-	 * @param string $path internal path relative to the storage root
512
-	 * @param int $size size of the physical file
513
-	 * @param int $unencryptedSize size of the unencrypted file
514
-	 *
515
-	 * @return int calculated unencrypted size
516
-	 */
517
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
518
-
519
-		$headerSize = $this->getHeaderSize($path);
520
-		$header = $this->getHeader($path);
521
-		$encryptionModule = $this->getEncryptionModule($path);
522
-
523
-		$stream = $this->storage->fopen($path, 'r');
524
-
525
-		// if we couldn't open the file we return the old unencrypted size
526
-		if (!is_resource($stream)) {
527
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
528
-			return $unencryptedSize;
529
-		}
530
-
531
-		$newUnencryptedSize = 0;
532
-		$size -= $headerSize;
533
-		$blockSize = $this->util->getBlockSize();
534
-
535
-		// if a header exists we skip it
536
-		if ($headerSize > 0) {
537
-			fread($stream, $headerSize);
538
-		}
539
-
540
-		// fast path, else the calculation for $lastChunkNr is bogus
541
-		if ($size === 0) {
542
-			return 0;
543
-		}
544
-
545
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
546
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
547
-
548
-		// calculate last chunk nr
549
-		// next highest is end of chunks, one subtracted is last one
550
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
551
-
552
-		$lastChunkNr = ceil($size/ $blockSize)-1;
553
-		// calculate last chunk position
554
-		$lastChunkPos = ($lastChunkNr * $blockSize);
555
-		// try to fseek to the last chunk, if it fails we have to read the whole file
556
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
557
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
558
-		}
559
-
560
-		$lastChunkContentEncrypted='';
561
-		$count = $blockSize;
562
-
563
-		while ($count > 0) {
564
-			$data=fread($stream, $blockSize);
565
-			$count=strlen($data);
566
-			$lastChunkContentEncrypted .= $data;
567
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
568
-				$newUnencryptedSize += $unencryptedBlockSize;
569
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
570
-			}
571
-		}
572
-
573
-		fclose($stream);
574
-
575
-		// we have to decrypt the last chunk to get it actual size
576
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
577
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
578
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
579
-
580
-		// calc the real file size with the size of the last chunk
581
-		$newUnencryptedSize += strlen($decryptedLastChunk);
582
-
583
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
584
-
585
-		// write to cache if applicable
586
-		$cache = $this->storage->getCache();
587
-		if ($cache) {
588
-			$entry = $cache->get($path);
589
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
590
-		}
591
-
592
-		return $newUnencryptedSize;
593
-	}
594
-
595
-	/**
596
-	 * @param Storage\IStorage $sourceStorage
597
-	 * @param string $sourceInternalPath
598
-	 * @param string $targetInternalPath
599
-	 * @param bool $preserveMtime
600
-	 * @return bool
601
-	 */
602
-	public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
603
-		if ($sourceStorage === $this) {
604
-			return $this->rename($sourceInternalPath, $targetInternalPath);
605
-		}
606
-
607
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
608
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
609
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
610
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
611
-		// - remove $this->copyBetweenStorage
612
-
613
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
614
-			return false;
615
-		}
616
-
617
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
618
-		if ($result) {
619
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
620
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
621
-			} else {
622
-				$result &= $sourceStorage->unlink($sourceInternalPath);
623
-			}
624
-		}
625
-		return $result;
626
-	}
627
-
628
-
629
-	/**
630
-	 * @param Storage\IStorage $sourceStorage
631
-	 * @param string $sourceInternalPath
632
-	 * @param string $targetInternalPath
633
-	 * @param bool $preserveMtime
634
-	 * @param bool $isRename
635
-	 * @return bool
636
-	 */
637
-	public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
638
-
639
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
640
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
641
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
642
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
643
-		// - remove $this->copyBetweenStorage
644
-
645
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
646
-	}
647
-
648
-	/**
649
-	 * Update the encrypted cache version in the database
650
-	 *
651
-	 * @param Storage\IStorage $sourceStorage
652
-	 * @param string $sourceInternalPath
653
-	 * @param string $targetInternalPath
654
-	 * @param bool $isRename
655
-	 */
656
-	private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
657
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
658
-		$cacheInformation = [
659
-			'encrypted' => (bool)$isEncrypted,
660
-		];
661
-		if($isEncrypted === 1) {
662
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
663
-
664
-			// In case of a move operation from an unencrypted to an encrypted
665
-			// storage the old encrypted version would stay with "0" while the
666
-			// correct value would be "1". Thus we manually set the value to "1"
667
-			// for those cases.
668
-			// See also https://github.com/owncloud/core/issues/23078
669
-			if($encryptedVersion === 0) {
670
-				$encryptedVersion = 1;
671
-			}
672
-
673
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
674
-		}
675
-
676
-		// in case of a rename we need to manipulate the source cache because
677
-		// this information will be kept for the new target
678
-		if ($isRename) {
679
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
680
-		} else {
681
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
682
-		}
683
-	}
684
-
685
-	/**
686
-	 * copy file between two storages
687
-	 *
688
-	 * @param Storage\IStorage $sourceStorage
689
-	 * @param string $sourceInternalPath
690
-	 * @param string $targetInternalPath
691
-	 * @param bool $preserveMtime
692
-	 * @param bool $isRename
693
-	 * @return bool
694
-	 * @throws \Exception
695
-	 */
696
-	private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
697
-
698
-		// for versions we have nothing to do, because versions should always use the
699
-		// key from the original file. Just create a 1:1 copy and done
700
-		if ($this->isVersion($targetInternalPath) ||
701
-			$this->isVersion($sourceInternalPath)) {
702
-			// remember that we try to create a version so that we can detect it during
703
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
704
-			// create a 1:1 copy of the file
705
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
706
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
707
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
708
-			if ($result) {
709
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
710
-				// make sure that we update the unencrypted size for the version
711
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
712
-					$this->updateUnencryptedSize(
713
-						$this->getFullPath($targetInternalPath),
714
-						$info['size']
715
-					);
716
-				}
717
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
718
-			}
719
-			return $result;
720
-		}
721
-
722
-		// first copy the keys that we reuse the existing file key on the target location
723
-		// and don't create a new one which would break versions for example.
724
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
725
-		if (count($mount) === 1) {
726
-			$mountPoint = $mount[0]->getMountPoint();
727
-			$source = $mountPoint . '/' . $sourceInternalPath;
728
-			$target = $this->getFullPath($targetInternalPath);
729
-			$this->copyKeys($source, $target);
730
-		} else {
731
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
732
-		}
733
-
734
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
735
-			$dh = $sourceStorage->opendir($sourceInternalPath);
736
-			$result = $this->mkdir($targetInternalPath);
737
-			if (is_resource($dh)) {
738
-				while ($result and ($file = readdir($dh)) !== false) {
739
-					if (!Filesystem::isIgnoredDir($file)) {
740
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
741
-					}
742
-				}
743
-			}
744
-		} else {
745
-			try {
746
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
747
-				$target = $this->fopen($targetInternalPath, 'w');
748
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
749
-				fclose($source);
750
-				fclose($target);
751
-			} catch (\Exception $e) {
752
-				fclose($source);
753
-				fclose($target);
754
-				throw $e;
755
-			}
756
-			if($result) {
757
-				if ($preserveMtime) {
758
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
759
-				}
760
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
761
-			} else {
762
-				// delete partially written target file
763
-				$this->unlink($targetInternalPath);
764
-				// delete cache entry that was created by fopen
765
-				$this->getCache()->remove($targetInternalPath);
766
-			}
767
-		}
768
-		return (bool)$result;
769
-
770
-	}
771
-
772
-	/**
773
-	 * get the path to a local version of the file.
774
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
775
-	 *
776
-	 * @param string $path
777
-	 * @return string
778
-	 */
779
-	public function getLocalFile($path) {
780
-		if ($this->encryptionManager->isEnabled()) {
781
-			$cachedFile = $this->getCachedFile($path);
782
-			if (is_string($cachedFile)) {
783
-				return $cachedFile;
784
-			}
785
-		}
786
-		return $this->storage->getLocalFile($path);
787
-	}
788
-
789
-	/**
790
-	 * Returns the wrapped storage's value for isLocal()
791
-	 *
792
-	 * @return bool wrapped storage's isLocal() value
793
-	 */
794
-	public function isLocal() {
795
-		if ($this->encryptionManager->isEnabled()) {
796
-			return false;
797
-		}
798
-		return $this->storage->isLocal();
799
-	}
800
-
801
-	/**
802
-	 * see http://php.net/manual/en/function.stat.php
803
-	 * only the following keys are required in the result: size and mtime
804
-	 *
805
-	 * @param string $path
806
-	 * @return array
807
-	 */
808
-	public function stat($path) {
809
-		$stat = $this->storage->stat($path);
810
-		$fileSize = $this->filesize($path);
811
-		$stat['size'] = $fileSize;
812
-		$stat[7] = $fileSize;
813
-		return $stat;
814
-	}
815
-
816
-	/**
817
-	 * see http://php.net/manual/en/function.hash.php
818
-	 *
819
-	 * @param string $type
820
-	 * @param string $path
821
-	 * @param bool $raw
822
-	 * @return string
823
-	 */
824
-	public function hash($type, $path, $raw = false) {
825
-		$fh = $this->fopen($path, 'rb');
826
-		$ctx = hash_init($type);
827
-		hash_update_stream($ctx, $fh);
828
-		fclose($fh);
829
-		return hash_final($ctx, $raw);
830
-	}
831
-
832
-	/**
833
-	 * return full path, including mount point
834
-	 *
835
-	 * @param string $path relative to mount point
836
-	 * @return string full path including mount point
837
-	 */
838
-	protected function getFullPath($path) {
839
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
840
-	}
841
-
842
-	/**
843
-	 * read first block of encrypted file, typically this will contain the
844
-	 * encryption header
845
-	 *
846
-	 * @param string $path
847
-	 * @return string
848
-	 */
849
-	protected function readFirstBlock($path) {
850
-		$firstBlock = '';
851
-		if ($this->storage->file_exists($path)) {
852
-			$handle = $this->storage->fopen($path, 'r');
853
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
854
-			fclose($handle);
855
-		}
856
-		return $firstBlock;
857
-	}
858
-
859
-	/**
860
-	 * return header size of given file
861
-	 *
862
-	 * @param string $path
863
-	 * @return int
864
-	 */
865
-	protected function getHeaderSize($path) {
866
-		$headerSize = 0;
867
-		$realFile = $this->util->stripPartialFileExtension($path);
868
-		if ($this->storage->file_exists($realFile)) {
869
-			$path = $realFile;
870
-		}
871
-		$firstBlock = $this->readFirstBlock($path);
872
-
873
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
874
-			$headerSize = $this->util->getHeaderSize();
875
-		}
876
-
877
-		return $headerSize;
878
-	}
879
-
880
-	/**
881
-	 * parse raw header to array
882
-	 *
883
-	 * @param string $rawHeader
884
-	 * @return array
885
-	 */
886
-	protected function parseRawHeader($rawHeader) {
887
-		$result = array();
888
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
889
-			$header = $rawHeader;
890
-			$endAt = strpos($header, Util::HEADER_END);
891
-			if ($endAt !== false) {
892
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
893
-
894
-				// +1 to not start with an ':' which would result in empty element at the beginning
895
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
896
-
897
-				$element = array_shift($exploded);
898
-				while ($element !== Util::HEADER_END) {
899
-					$result[$element] = array_shift($exploded);
900
-					$element = array_shift($exploded);
901
-				}
902
-			}
903
-		}
904
-
905
-		return $result;
906
-	}
907
-
908
-	/**
909
-	 * read header from file
910
-	 *
911
-	 * @param string $path
912
-	 * @return array
913
-	 */
914
-	protected function getHeader($path) {
915
-		$realFile = $this->util->stripPartialFileExtension($path);
916
-		$exists = $this->storage->file_exists($realFile);
917
-		if ($exists) {
918
-			$path = $realFile;
919
-		}
920
-
921
-		$firstBlock = $this->readFirstBlock($path);
922
-		$result = $this->parseRawHeader($firstBlock);
923
-
924
-		// if the header doesn't contain a encryption module we check if it is a
925
-		// legacy file. If true, we add the default encryption module
926
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
927
-			if (!empty($result)) {
928
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
929
-			} else if ($exists) {
930
-				// if the header was empty we have to check first if it is a encrypted file at all
931
-				// We would do query to filecache only if we know that entry in filecache exists
932
-				$info = $this->getCache()->get($path);
933
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
934
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
935
-				}
936
-			}
937
-		}
938
-
939
-		return $result;
940
-	}
941
-
942
-	/**
943
-	 * read encryption module needed to read/write the file located at $path
944
-	 *
945
-	 * @param string $path
946
-	 * @return null|\OCP\Encryption\IEncryptionModule
947
-	 * @throws ModuleDoesNotExistsException
948
-	 * @throws \Exception
949
-	 */
950
-	protected function getEncryptionModule($path) {
951
-		$encryptionModule = null;
952
-		$header = $this->getHeader($path);
953
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
954
-		if (!empty($encryptionModuleId)) {
955
-			try {
956
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
957
-			} catch (ModuleDoesNotExistsException $e) {
958
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
959
-				throw $e;
960
-			}
961
-		}
962
-
963
-		return $encryptionModule;
964
-	}
965
-
966
-	/**
967
-	 * @param string $path
968
-	 * @param int $unencryptedSize
969
-	 */
970
-	public function updateUnencryptedSize($path, $unencryptedSize) {
971
-		$this->unencryptedSize[$path] = $unencryptedSize;
972
-	}
973
-
974
-	/**
975
-	 * copy keys to new location
976
-	 *
977
-	 * @param string $source path relative to data/
978
-	 * @param string $target path relative to data/
979
-	 * @return bool
980
-	 */
981
-	protected function copyKeys($source, $target) {
982
-		if (!$this->util->isExcluded($source)) {
983
-			return $this->keyStorage->copyKeys($source, $target);
984
-		}
985
-
986
-		return false;
987
-	}
988
-
989
-	/**
990
-	 * check if path points to a files version
991
-	 *
992
-	 * @param $path
993
-	 * @return bool
994
-	 */
995
-	protected function isVersion($path) {
996
-		$normalized = Filesystem::normalizePath($path);
997
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
998
-	}
999
-
1000
-	/**
1001
-	 * check if the given storage should be encrypted or not
1002
-	 *
1003
-	 * @param $path
1004
-	 * @return bool
1005
-	 */
1006
-	protected function shouldEncrypt($path) {
1007
-		$fullPath = $this->getFullPath($path);
1008
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1009
-		if ($mountPointConfig === false) {
1010
-			return false;
1011
-		}
1012
-
1013
-		try {
1014
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1015
-		} catch (ModuleDoesNotExistsException $e) {
1016
-			return false;
1017
-		}
1018
-
1019
-		if ($encryptionModule === null) {
1020
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1021
-		}
1022
-
1023
-		return $encryptionModule->shouldEncrypt($fullPath);
1024
-
1025
-	}
51
+    use LocalTempFileTrait;
52
+
53
+    /** @var string */
54
+    private $mountPoint;
55
+
56
+    /** @var \OC\Encryption\Util */
57
+    private $util;
58
+
59
+    /** @var \OCP\Encryption\IManager */
60
+    private $encryptionManager;
61
+
62
+    /** @var \OCP\ILogger */
63
+    private $logger;
64
+
65
+    /** @var string */
66
+    private $uid;
67
+
68
+    /** @var array */
69
+    protected $unencryptedSize;
70
+
71
+    /** @var \OCP\Encryption\IFile */
72
+    private $fileHelper;
73
+
74
+    /** @var IMountPoint */
75
+    private $mount;
76
+
77
+    /** @var IStorage */
78
+    private $keyStorage;
79
+
80
+    /** @var Update */
81
+    private $update;
82
+
83
+    /** @var Manager */
84
+    private $mountManager;
85
+
86
+    /** @var array remember for which path we execute the repair step to avoid recursions */
87
+    private $fixUnencryptedSizeOf = array();
88
+
89
+    /** @var  ArrayCache */
90
+    private $arrayCache;
91
+
92
+    /**
93
+     * @param array $parameters
94
+     * @param IManager $encryptionManager
95
+     * @param Util $util
96
+     * @param ILogger $logger
97
+     * @param IFile $fileHelper
98
+     * @param string $uid
99
+     * @param IStorage $keyStorage
100
+     * @param Update $update
101
+     * @param Manager $mountManager
102
+     * @param ArrayCache $arrayCache
103
+     */
104
+    public function __construct(
105
+            $parameters,
106
+            IManager $encryptionManager = null,
107
+            Util $util = null,
108
+            ILogger $logger = null,
109
+            IFile $fileHelper = null,
110
+            $uid = null,
111
+            IStorage $keyStorage = null,
112
+            Update $update = null,
113
+            Manager $mountManager = null,
114
+            ArrayCache $arrayCache = null
115
+        ) {
116
+
117
+        $this->mountPoint = $parameters['mountPoint'];
118
+        $this->mount = $parameters['mount'];
119
+        $this->encryptionManager = $encryptionManager;
120
+        $this->util = $util;
121
+        $this->logger = $logger;
122
+        $this->uid = $uid;
123
+        $this->fileHelper = $fileHelper;
124
+        $this->keyStorage = $keyStorage;
125
+        $this->unencryptedSize = array();
126
+        $this->update = $update;
127
+        $this->mountManager = $mountManager;
128
+        $this->arrayCache = $arrayCache;
129
+        parent::__construct($parameters);
130
+    }
131
+
132
+    /**
133
+     * see http://php.net/manual/en/function.filesize.php
134
+     * The result for filesize when called on a folder is required to be 0
135
+     *
136
+     * @param string $path
137
+     * @return int
138
+     */
139
+    public function filesize($path) {
140
+        $fullPath = $this->getFullPath($path);
141
+
142
+        /** @var CacheEntry $info */
143
+        $info = $this->getCache()->get($path);
144
+        if (isset($this->unencryptedSize[$fullPath])) {
145
+            $size = $this->unencryptedSize[$fullPath];
146
+            // update file cache
147
+            if ($info instanceof ICacheEntry) {
148
+                $info = $info->getData();
149
+                $info['encrypted'] = $info['encryptedVersion'];
150
+            } else {
151
+                if (!is_array($info)) {
152
+                    $info = [];
153
+                }
154
+                $info['encrypted'] = true;
155
+            }
156
+
157
+            $info['size'] = $size;
158
+            $this->getCache()->put($path, $info);
159
+
160
+            return $size;
161
+        }
162
+
163
+        if (isset($info['fileid']) && $info['encrypted']) {
164
+            return $this->verifyUnencryptedSize($path, $info['size']);
165
+        }
166
+
167
+        return $this->storage->filesize($path);
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @return array
173
+     */
174
+    public function getMetaData($path) {
175
+        $data = $this->storage->getMetaData($path);
176
+        if (is_null($data)) {
177
+            return null;
178
+        }
179
+        $fullPath = $this->getFullPath($path);
180
+        $info = $this->getCache()->get($path);
181
+
182
+        if (isset($this->unencryptedSize[$fullPath])) {
183
+            $data['encrypted'] = true;
184
+            $data['size'] = $this->unencryptedSize[$fullPath];
185
+        } else {
186
+            if (isset($info['fileid']) && $info['encrypted']) {
187
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
188
+                $data['encrypted'] = true;
189
+            }
190
+        }
191
+
192
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
193
+            $data['encryptedVersion'] = $info['encryptedVersion'];
194
+        }
195
+
196
+        return $data;
197
+    }
198
+
199
+    /**
200
+     * see http://php.net/manual/en/function.file_get_contents.php
201
+     *
202
+     * @param string $path
203
+     * @return string
204
+     */
205
+    public function file_get_contents($path) {
206
+
207
+        $encryptionModule = $this->getEncryptionModule($path);
208
+
209
+        if ($encryptionModule) {
210
+            $handle = $this->fopen($path, "r");
211
+            if (!$handle) {
212
+                return false;
213
+            }
214
+            $data = stream_get_contents($handle);
215
+            fclose($handle);
216
+            return $data;
217
+        }
218
+        return $this->storage->file_get_contents($path);
219
+    }
220
+
221
+    /**
222
+     * see http://php.net/manual/en/function.file_put_contents.php
223
+     *
224
+     * @param string $path
225
+     * @param string $data
226
+     * @return bool
227
+     */
228
+    public function file_put_contents($path, $data) {
229
+        // file put content will always be translated to a stream write
230
+        $handle = $this->fopen($path, 'w');
231
+        if (is_resource($handle)) {
232
+            $written = fwrite($handle, $data);
233
+            fclose($handle);
234
+            return $written;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * see http://php.net/manual/en/function.unlink.php
242
+     *
243
+     * @param string $path
244
+     * @return bool
245
+     */
246
+    public function unlink($path) {
247
+        $fullPath = $this->getFullPath($path);
248
+        if ($this->util->isExcluded($fullPath)) {
249
+            return $this->storage->unlink($path);
250
+        }
251
+
252
+        $encryptionModule = $this->getEncryptionModule($path);
253
+        if ($encryptionModule) {
254
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
255
+        }
256
+
257
+        return $this->storage->unlink($path);
258
+    }
259
+
260
+    /**
261
+     * see http://php.net/manual/en/function.rename.php
262
+     *
263
+     * @param string $path1
264
+     * @param string $path2
265
+     * @return bool
266
+     */
267
+    public function rename($path1, $path2) {
268
+
269
+        $result = $this->storage->rename($path1, $path2);
270
+
271
+        if ($result &&
272
+            // versions always use the keys from the original file, so we can skip
273
+            // this step for versions
274
+            $this->isVersion($path2) === false &&
275
+            $this->encryptionManager->isEnabled()) {
276
+            $source = $this->getFullPath($path1);
277
+            if (!$this->util->isExcluded($source)) {
278
+                $target = $this->getFullPath($path2);
279
+                if (isset($this->unencryptedSize[$source])) {
280
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
281
+                }
282
+                $this->keyStorage->renameKeys($source, $target);
283
+                $module = $this->getEncryptionModule($path2);
284
+                if ($module) {
285
+                    $module->update($target, $this->uid, []);
286
+                }
287
+            }
288
+        }
289
+
290
+        return $result;
291
+    }
292
+
293
+    /**
294
+     * see http://php.net/manual/en/function.rmdir.php
295
+     *
296
+     * @param string $path
297
+     * @return bool
298
+     */
299
+    public function rmdir($path) {
300
+        $result = $this->storage->rmdir($path);
301
+        $fullPath = $this->getFullPath($path);
302
+        if ($result &&
303
+            $this->util->isExcluded($fullPath) === false &&
304
+            $this->encryptionManager->isEnabled()
305
+        ) {
306
+            $this->keyStorage->deleteAllFileKeys($fullPath);
307
+        }
308
+
309
+        return $result;
310
+    }
311
+
312
+    /**
313
+     * check if a file can be read
314
+     *
315
+     * @param string $path
316
+     * @return bool
317
+     */
318
+    public function isReadable($path) {
319
+
320
+        $isReadable = true;
321
+
322
+        $metaData = $this->getMetaData($path);
323
+        if (
324
+            !$this->is_dir($path) &&
325
+            isset($metaData['encrypted']) &&
326
+            $metaData['encrypted'] === true
327
+        ) {
328
+            $fullPath = $this->getFullPath($path);
329
+            $module = $this->getEncryptionModule($path);
330
+            $isReadable = $module->isReadable($fullPath, $this->uid);
331
+        }
332
+
333
+        return $this->storage->isReadable($path) && $isReadable;
334
+    }
335
+
336
+    /**
337
+     * see http://php.net/manual/en/function.copy.php
338
+     *
339
+     * @param string $path1
340
+     * @param string $path2
341
+     * @return bool
342
+     */
343
+    public function copy($path1, $path2) {
344
+
345
+        $source = $this->getFullPath($path1);
346
+
347
+        if ($this->util->isExcluded($source)) {
348
+            return $this->storage->copy($path1, $path2);
349
+        }
350
+
351
+        // need to stream copy file by file in case we copy between a encrypted
352
+        // and a unencrypted storage
353
+        $this->unlink($path2);
354
+        return $this->copyFromStorage($this, $path1, $path2);
355
+    }
356
+
357
+    /**
358
+     * see http://php.net/manual/en/function.fopen.php
359
+     *
360
+     * @param string $path
361
+     * @param string $mode
362
+     * @return resource|bool
363
+     * @throws GenericEncryptionException
364
+     * @throws ModuleDoesNotExistsException
365
+     */
366
+    public function fopen($path, $mode) {
367
+
368
+        // check if the file is stored in the array cache, this means that we
369
+        // copy a file over to the versions folder, in this case we don't want to
370
+        // decrypt it
371
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
373
+            return $this->storage->fopen($path, $mode);
374
+        }
375
+
376
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
377
+        $shouldEncrypt = false;
378
+        $encryptionModule = null;
379
+        $header = $this->getHeader($path);
380
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
381
+        $fullPath = $this->getFullPath($path);
382
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
383
+
384
+        if ($this->util->isExcluded($fullPath) === false) {
385
+
386
+            $size = $unencryptedSize = 0;
387
+            $realFile = $this->util->stripPartialFileExtension($path);
388
+            $targetExists = $this->file_exists($realFile) || $this->file_exists($path);
389
+            $targetIsEncrypted = false;
390
+            if ($targetExists) {
391
+                // in case the file exists we require the explicit module as
392
+                // specified in the file header - otherwise we need to fail hard to
393
+                // prevent data loss on client side
394
+                if (!empty($encryptionModuleId)) {
395
+                    $targetIsEncrypted = true;
396
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
397
+                }
398
+
399
+                if ($this->file_exists($path)) {
400
+                    $size = $this->storage->filesize($path);
401
+                    $unencryptedSize = $this->filesize($path);
402
+                } else {
403
+                    $size = $unencryptedSize = 0;
404
+                }
405
+            }
406
+
407
+            try {
408
+
409
+                if (
410
+                    $mode === 'w'
411
+                    || $mode === 'w+'
412
+                    || $mode === 'wb'
413
+                    || $mode === 'wb+'
414
+                ) {
415
+                    // don't overwrite encrypted files if encryption is not enabled
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        throw new GenericEncryptionException('Tried to access encrypted file but encryption is not enabled');
418
+                    }
419
+                    if ($encryptionEnabled) {
420
+                        // if $encryptionModuleId is empty, the default module will be used
421
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
422
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
423
+                        $signed = true;
424
+                    }
425
+                } else {
426
+                    $info = $this->getCache()->get($path);
427
+                    // only get encryption module if we found one in the header
428
+                    // or if file should be encrypted according to the file cache
429
+                    if (!empty($encryptionModuleId)) {
430
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
431
+                        $shouldEncrypt = true;
432
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
433
+                        // we come from a old installation. No header and/or no module defined
434
+                        // but the file is encrypted. In this case we need to use the
435
+                        // OC_DEFAULT_MODULE to read the file
436
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
437
+                        $shouldEncrypt = true;
438
+                        $targetIsEncrypted = true;
439
+                    }
440
+                }
441
+            } catch (ModuleDoesNotExistsException $e) {
442
+                $this->logger->logException($e, [
443
+                    'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
444
+                    'level' => \OCP\Util::WARN,
445
+                    'app' => 'core',
446
+                ]);
447
+            }
448
+
449
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
450
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
451
+                if (!$targetExists || !$targetIsEncrypted) {
452
+                    $shouldEncrypt = false;
453
+                }
454
+            }
455
+
456
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
457
+                $headerSize = $this->getHeaderSize($path);
458
+                $source = $this->storage->fopen($path, $mode);
459
+                if (!is_resource($source)) {
460
+                    return false;
461
+                }
462
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
463
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
464
+                    $size, $unencryptedSize, $headerSize, $signed);
465
+                return $handle;
466
+            }
467
+
468
+        }
469
+
470
+        return $this->storage->fopen($path, $mode);
471
+    }
472
+
473
+
474
+    /**
475
+     * perform some plausibility checks if the the unencrypted size is correct.
476
+     * If not, we calculate the correct unencrypted size and return it
477
+     *
478
+     * @param string $path internal path relative to the storage root
479
+     * @param int $unencryptedSize size of the unencrypted file
480
+     *
481
+     * @return int unencrypted size
482
+     */
483
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
484
+
485
+        $size = $this->storage->filesize($path);
486
+        $result = $unencryptedSize;
487
+
488
+        if ($unencryptedSize < 0 ||
489
+            ($size > 0 && $unencryptedSize === $size)
490
+        ) {
491
+            // check if we already calculate the unencrypted size for the
492
+            // given path to avoid recursions
493
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
494
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
495
+                try {
496
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
497
+                } catch (\Exception $e) {
498
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
499
+                    $this->logger->logException($e);
500
+                }
501
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
502
+            }
503
+        }
504
+
505
+        return $result;
506
+    }
507
+
508
+    /**
509
+     * calculate the unencrypted size
510
+     *
511
+     * @param string $path internal path relative to the storage root
512
+     * @param int $size size of the physical file
513
+     * @param int $unencryptedSize size of the unencrypted file
514
+     *
515
+     * @return int calculated unencrypted size
516
+     */
517
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
518
+
519
+        $headerSize = $this->getHeaderSize($path);
520
+        $header = $this->getHeader($path);
521
+        $encryptionModule = $this->getEncryptionModule($path);
522
+
523
+        $stream = $this->storage->fopen($path, 'r');
524
+
525
+        // if we couldn't open the file we return the old unencrypted size
526
+        if (!is_resource($stream)) {
527
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
528
+            return $unencryptedSize;
529
+        }
530
+
531
+        $newUnencryptedSize = 0;
532
+        $size -= $headerSize;
533
+        $blockSize = $this->util->getBlockSize();
534
+
535
+        // if a header exists we skip it
536
+        if ($headerSize > 0) {
537
+            fread($stream, $headerSize);
538
+        }
539
+
540
+        // fast path, else the calculation for $lastChunkNr is bogus
541
+        if ($size === 0) {
542
+            return 0;
543
+        }
544
+
545
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
546
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
547
+
548
+        // calculate last chunk nr
549
+        // next highest is end of chunks, one subtracted is last one
550
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
551
+
552
+        $lastChunkNr = ceil($size/ $blockSize)-1;
553
+        // calculate last chunk position
554
+        $lastChunkPos = ($lastChunkNr * $blockSize);
555
+        // try to fseek to the last chunk, if it fails we have to read the whole file
556
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
557
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
558
+        }
559
+
560
+        $lastChunkContentEncrypted='';
561
+        $count = $blockSize;
562
+
563
+        while ($count > 0) {
564
+            $data=fread($stream, $blockSize);
565
+            $count=strlen($data);
566
+            $lastChunkContentEncrypted .= $data;
567
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
568
+                $newUnencryptedSize += $unencryptedBlockSize;
569
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
570
+            }
571
+        }
572
+
573
+        fclose($stream);
574
+
575
+        // we have to decrypt the last chunk to get it actual size
576
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
577
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
578
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
579
+
580
+        // calc the real file size with the size of the last chunk
581
+        $newUnencryptedSize += strlen($decryptedLastChunk);
582
+
583
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
584
+
585
+        // write to cache if applicable
586
+        $cache = $this->storage->getCache();
587
+        if ($cache) {
588
+            $entry = $cache->get($path);
589
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
590
+        }
591
+
592
+        return $newUnencryptedSize;
593
+    }
594
+
595
+    /**
596
+     * @param Storage\IStorage $sourceStorage
597
+     * @param string $sourceInternalPath
598
+     * @param string $targetInternalPath
599
+     * @param bool $preserveMtime
600
+     * @return bool
601
+     */
602
+    public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
603
+        if ($sourceStorage === $this) {
604
+            return $this->rename($sourceInternalPath, $targetInternalPath);
605
+        }
606
+
607
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
608
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
609
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
610
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
611
+        // - remove $this->copyBetweenStorage
612
+
613
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
614
+            return false;
615
+        }
616
+
617
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
618
+        if ($result) {
619
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
620
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
621
+            } else {
622
+                $result &= $sourceStorage->unlink($sourceInternalPath);
623
+            }
624
+        }
625
+        return $result;
626
+    }
627
+
628
+
629
+    /**
630
+     * @param Storage\IStorage $sourceStorage
631
+     * @param string $sourceInternalPath
632
+     * @param string $targetInternalPath
633
+     * @param bool $preserveMtime
634
+     * @param bool $isRename
635
+     * @return bool
636
+     */
637
+    public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
638
+
639
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
640
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
641
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
642
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
643
+        // - remove $this->copyBetweenStorage
644
+
645
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
646
+    }
647
+
648
+    /**
649
+     * Update the encrypted cache version in the database
650
+     *
651
+     * @param Storage\IStorage $sourceStorage
652
+     * @param string $sourceInternalPath
653
+     * @param string $targetInternalPath
654
+     * @param bool $isRename
655
+     */
656
+    private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
657
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath) ? 1 : 0;
658
+        $cacheInformation = [
659
+            'encrypted' => (bool)$isEncrypted,
660
+        ];
661
+        if($isEncrypted === 1) {
662
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
663
+
664
+            // In case of a move operation from an unencrypted to an encrypted
665
+            // storage the old encrypted version would stay with "0" while the
666
+            // correct value would be "1". Thus we manually set the value to "1"
667
+            // for those cases.
668
+            // See also https://github.com/owncloud/core/issues/23078
669
+            if($encryptedVersion === 0) {
670
+                $encryptedVersion = 1;
671
+            }
672
+
673
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
674
+        }
675
+
676
+        // in case of a rename we need to manipulate the source cache because
677
+        // this information will be kept for the new target
678
+        if ($isRename) {
679
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
680
+        } else {
681
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
682
+        }
683
+    }
684
+
685
+    /**
686
+     * copy file between two storages
687
+     *
688
+     * @param Storage\IStorage $sourceStorage
689
+     * @param string $sourceInternalPath
690
+     * @param string $targetInternalPath
691
+     * @param bool $preserveMtime
692
+     * @param bool $isRename
693
+     * @return bool
694
+     * @throws \Exception
695
+     */
696
+    private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
697
+
698
+        // for versions we have nothing to do, because versions should always use the
699
+        // key from the original file. Just create a 1:1 copy and done
700
+        if ($this->isVersion($targetInternalPath) ||
701
+            $this->isVersion($sourceInternalPath)) {
702
+            // remember that we try to create a version so that we can detect it during
703
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
704
+            // create a 1:1 copy of the file
705
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
706
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
707
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
708
+            if ($result) {
709
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
710
+                // make sure that we update the unencrypted size for the version
711
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
712
+                    $this->updateUnencryptedSize(
713
+                        $this->getFullPath($targetInternalPath),
714
+                        $info['size']
715
+                    );
716
+                }
717
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
718
+            }
719
+            return $result;
720
+        }
721
+
722
+        // first copy the keys that we reuse the existing file key on the target location
723
+        // and don't create a new one which would break versions for example.
724
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
725
+        if (count($mount) === 1) {
726
+            $mountPoint = $mount[0]->getMountPoint();
727
+            $source = $mountPoint . '/' . $sourceInternalPath;
728
+            $target = $this->getFullPath($targetInternalPath);
729
+            $this->copyKeys($source, $target);
730
+        } else {
731
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
732
+        }
733
+
734
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
735
+            $dh = $sourceStorage->opendir($sourceInternalPath);
736
+            $result = $this->mkdir($targetInternalPath);
737
+            if (is_resource($dh)) {
738
+                while ($result and ($file = readdir($dh)) !== false) {
739
+                    if (!Filesystem::isIgnoredDir($file)) {
740
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
741
+                    }
742
+                }
743
+            }
744
+        } else {
745
+            try {
746
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
747
+                $target = $this->fopen($targetInternalPath, 'w');
748
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
749
+                fclose($source);
750
+                fclose($target);
751
+            } catch (\Exception $e) {
752
+                fclose($source);
753
+                fclose($target);
754
+                throw $e;
755
+            }
756
+            if($result) {
757
+                if ($preserveMtime) {
758
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
759
+                }
760
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
761
+            } else {
762
+                // delete partially written target file
763
+                $this->unlink($targetInternalPath);
764
+                // delete cache entry that was created by fopen
765
+                $this->getCache()->remove($targetInternalPath);
766
+            }
767
+        }
768
+        return (bool)$result;
769
+
770
+    }
771
+
772
+    /**
773
+     * get the path to a local version of the file.
774
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
775
+     *
776
+     * @param string $path
777
+     * @return string
778
+     */
779
+    public function getLocalFile($path) {
780
+        if ($this->encryptionManager->isEnabled()) {
781
+            $cachedFile = $this->getCachedFile($path);
782
+            if (is_string($cachedFile)) {
783
+                return $cachedFile;
784
+            }
785
+        }
786
+        return $this->storage->getLocalFile($path);
787
+    }
788
+
789
+    /**
790
+     * Returns the wrapped storage's value for isLocal()
791
+     *
792
+     * @return bool wrapped storage's isLocal() value
793
+     */
794
+    public function isLocal() {
795
+        if ($this->encryptionManager->isEnabled()) {
796
+            return false;
797
+        }
798
+        return $this->storage->isLocal();
799
+    }
800
+
801
+    /**
802
+     * see http://php.net/manual/en/function.stat.php
803
+     * only the following keys are required in the result: size and mtime
804
+     *
805
+     * @param string $path
806
+     * @return array
807
+     */
808
+    public function stat($path) {
809
+        $stat = $this->storage->stat($path);
810
+        $fileSize = $this->filesize($path);
811
+        $stat['size'] = $fileSize;
812
+        $stat[7] = $fileSize;
813
+        return $stat;
814
+    }
815
+
816
+    /**
817
+     * see http://php.net/manual/en/function.hash.php
818
+     *
819
+     * @param string $type
820
+     * @param string $path
821
+     * @param bool $raw
822
+     * @return string
823
+     */
824
+    public function hash($type, $path, $raw = false) {
825
+        $fh = $this->fopen($path, 'rb');
826
+        $ctx = hash_init($type);
827
+        hash_update_stream($ctx, $fh);
828
+        fclose($fh);
829
+        return hash_final($ctx, $raw);
830
+    }
831
+
832
+    /**
833
+     * return full path, including mount point
834
+     *
835
+     * @param string $path relative to mount point
836
+     * @return string full path including mount point
837
+     */
838
+    protected function getFullPath($path) {
839
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
840
+    }
841
+
842
+    /**
843
+     * read first block of encrypted file, typically this will contain the
844
+     * encryption header
845
+     *
846
+     * @param string $path
847
+     * @return string
848
+     */
849
+    protected function readFirstBlock($path) {
850
+        $firstBlock = '';
851
+        if ($this->storage->file_exists($path)) {
852
+            $handle = $this->storage->fopen($path, 'r');
853
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
854
+            fclose($handle);
855
+        }
856
+        return $firstBlock;
857
+    }
858
+
859
+    /**
860
+     * return header size of given file
861
+     *
862
+     * @param string $path
863
+     * @return int
864
+     */
865
+    protected function getHeaderSize($path) {
866
+        $headerSize = 0;
867
+        $realFile = $this->util->stripPartialFileExtension($path);
868
+        if ($this->storage->file_exists($realFile)) {
869
+            $path = $realFile;
870
+        }
871
+        $firstBlock = $this->readFirstBlock($path);
872
+
873
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
874
+            $headerSize = $this->util->getHeaderSize();
875
+        }
876
+
877
+        return $headerSize;
878
+    }
879
+
880
+    /**
881
+     * parse raw header to array
882
+     *
883
+     * @param string $rawHeader
884
+     * @return array
885
+     */
886
+    protected function parseRawHeader($rawHeader) {
887
+        $result = array();
888
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
889
+            $header = $rawHeader;
890
+            $endAt = strpos($header, Util::HEADER_END);
891
+            if ($endAt !== false) {
892
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
893
+
894
+                // +1 to not start with an ':' which would result in empty element at the beginning
895
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
896
+
897
+                $element = array_shift($exploded);
898
+                while ($element !== Util::HEADER_END) {
899
+                    $result[$element] = array_shift($exploded);
900
+                    $element = array_shift($exploded);
901
+                }
902
+            }
903
+        }
904
+
905
+        return $result;
906
+    }
907
+
908
+    /**
909
+     * read header from file
910
+     *
911
+     * @param string $path
912
+     * @return array
913
+     */
914
+    protected function getHeader($path) {
915
+        $realFile = $this->util->stripPartialFileExtension($path);
916
+        $exists = $this->storage->file_exists($realFile);
917
+        if ($exists) {
918
+            $path = $realFile;
919
+        }
920
+
921
+        $firstBlock = $this->readFirstBlock($path);
922
+        $result = $this->parseRawHeader($firstBlock);
923
+
924
+        // if the header doesn't contain a encryption module we check if it is a
925
+        // legacy file. If true, we add the default encryption module
926
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
927
+            if (!empty($result)) {
928
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
929
+            } else if ($exists) {
930
+                // if the header was empty we have to check first if it is a encrypted file at all
931
+                // We would do query to filecache only if we know that entry in filecache exists
932
+                $info = $this->getCache()->get($path);
933
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
934
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
935
+                }
936
+            }
937
+        }
938
+
939
+        return $result;
940
+    }
941
+
942
+    /**
943
+     * read encryption module needed to read/write the file located at $path
944
+     *
945
+     * @param string $path
946
+     * @return null|\OCP\Encryption\IEncryptionModule
947
+     * @throws ModuleDoesNotExistsException
948
+     * @throws \Exception
949
+     */
950
+    protected function getEncryptionModule($path) {
951
+        $encryptionModule = null;
952
+        $header = $this->getHeader($path);
953
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
954
+        if (!empty($encryptionModuleId)) {
955
+            try {
956
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
957
+            } catch (ModuleDoesNotExistsException $e) {
958
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
959
+                throw $e;
960
+            }
961
+        }
962
+
963
+        return $encryptionModule;
964
+    }
965
+
966
+    /**
967
+     * @param string $path
968
+     * @param int $unencryptedSize
969
+     */
970
+    public function updateUnencryptedSize($path, $unencryptedSize) {
971
+        $this->unencryptedSize[$path] = $unencryptedSize;
972
+    }
973
+
974
+    /**
975
+     * copy keys to new location
976
+     *
977
+     * @param string $source path relative to data/
978
+     * @param string $target path relative to data/
979
+     * @return bool
980
+     */
981
+    protected function copyKeys($source, $target) {
982
+        if (!$this->util->isExcluded($source)) {
983
+            return $this->keyStorage->copyKeys($source, $target);
984
+        }
985
+
986
+        return false;
987
+    }
988
+
989
+    /**
990
+     * check if path points to a files version
991
+     *
992
+     * @param $path
993
+     * @return bool
994
+     */
995
+    protected function isVersion($path) {
996
+        $normalized = Filesystem::normalizePath($path);
997
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
998
+    }
999
+
1000
+    /**
1001
+     * check if the given storage should be encrypted or not
1002
+     *
1003
+     * @param $path
1004
+     * @return bool
1005
+     */
1006
+    protected function shouldEncrypt($path) {
1007
+        $fullPath = $this->getFullPath($path);
1008
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1009
+        if ($mountPointConfig === false) {
1010
+            return false;
1011
+        }
1012
+
1013
+        try {
1014
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1015
+        } catch (ModuleDoesNotExistsException $e) {
1016
+            return false;
1017
+        }
1018
+
1019
+        if ($encryptionModule === null) {
1020
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1021
+        }
1022
+
1023
+        return $encryptionModule->shouldEncrypt($fullPath);
1024
+
1025
+    }
1026 1026
 
1027 1027
 }
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/ObjectStoreStorage.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -162,6 +162,9 @@  discard block
 block discarded – undo
162 162
 		return true;
163 163
 	}
164 164
 
165
+	/**
166
+	 * @param string $path
167
+	 */
165 168
 	private function rmObjects($path) {
166 169
 		$children = $this->getCache()->getFolderContents($path);
167 170
 		foreach ($children as $child) {
@@ -364,6 +367,9 @@  discard block
 block discarded – undo
364 367
 		return true;
365 368
 	}
366 369
 
370
+	/**
371
+	 * @param string $path
372
+	 */
367 373
 	public function writeBack($tmpFile, $path) {
368 374
 		$stat = $this->stat($path);
369 375
 		if (empty($stat)) {
Please login to merge, or discard this patch.
Indentation   +392 added lines, -392 removed lines patch added patch discarded remove patch
@@ -31,396 +31,396 @@
 block discarded – undo
31 31
 use OCP\Files\ObjectStore\IObjectStore;
32 32
 
33 33
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
34
-	/**
35
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
-	 */
37
-	protected $objectStore;
38
-	/**
39
-	 * @var string $id
40
-	 */
41
-	protected $id;
42
-	/**
43
-	 * @var \OC\User\User $user
44
-	 */
45
-	protected $user;
46
-
47
-	private $objectPrefix = 'urn:oid:';
48
-
49
-	private $logger;
50
-
51
-	public function __construct($params) {
52
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
-			$this->objectStore = $params['objectstore'];
54
-		} else {
55
-			throw new \Exception('missing IObjectStore instance');
56
-		}
57
-		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
59
-		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
61
-		}
62
-		if (isset($params['objectPrefix'])) {
63
-			$this->objectPrefix = $params['objectPrefix'];
64
-		}
65
-		//initialize cache with root directory in cache
66
-		if (!$this->is_dir('/')) {
67
-			$this->mkdir('/');
68
-		}
69
-
70
-		$this->logger = \OC::$server->getLogger();
71
-	}
72
-
73
-	public function mkdir($path) {
74
-		$path = $this->normalizePath($path);
75
-
76
-		if ($this->file_exists($path)) {
77
-			return false;
78
-		}
79
-
80
-		$mTime = time();
81
-		$data = [
82
-			'mimetype' => 'httpd/unix-directory',
83
-			'size' => 0,
84
-			'mtime' => $mTime,
85
-			'storage_mtime' => $mTime,
86
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
87
-		];
88
-		if ($path === '') {
89
-			//create root on the fly
90
-			$data['etag'] = $this->getETag('');
91
-			$this->getCache()->put('', $data);
92
-			return true;
93
-		} else {
94
-			// if parent does not exist, create it
95
-			$parent = $this->normalizePath(dirname($path));
96
-			$parentType = $this->filetype($parent);
97
-			if ($parentType === false) {
98
-				if (!$this->mkdir($parent)) {
99
-					// something went wrong
100
-					return false;
101
-				}
102
-			} else if ($parentType === 'file') {
103
-				// parent is a file
104
-				return false;
105
-			}
106
-			// finally create the new dir
107
-			$mTime = time(); // update mtime
108
-			$data['mtime'] = $mTime;
109
-			$data['storage_mtime'] = $mTime;
110
-			$data['etag'] = $this->getETag($path);
111
-			$this->getCache()->put($path, $data);
112
-			return true;
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @param string $path
118
-	 * @return string
119
-	 */
120
-	private function normalizePath($path) {
121
-		$path = trim($path, '/');
122
-		//FIXME why do we sometimes get a path like 'files//username'?
123
-		$path = str_replace('//', '/', $path);
124
-
125
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
-		if (!$path || $path === '.') {
127
-			$path = '';
128
-		}
129
-
130
-		return $path;
131
-	}
132
-
133
-	/**
134
-	 * Object Stores use a NoopScanner because metadata is directly stored in
135
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
-	 *
137
-	 * @param string $path
138
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
-	 * @return \OC\Files\ObjectStore\NoopScanner
140
-	 */
141
-	public function getScanner($path = '', $storage = null) {
142
-		if (!$storage) {
143
-			$storage = $this;
144
-		}
145
-		if (!isset($this->scanner)) {
146
-			$this->scanner = new NoopScanner($storage);
147
-		}
148
-		return $this->scanner;
149
-	}
150
-
151
-	public function getId() {
152
-		return $this->id;
153
-	}
154
-
155
-	public function rmdir($path) {
156
-		$path = $this->normalizePath($path);
157
-
158
-		if (!$this->is_dir($path)) {
159
-			return false;
160
-		}
161
-
162
-		$this->rmObjects($path);
163
-
164
-		$this->getCache()->remove($path);
165
-
166
-		return true;
167
-	}
168
-
169
-	private function rmObjects($path) {
170
-		$children = $this->getCache()->getFolderContents($path);
171
-		foreach ($children as $child) {
172
-			if ($child['mimetype'] === 'httpd/unix-directory') {
173
-				$this->rmObjects($child['path']);
174
-			} else {
175
-				$this->unlink($child['path']);
176
-			}
177
-		}
178
-	}
179
-
180
-	public function unlink($path) {
181
-		$path = $this->normalizePath($path);
182
-		$stat = $this->stat($path);
183
-
184
-		if ($stat && isset($stat['fileid'])) {
185
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
186
-				return $this->rmdir($path);
187
-			}
188
-			try {
189
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
-			} catch (\Exception $ex) {
191
-				if ($ex->getCode() !== 404) {
192
-					$this->logger->logException($ex, [
193
-						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
-					]);
196
-					return false;
197
-				}
198
-				//removing from cache is ok as it does not exist in the objectstore anyway
199
-			}
200
-			$this->getCache()->remove($path);
201
-			return true;
202
-		}
203
-		return false;
204
-	}
205
-
206
-	public function stat($path) {
207
-		$path = $this->normalizePath($path);
208
-		$cacheEntry = $this->getCache()->get($path);
209
-		if ($cacheEntry instanceof CacheEntry) {
210
-			return $cacheEntry->getData();
211
-		} else {
212
-			return false;
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
218
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
-	 *
221
-	 * @param int $fileId the fileid
222
-	 * @return null|string the unified resource name used to identify the object
223
-	 */
224
-	protected function getURN($fileId) {
225
-		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
227
-		}
228
-		return null;
229
-	}
230
-
231
-	public function opendir($path) {
232
-		$path = $this->normalizePath($path);
233
-
234
-		try {
235
-			$files = array();
236
-			$folderContents = $this->getCache()->getFolderContents($path);
237
-			foreach ($folderContents as $file) {
238
-				$files[] = $file['name'];
239
-			}
240
-
241
-			return IteratorDirectory::wrap($files);
242
-		} catch (\Exception $e) {
243
-			$this->logger->logException($e);
244
-			return false;
245
-		}
246
-	}
247
-
248
-	public function filetype($path) {
249
-		$path = $this->normalizePath($path);
250
-		$stat = $this->stat($path);
251
-		if ($stat) {
252
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
253
-				return 'dir';
254
-			}
255
-			return 'file';
256
-		} else {
257
-			return false;
258
-		}
259
-	}
260
-
261
-	public function fopen($path, $mode) {
262
-		$path = $this->normalizePath($path);
263
-
264
-		switch ($mode) {
265
-			case 'r':
266
-			case 'rb':
267
-				$stat = $this->stat($path);
268
-				if (is_array($stat)) {
269
-					try {
270
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
271
-					} catch (\Exception $ex) {
272
-						$this->logger->logException($ex, [
273
-							'app' => 'objectstore',
274
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
275
-						]);
276
-						return false;
277
-					}
278
-				} else {
279
-					return false;
280
-				}
281
-			case 'w':
282
-			case 'wb':
283
-			case 'a':
284
-			case 'ab':
285
-			case 'r+':
286
-			case 'w+':
287
-			case 'wb+':
288
-			case 'a+':
289
-			case 'x':
290
-			case 'x+':
291
-			case 'c':
292
-			case 'c+':
293
-				if (strrpos($path, '.') !== false) {
294
-					$ext = substr($path, strrpos($path, '.'));
295
-				} else {
296
-					$ext = '';
297
-				}
298
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
299
-				if ($this->file_exists($path)) {
300
-					$source = $this->fopen($path, 'r');
301
-					file_put_contents($tmpFile, $source);
302
-				}
303
-				$handle = fopen($tmpFile, $mode);
304
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
305
-					$this->writeBack($tmpFile, $path);
306
-				});
307
-		}
308
-		return false;
309
-	}
310
-
311
-	public function file_exists($path) {
312
-		$path = $this->normalizePath($path);
313
-		return (bool)$this->stat($path);
314
-	}
315
-
316
-	public function rename($source, $target) {
317
-		$source = $this->normalizePath($source);
318
-		$target = $this->normalizePath($target);
319
-		$this->remove($target);
320
-		$this->getCache()->move($source, $target);
321
-		$this->touch(dirname($target));
322
-		return true;
323
-	}
324
-
325
-	public function getMimeType($path) {
326
-		$path = $this->normalizePath($path);
327
-		$stat = $this->stat($path);
328
-		if (is_array($stat)) {
329
-			return $stat['mimetype'];
330
-		} else {
331
-			return false;
332
-		}
333
-	}
334
-
335
-	public function touch($path, $mtime = null) {
336
-		if (is_null($mtime)) {
337
-			$mtime = time();
338
-		}
339
-
340
-		$path = $this->normalizePath($path);
341
-		$dirName = dirname($path);
342
-		$parentExists = $this->is_dir($dirName);
343
-		if (!$parentExists) {
344
-			return false;
345
-		}
346
-
347
-		$stat = $this->stat($path);
348
-		if (is_array($stat)) {
349
-			// update existing mtime in db
350
-			$stat['mtime'] = $mtime;
351
-			$this->getCache()->update($stat['fileid'], $stat);
352
-		} else {
353
-			try {
354
-				//create a empty file, need to have at least on char to make it
355
-				// work with all object storage implementations
356
-				$this->file_put_contents($path, ' ');
357
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
358
-				$stat = array(
359
-					'etag' => $this->getETag($path),
360
-					'mimetype' => $mimeType,
361
-					'size' => 0,
362
-					'mtime' => $mtime,
363
-					'storage_mtime' => $mtime,
364
-					'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
365
-				);
366
-				$this->getCache()->put($path, $stat);
367
-			} catch (\Exception $ex) {
368
-				$this->logger->logException($ex, [
369
-					'app' => 'objectstore',
370
-					'message' => 'Could not create object for ' . $path,
371
-				]);
372
-				throw $ex;
373
-			}
374
-		}
375
-		return true;
376
-	}
377
-
378
-	public function writeBack($tmpFile, $path) {
379
-		$stat = $this->stat($path);
380
-		if (empty($stat)) {
381
-			// create new file
382
-			$stat = array(
383
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
384
-			);
385
-		}
386
-		// update stat with new data
387
-		$mTime = time();
388
-		$stat['size'] = filesize($tmpFile);
389
-		$stat['mtime'] = $mTime;
390
-		$stat['storage_mtime'] = $mTime;
391
-
392
-		// run path based detection first, to use file extension because $tmpFile is only a random string
393
-		$mimetypeDetector = \OC::$server->getMimeTypeDetector();
394
-		$mimetype = $mimetypeDetector->detectPath($path);
395
-		if ($mimetype === 'application/octet-stream') {
396
-			$mimetype = $mimetypeDetector->detect($tmpFile);
397
-		}
398
-
399
-		$stat['mimetype'] = $mimetype;
400
-		$stat['etag'] = $this->getETag($path);
401
-
402
-		$fileId = $this->getCache()->put($path, $stat);
403
-		try {
404
-			//upload to object storage
405
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
406
-		} catch (\Exception $ex) {
407
-			$this->getCache()->remove($path);
408
-			$this->logger->logException($ex, [
409
-				'app' => 'objectstore',
410
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
411
-			]);
412
-			throw $ex; // make this bubble up
413
-		}
414
-	}
415
-
416
-	/**
417
-	 * external changes are not supported, exclusive access to the object storage is assumed
418
-	 *
419
-	 * @param string $path
420
-	 * @param int $time
421
-	 * @return false
422
-	 */
423
-	public function hasUpdated($path, $time) {
424
-		return false;
425
-	}
34
+    /**
35
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
+     */
37
+    protected $objectStore;
38
+    /**
39
+     * @var string $id
40
+     */
41
+    protected $id;
42
+    /**
43
+     * @var \OC\User\User $user
44
+     */
45
+    protected $user;
46
+
47
+    private $objectPrefix = 'urn:oid:';
48
+
49
+    private $logger;
50
+
51
+    public function __construct($params) {
52
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
53
+            $this->objectStore = $params['objectstore'];
54
+        } else {
55
+            throw new \Exception('missing IObjectStore instance');
56
+        }
57
+        if (isset($params['storageid'])) {
58
+            $this->id = 'object::store:' . $params['storageid'];
59
+        } else {
60
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
61
+        }
62
+        if (isset($params['objectPrefix'])) {
63
+            $this->objectPrefix = $params['objectPrefix'];
64
+        }
65
+        //initialize cache with root directory in cache
66
+        if (!$this->is_dir('/')) {
67
+            $this->mkdir('/');
68
+        }
69
+
70
+        $this->logger = \OC::$server->getLogger();
71
+    }
72
+
73
+    public function mkdir($path) {
74
+        $path = $this->normalizePath($path);
75
+
76
+        if ($this->file_exists($path)) {
77
+            return false;
78
+        }
79
+
80
+        $mTime = time();
81
+        $data = [
82
+            'mimetype' => 'httpd/unix-directory',
83
+            'size' => 0,
84
+            'mtime' => $mTime,
85
+            'storage_mtime' => $mTime,
86
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
87
+        ];
88
+        if ($path === '') {
89
+            //create root on the fly
90
+            $data['etag'] = $this->getETag('');
91
+            $this->getCache()->put('', $data);
92
+            return true;
93
+        } else {
94
+            // if parent does not exist, create it
95
+            $parent = $this->normalizePath(dirname($path));
96
+            $parentType = $this->filetype($parent);
97
+            if ($parentType === false) {
98
+                if (!$this->mkdir($parent)) {
99
+                    // something went wrong
100
+                    return false;
101
+                }
102
+            } else if ($parentType === 'file') {
103
+                // parent is a file
104
+                return false;
105
+            }
106
+            // finally create the new dir
107
+            $mTime = time(); // update mtime
108
+            $data['mtime'] = $mTime;
109
+            $data['storage_mtime'] = $mTime;
110
+            $data['etag'] = $this->getETag($path);
111
+            $this->getCache()->put($path, $data);
112
+            return true;
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @param string $path
118
+     * @return string
119
+     */
120
+    private function normalizePath($path) {
121
+        $path = trim($path, '/');
122
+        //FIXME why do we sometimes get a path like 'files//username'?
123
+        $path = str_replace('//', '/', $path);
124
+
125
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
126
+        if (!$path || $path === '.') {
127
+            $path = '';
128
+        }
129
+
130
+        return $path;
131
+    }
132
+
133
+    /**
134
+     * Object Stores use a NoopScanner because metadata is directly stored in
135
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
136
+     *
137
+     * @param string $path
138
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
139
+     * @return \OC\Files\ObjectStore\NoopScanner
140
+     */
141
+    public function getScanner($path = '', $storage = null) {
142
+        if (!$storage) {
143
+            $storage = $this;
144
+        }
145
+        if (!isset($this->scanner)) {
146
+            $this->scanner = new NoopScanner($storage);
147
+        }
148
+        return $this->scanner;
149
+    }
150
+
151
+    public function getId() {
152
+        return $this->id;
153
+    }
154
+
155
+    public function rmdir($path) {
156
+        $path = $this->normalizePath($path);
157
+
158
+        if (!$this->is_dir($path)) {
159
+            return false;
160
+        }
161
+
162
+        $this->rmObjects($path);
163
+
164
+        $this->getCache()->remove($path);
165
+
166
+        return true;
167
+    }
168
+
169
+    private function rmObjects($path) {
170
+        $children = $this->getCache()->getFolderContents($path);
171
+        foreach ($children as $child) {
172
+            if ($child['mimetype'] === 'httpd/unix-directory') {
173
+                $this->rmObjects($child['path']);
174
+            } else {
175
+                $this->unlink($child['path']);
176
+            }
177
+        }
178
+    }
179
+
180
+    public function unlink($path) {
181
+        $path = $this->normalizePath($path);
182
+        $stat = $this->stat($path);
183
+
184
+        if ($stat && isset($stat['fileid'])) {
185
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
186
+                return $this->rmdir($path);
187
+            }
188
+            try {
189
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
190
+            } catch (\Exception $ex) {
191
+                if ($ex->getCode() !== 404) {
192
+                    $this->logger->logException($ex, [
193
+                        'app' => 'objectstore',
194
+                        'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
195
+                    ]);
196
+                    return false;
197
+                }
198
+                //removing from cache is ok as it does not exist in the objectstore anyway
199
+            }
200
+            $this->getCache()->remove($path);
201
+            return true;
202
+        }
203
+        return false;
204
+    }
205
+
206
+    public function stat($path) {
207
+        $path = $this->normalizePath($path);
208
+        $cacheEntry = $this->getCache()->get($path);
209
+        if ($cacheEntry instanceof CacheEntry) {
210
+            return $cacheEntry->getData();
211
+        } else {
212
+            return false;
213
+        }
214
+    }
215
+
216
+    /**
217
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
218
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
219
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
220
+     *
221
+     * @param int $fileId the fileid
222
+     * @return null|string the unified resource name used to identify the object
223
+     */
224
+    protected function getURN($fileId) {
225
+        if (is_numeric($fileId)) {
226
+            return $this->objectPrefix . $fileId;
227
+        }
228
+        return null;
229
+    }
230
+
231
+    public function opendir($path) {
232
+        $path = $this->normalizePath($path);
233
+
234
+        try {
235
+            $files = array();
236
+            $folderContents = $this->getCache()->getFolderContents($path);
237
+            foreach ($folderContents as $file) {
238
+                $files[] = $file['name'];
239
+            }
240
+
241
+            return IteratorDirectory::wrap($files);
242
+        } catch (\Exception $e) {
243
+            $this->logger->logException($e);
244
+            return false;
245
+        }
246
+    }
247
+
248
+    public function filetype($path) {
249
+        $path = $this->normalizePath($path);
250
+        $stat = $this->stat($path);
251
+        if ($stat) {
252
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
253
+                return 'dir';
254
+            }
255
+            return 'file';
256
+        } else {
257
+            return false;
258
+        }
259
+    }
260
+
261
+    public function fopen($path, $mode) {
262
+        $path = $this->normalizePath($path);
263
+
264
+        switch ($mode) {
265
+            case 'r':
266
+            case 'rb':
267
+                $stat = $this->stat($path);
268
+                if (is_array($stat)) {
269
+                    try {
270
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
271
+                    } catch (\Exception $ex) {
272
+                        $this->logger->logException($ex, [
273
+                            'app' => 'objectstore',
274
+                            'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
275
+                        ]);
276
+                        return false;
277
+                    }
278
+                } else {
279
+                    return false;
280
+                }
281
+            case 'w':
282
+            case 'wb':
283
+            case 'a':
284
+            case 'ab':
285
+            case 'r+':
286
+            case 'w+':
287
+            case 'wb+':
288
+            case 'a+':
289
+            case 'x':
290
+            case 'x+':
291
+            case 'c':
292
+            case 'c+':
293
+                if (strrpos($path, '.') !== false) {
294
+                    $ext = substr($path, strrpos($path, '.'));
295
+                } else {
296
+                    $ext = '';
297
+                }
298
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
299
+                if ($this->file_exists($path)) {
300
+                    $source = $this->fopen($path, 'r');
301
+                    file_put_contents($tmpFile, $source);
302
+                }
303
+                $handle = fopen($tmpFile, $mode);
304
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
305
+                    $this->writeBack($tmpFile, $path);
306
+                });
307
+        }
308
+        return false;
309
+    }
310
+
311
+    public function file_exists($path) {
312
+        $path = $this->normalizePath($path);
313
+        return (bool)$this->stat($path);
314
+    }
315
+
316
+    public function rename($source, $target) {
317
+        $source = $this->normalizePath($source);
318
+        $target = $this->normalizePath($target);
319
+        $this->remove($target);
320
+        $this->getCache()->move($source, $target);
321
+        $this->touch(dirname($target));
322
+        return true;
323
+    }
324
+
325
+    public function getMimeType($path) {
326
+        $path = $this->normalizePath($path);
327
+        $stat = $this->stat($path);
328
+        if (is_array($stat)) {
329
+            return $stat['mimetype'];
330
+        } else {
331
+            return false;
332
+        }
333
+    }
334
+
335
+    public function touch($path, $mtime = null) {
336
+        if (is_null($mtime)) {
337
+            $mtime = time();
338
+        }
339
+
340
+        $path = $this->normalizePath($path);
341
+        $dirName = dirname($path);
342
+        $parentExists = $this->is_dir($dirName);
343
+        if (!$parentExists) {
344
+            return false;
345
+        }
346
+
347
+        $stat = $this->stat($path);
348
+        if (is_array($stat)) {
349
+            // update existing mtime in db
350
+            $stat['mtime'] = $mtime;
351
+            $this->getCache()->update($stat['fileid'], $stat);
352
+        } else {
353
+            try {
354
+                //create a empty file, need to have at least on char to make it
355
+                // work with all object storage implementations
356
+                $this->file_put_contents($path, ' ');
357
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
358
+                $stat = array(
359
+                    'etag' => $this->getETag($path),
360
+                    'mimetype' => $mimeType,
361
+                    'size' => 0,
362
+                    'mtime' => $mtime,
363
+                    'storage_mtime' => $mtime,
364
+                    'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
365
+                );
366
+                $this->getCache()->put($path, $stat);
367
+            } catch (\Exception $ex) {
368
+                $this->logger->logException($ex, [
369
+                    'app' => 'objectstore',
370
+                    'message' => 'Could not create object for ' . $path,
371
+                ]);
372
+                throw $ex;
373
+            }
374
+        }
375
+        return true;
376
+    }
377
+
378
+    public function writeBack($tmpFile, $path) {
379
+        $stat = $this->stat($path);
380
+        if (empty($stat)) {
381
+            // create new file
382
+            $stat = array(
383
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
384
+            );
385
+        }
386
+        // update stat with new data
387
+        $mTime = time();
388
+        $stat['size'] = filesize($tmpFile);
389
+        $stat['mtime'] = $mTime;
390
+        $stat['storage_mtime'] = $mTime;
391
+
392
+        // run path based detection first, to use file extension because $tmpFile is only a random string
393
+        $mimetypeDetector = \OC::$server->getMimeTypeDetector();
394
+        $mimetype = $mimetypeDetector->detectPath($path);
395
+        if ($mimetype === 'application/octet-stream') {
396
+            $mimetype = $mimetypeDetector->detect($tmpFile);
397
+        }
398
+
399
+        $stat['mimetype'] = $mimetype;
400
+        $stat['etag'] = $this->getETag($path);
401
+
402
+        $fileId = $this->getCache()->put($path, $stat);
403
+        try {
404
+            //upload to object storage
405
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
406
+        } catch (\Exception $ex) {
407
+            $this->getCache()->remove($path);
408
+            $this->logger->logException($ex, [
409
+                'app' => 'objectstore',
410
+                'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
411
+            ]);
412
+            throw $ex; // make this bubble up
413
+        }
414
+    }
415
+
416
+    /**
417
+     * external changes are not supported, exclusive access to the object storage is assumed
418
+     *
419
+     * @param string $path
420
+     * @param int $time
421
+     * @return false
422
+     */
423
+    public function hasUpdated($path, $time) {
424
+        return false;
425
+    }
426 426
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
 			throw new \Exception('missing IObjectStore instance');
56 56
 		}
57 57
 		if (isset($params['storageid'])) {
58
-			$this->id = 'object::store:' . $params['storageid'];
58
+			$this->id = 'object::store:'.$params['storageid'];
59 59
 		} else {
60
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
60
+			$this->id = 'object::store:'.$this->objectStore->getStorageId();
61 61
 		}
62 62
 		if (isset($params['objectPrefix'])) {
63 63
 			$this->objectPrefix = $params['objectPrefix'];
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 				if ($ex->getCode() !== 404) {
192 192
 					$this->logger->logException($ex, [
193 193
 						'app' => 'objectstore',
194
-						'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
194
+						'message' => 'Could not delete object '.$this->getURN($stat['fileid']).' for '.$path,
195 195
 					]);
196 196
 					return false;
197 197
 				}
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 */
224 224
 	protected function getURN($fileId) {
225 225
 		if (is_numeric($fileId)) {
226
-			return $this->objectPrefix . $fileId;
226
+			return $this->objectPrefix.$fileId;
227 227
 		}
228 228
 		return null;
229 229
 	}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 					} catch (\Exception $ex) {
272 272
 						$this->logger->logException($ex, [
273 273
 							'app' => 'objectstore',
274
-							'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
274
+							'message' => 'Count not get object '.$this->getURN($stat['fileid']).' for file '.$path,
275 275
 						]);
276 276
 						return false;
277 277
 					}
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 					file_put_contents($tmpFile, $source);
302 302
 				}
303 303
 				$handle = fopen($tmpFile, $mode);
304
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
304
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
305 305
 					$this->writeBack($tmpFile, $path);
306 306
 				});
307 307
 		}
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 
311 311
 	public function file_exists($path) {
312 312
 		$path = $this->normalizePath($path);
313
-		return (bool)$this->stat($path);
313
+		return (bool) $this->stat($path);
314 314
 	}
315 315
 
316 316
 	public function rename($source, $target) {
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 			} catch (\Exception $ex) {
368 368
 				$this->logger->logException($ex, [
369 369
 					'app' => 'objectstore',
370
-					'message' => 'Could not create object for ' . $path,
370
+					'message' => 'Could not create object for '.$path,
371 371
 				]);
372 372
 				throw $ex;
373 373
 			}
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 			$this->getCache()->remove($path);
408 408
 			$this->logger->logException($ex, [
409 409
 				'app' => 'objectstore',
410
-				'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
410
+				'message' => 'Could not create object '.$this->getURN($fileId).' for '.$path,
411 411
 			]);
412 412
 			throw $ex; // make this bubble up
413 413
 		}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@
 block discarded – undo
102 102
 
103 103
 	/**
104 104
 	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
105
+	 * @return null|Change
106 106
 	 */
107 107
 	private function mapChange(\Icewind\SMB\Change $change) {
108 108
 		$path = $this->relativePath($change->getPath());
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -29,122 +29,122 @@
 block discarded – undo
29 29
 use OCP\Files\Notify\INotifyHandler;
30 30
 
31 31
 class SMBNotifyHandler implements INotifyHandler {
32
-	/**
33
-	 * @var \Icewind\SMB\INotifyHandler
34
-	 */
35
-	private $shareNotifyHandler;
32
+    /**
33
+     * @var \Icewind\SMB\INotifyHandler
34
+     */
35
+    private $shareNotifyHandler;
36 36
 
37
-	/**
38
-	 * @var string
39
-	 */
40
-	private $root;
37
+    /**
38
+     * @var string
39
+     */
40
+    private $root;
41 41
 
42
-	private $oldRenamePath = null;
42
+    private $oldRenamePath = null;
43 43
 
44
-	/**
45
-	 * SMBNotifyHandler constructor.
46
-	 *
47
-	 * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
-	 * @param string $root
49
-	 */
50
-	public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
-		$this->shareNotifyHandler = $shareNotifyHandler;
52
-		$this->root = $root;
53
-	}
44
+    /**
45
+     * SMBNotifyHandler constructor.
46
+     *
47
+     * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
+     * @param string $root
49
+     */
50
+    public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
+        $this->shareNotifyHandler = $shareNotifyHandler;
52
+        $this->root = $root;
53
+    }
54 54
 
55
-	private function relativePath($fullPath) {
56
-		if ($fullPath === $this->root) {
57
-			return '';
58
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
-			return substr($fullPath, strlen($this->root));
60
-		} else {
61
-			return null;
62
-		}
63
-	}
55
+    private function relativePath($fullPath) {
56
+        if ($fullPath === $this->root) {
57
+            return '';
58
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
+            return substr($fullPath, strlen($this->root));
60
+        } else {
61
+            return null;
62
+        }
63
+    }
64 64
 
65
-	public function listen(callable $callback) {
66
-		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
-			$change = $this->mapChange($shareChange);
69
-			if (!is_null($change)) {
70
-				return $callback($change);
71
-			} else {
72
-				return true;
73
-			}
74
-		});
75
-	}
65
+    public function listen(callable $callback) {
66
+        $oldRenamePath = null;
67
+        $this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
+            $change = $this->mapChange($shareChange);
69
+            if (!is_null($change)) {
70
+                return $callback($change);
71
+            } else {
72
+                return true;
73
+            }
74
+        });
75
+    }
76 76
 
77
-	/**
78
-	 * Get all changes detected since the start of the notify process or the last call to getChanges
79
-	 *
80
-	 * @return IChange[]
81
-	 */
82
-	public function getChanges() {
83
-		$shareChanges = $this->shareNotifyHandler->getChanges();
84
-		$changes = [];
85
-		foreach ($shareChanges as $shareChange) {
86
-			$change = $this->mapChange($shareChange);
87
-			if ($change) {
88
-				$changes[] = $change;
89
-			}
90
-		}
91
-		return $changes;
92
-	}
77
+    /**
78
+     * Get all changes detected since the start of the notify process or the last call to getChanges
79
+     *
80
+     * @return IChange[]
81
+     */
82
+    public function getChanges() {
83
+        $shareChanges = $this->shareNotifyHandler->getChanges();
84
+        $changes = [];
85
+        foreach ($shareChanges as $shareChange) {
86
+            $change = $this->mapChange($shareChange);
87
+            if ($change) {
88
+                $changes[] = $change;
89
+            }
90
+        }
91
+        return $changes;
92
+    }
93 93
 
94
-	/**
95
-	 * Stop listening for changes
96
-	 *
97
-	 * Note that any pending changes will be discarded
98
-	 */
99
-	public function stop() {
100
-		$this->shareNotifyHandler->stop();
101
-	}
94
+    /**
95
+     * Stop listening for changes
96
+     *
97
+     * Note that any pending changes will be discarded
98
+     */
99
+    public function stop() {
100
+        $this->shareNotifyHandler->stop();
101
+    }
102 102
 
103
-	/**
104
-	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
106
-	 */
107
-	private function mapChange(\Icewind\SMB\Change $change) {
108
-		$path = $this->relativePath($change->getPath());
109
-		if (is_null($path)) {
110
-			return null;
111
-		}
112
-		if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
-			$this->oldRenamePath = $path;
114
-			return null;
115
-		}
116
-		$type = $this->mapNotifyType($change->getCode());
117
-		if (is_null($type)) {
118
-			return null;
119
-		}
120
-		if ($type === IChange::RENAMED) {
121
-			if (!is_null($this->oldRenamePath)) {
122
-				$result = new RenameChange($type, $this->oldRenamePath, $path);
123
-				$this->oldRenamePath = null;
124
-			} else {
125
-				$result = null;
126
-			}
127
-		} else {
128
-			$result = new Change($type, $path);
129
-		}
130
-		return $result;
131
-	}
103
+    /**
104
+     * @param \Icewind\SMB\Change $change
105
+     * @return IChange|null
106
+     */
107
+    private function mapChange(\Icewind\SMB\Change $change) {
108
+        $path = $this->relativePath($change->getPath());
109
+        if (is_null($path)) {
110
+            return null;
111
+        }
112
+        if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
+            $this->oldRenamePath = $path;
114
+            return null;
115
+        }
116
+        $type = $this->mapNotifyType($change->getCode());
117
+        if (is_null($type)) {
118
+            return null;
119
+        }
120
+        if ($type === IChange::RENAMED) {
121
+            if (!is_null($this->oldRenamePath)) {
122
+                $result = new RenameChange($type, $this->oldRenamePath, $path);
123
+                $this->oldRenamePath = null;
124
+            } else {
125
+                $result = null;
126
+            }
127
+        } else {
128
+            $result = new Change($type, $path);
129
+        }
130
+        return $result;
131
+    }
132 132
 
133
-	private function mapNotifyType($smbType) {
134
-		switch ($smbType) {
135
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
-				return IChange::ADDED;
137
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
-				return IChange::REMOVED;
139
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
-				return IChange::MODIFIED;
144
-			case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
-				return IChange::RENAMED;
146
-			default:
147
-				return null;
148
-		}
149
-	}
133
+    private function mapNotifyType($smbType) {
134
+        switch ($smbType) {
135
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
+                return IChange::ADDED;
137
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
+                return IChange::REMOVED;
139
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
+                return IChange::MODIFIED;
144
+            case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
+                return IChange::RENAMED;
146
+            default:
147
+                return null;
148
+        }
149
+    }
150 150
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@
 block discarded – undo
64 64
 
65 65
 	public function listen(callable $callback) {
66 66
 		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
67
+		$this->shareNotifyHandler->listen(function(\Icewind\SMB\Change $shareChange) use ($callback) {
68 68
 			$change = $this->mapChange($shareChange);
69 69
 			if (!is_null($change)) {
70 70
 				return $callback($change);
Please login to merge, or discard this patch.
lib/private/Files/Node/File.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
 	 * Creates a Folder that represents a non-existing path
32 32
 	 *
33 33
 	 * @param string $path path
34
-	 * @return string non-existing node class
34
+	 * @return NonExistingFile non-existing node class
35 35
 	 */
36 36
 	protected function createNonExistingNode($path) {
37 37
 		return new NonExistingFile($this->root, $this->view, $path);
Please login to merge, or discard this patch.
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -29,113 +29,113 @@
 block discarded – undo
29 29
 use OCP\Files\NotPermittedException;
30 30
 
31 31
 class File extends Node implements \OCP\Files\File {
32
-	/**
33
-	 * Creates a Folder that represents a non-existing path
34
-	 *
35
-	 * @param string $path path
36
-	 * @return string non-existing node class
37
-	 */
38
-	protected function createNonExistingNode($path) {
39
-		return new NonExistingFile($this->root, $this->view, $path);
40
-	}
32
+    /**
33
+     * Creates a Folder that represents a non-existing path
34
+     *
35
+     * @param string $path path
36
+     * @return string non-existing node class
37
+     */
38
+    protected function createNonExistingNode($path) {
39
+        return new NonExistingFile($this->root, $this->view, $path);
40
+    }
41 41
 
42
-	/**
43
-	 * @return string
44
-	 * @throws \OCP\Files\NotPermittedException
45
-	 */
46
-	public function getContent() {
47
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
48
-			/**
49
-			 * @var \OC\Files\Storage\Storage $storage;
50
-			 */
51
-			return $this->view->file_get_contents($this->path);
52
-		} else {
53
-			throw new NotPermittedException();
54
-		}
55
-	}
42
+    /**
43
+     * @return string
44
+     * @throws \OCP\Files\NotPermittedException
45
+     */
46
+    public function getContent() {
47
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
48
+            /**
49
+             * @var \OC\Files\Storage\Storage $storage;
50
+             */
51
+            return $this->view->file_get_contents($this->path);
52
+        } else {
53
+            throw new NotPermittedException();
54
+        }
55
+    }
56 56
 
57
-	/**
58
-	 * @param string $data
59
-	 * @throws \OCP\Files\NotPermittedException
60
-	 */
61
-	public function putContent($data) {
62
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
63
-			$this->sendHooks(array('preWrite'));
64
-			$this->view->file_put_contents($this->path, $data);
65
-			$this->fileInfo = null;
66
-			$this->sendHooks(array('postWrite'));
67
-		} else {
68
-			throw new NotPermittedException();
69
-		}
70
-	}
57
+    /**
58
+     * @param string $data
59
+     * @throws \OCP\Files\NotPermittedException
60
+     */
61
+    public function putContent($data) {
62
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
63
+            $this->sendHooks(array('preWrite'));
64
+            $this->view->file_put_contents($this->path, $data);
65
+            $this->fileInfo = null;
66
+            $this->sendHooks(array('postWrite'));
67
+        } else {
68
+            throw new NotPermittedException();
69
+        }
70
+    }
71 71
 
72
-	/**
73
-	 * @param string $mode
74
-	 * @return resource
75
-	 * @throws \OCP\Files\NotPermittedException
76
-	 */
77
-	public function fopen($mode) {
78
-		$preHooks = array();
79
-		$postHooks = array();
80
-		$requiredPermissions = \OCP\Constants::PERMISSION_READ;
81
-		switch ($mode) {
82
-			case 'r+':
83
-			case 'rb+':
84
-			case 'w+':
85
-			case 'wb+':
86
-			case 'x+':
87
-			case 'xb+':
88
-			case 'a+':
89
-			case 'ab+':
90
-			case 'w':
91
-			case 'wb':
92
-			case 'x':
93
-			case 'xb':
94
-			case 'a':
95
-			case 'ab':
96
-				$preHooks[] = 'preWrite';
97
-				$postHooks[] = 'postWrite';
98
-				$requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
99
-				break;
100
-		}
72
+    /**
73
+     * @param string $mode
74
+     * @return resource
75
+     * @throws \OCP\Files\NotPermittedException
76
+     */
77
+    public function fopen($mode) {
78
+        $preHooks = array();
79
+        $postHooks = array();
80
+        $requiredPermissions = \OCP\Constants::PERMISSION_READ;
81
+        switch ($mode) {
82
+            case 'r+':
83
+            case 'rb+':
84
+            case 'w+':
85
+            case 'wb+':
86
+            case 'x+':
87
+            case 'xb+':
88
+            case 'a+':
89
+            case 'ab+':
90
+            case 'w':
91
+            case 'wb':
92
+            case 'x':
93
+            case 'xb':
94
+            case 'a':
95
+            case 'ab':
96
+                $preHooks[] = 'preWrite';
97
+                $postHooks[] = 'postWrite';
98
+                $requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
99
+                break;
100
+        }
101 101
 
102
-		if ($this->checkPermissions($requiredPermissions)) {
103
-			$this->sendHooks($preHooks);
104
-			$result = $this->view->fopen($this->path, $mode);
105
-			$this->sendHooks($postHooks);
106
-			return $result;
107
-		} else {
108
-			throw new NotPermittedException();
109
-		}
110
-	}
102
+        if ($this->checkPermissions($requiredPermissions)) {
103
+            $this->sendHooks($preHooks);
104
+            $result = $this->view->fopen($this->path, $mode);
105
+            $this->sendHooks($postHooks);
106
+            return $result;
107
+        } else {
108
+            throw new NotPermittedException();
109
+        }
110
+    }
111 111
 
112
-	public function delete() {
113
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
114
-			$this->sendHooks(array('preDelete'));
115
-			$fileInfo = $this->getFileInfo();
116
-			$this->view->unlink($this->path);
117
-			$nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
118
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
119
-			$this->exists = false;
120
-			$this->fileInfo = null;
121
-		} else {
122
-			throw new NotPermittedException();
123
-		}
124
-	}
112
+    public function delete() {
113
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
114
+            $this->sendHooks(array('preDelete'));
115
+            $fileInfo = $this->getFileInfo();
116
+            $this->view->unlink($this->path);
117
+            $nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
118
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
119
+            $this->exists = false;
120
+            $this->fileInfo = null;
121
+        } else {
122
+            throw new NotPermittedException();
123
+        }
124
+    }
125 125
 
126
-	/**
127
-	 * @param string $type
128
-	 * @param bool $raw
129
-	 * @return string
130
-	 */
131
-	public function hash($type, $raw = false) {
132
-		return $this->view->hash($type, $this->path, $raw);
133
-	}
126
+    /**
127
+     * @param string $type
128
+     * @param bool $raw
129
+     * @return string
130
+     */
131
+    public function hash($type, $raw = false) {
132
+        return $this->view->hash($type, $this->path, $raw);
133
+    }
134 134
 
135
-	/**
136
-	 * @inheritdoc
137
-	 */
138
-	public function getChecksum() {
139
-		return $this->getFileInfo()->getChecksum();
140
-	}
135
+    /**
136
+     * @inheritdoc
137
+     */
138
+    public function getChecksum() {
139
+        return $this->getFileInfo()->getChecksum();
140
+    }
141 141
 }
Please login to merge, or discard this patch.
lib/private/Files/Node/Folder.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
 	 * Creates a Folder that represents a non-existing path
38 38
 	 *
39 39
 	 * @param string $path path
40
-	 * @return string non-existing node class
40
+	 * @return NonExistingFolder non-existing node class
41 41
 	 */
42 42
 	protected function createNonExistingNode($path) {
43 43
 		return new NonExistingFolder($this->root, $this->view, $path);
Please login to merge, or discard this patch.
Indentation   +395 added lines, -395 removed lines patch added patch discarded remove patch
@@ -36,399 +36,399 @@
 block discarded – undo
36 36
 use OCP\Files\Search\ISearchOperator;
37 37
 
38 38
 class Folder extends Node implements \OCP\Files\Folder {
39
-	/**
40
-	 * Creates a Folder that represents a non-existing path
41
-	 *
42
-	 * @param string $path path
43
-	 * @return string non-existing node class
44
-	 */
45
-	protected function createNonExistingNode($path) {
46
-		return new NonExistingFolder($this->root, $this->view, $path);
47
-	}
48
-
49
-	/**
50
-	 * @param string $path path relative to the folder
51
-	 * @return string
52
-	 * @throws \OCP\Files\NotPermittedException
53
-	 */
54
-	public function getFullPath($path) {
55
-		if (!$this->isValidPath($path)) {
56
-			throw new NotPermittedException('Invalid path');
57
-		}
58
-		return $this->path . $this->normalizePath($path);
59
-	}
60
-
61
-	/**
62
-	 * @param string $path
63
-	 * @return string
64
-	 */
65
-	public function getRelativePath($path) {
66
-		if ($this->path === '' or $this->path === '/') {
67
-			return $this->normalizePath($path);
68
-		}
69
-		if ($path === $this->path) {
70
-			return '/';
71
-		} else if (strpos($path, $this->path . '/') !== 0) {
72
-			return null;
73
-		} else {
74
-			$path = substr($path, strlen($this->path));
75
-			return $this->normalizePath($path);
76
-		}
77
-	}
78
-
79
-	/**
80
-	 * check if a node is a (grand-)child of the folder
81
-	 *
82
-	 * @param \OC\Files\Node\Node $node
83
-	 * @return bool
84
-	 */
85
-	public function isSubNode($node) {
86
-		return strpos($node->getPath(), $this->path . '/') === 0;
87
-	}
88
-
89
-	/**
90
-	 * get the content of this directory
91
-	 *
92
-	 * @throws \OCP\Files\NotFoundException
93
-	 * @return Node[]
94
-	 */
95
-	public function getDirectoryListing() {
96
-		$folderContent = $this->view->getDirectoryContent($this->path);
97
-
98
-		return array_map(function (FileInfo $info) {
99
-			if ($info->getMimetype() === 'httpd/unix-directory') {
100
-				return new Folder($this->root, $this->view, $info->getPath(), $info);
101
-			} else {
102
-				return new File($this->root, $this->view, $info->getPath(), $info);
103
-			}
104
-		}, $folderContent);
105
-	}
106
-
107
-	/**
108
-	 * @param string $path
109
-	 * @param FileInfo $info
110
-	 * @return File|Folder
111
-	 */
112
-	protected function createNode($path, FileInfo $info = null) {
113
-		if (is_null($info)) {
114
-			$isDir = $this->view->is_dir($path);
115
-		} else {
116
-			$isDir = $info->getType() === FileInfo::TYPE_FOLDER;
117
-		}
118
-		if ($isDir) {
119
-			return new Folder($this->root, $this->view, $path, $info);
120
-		} else {
121
-			return new File($this->root, $this->view, $path, $info);
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * Get the node at $path
127
-	 *
128
-	 * @param string $path
129
-	 * @return \OC\Files\Node\Node
130
-	 * @throws \OCP\Files\NotFoundException
131
-	 */
132
-	public function get($path) {
133
-		return $this->root->get($this->getFullPath($path));
134
-	}
135
-
136
-	/**
137
-	 * @param string $path
138
-	 * @return bool
139
-	 */
140
-	public function nodeExists($path) {
141
-		try {
142
-			$this->get($path);
143
-			return true;
144
-		} catch (NotFoundException $e) {
145
-			return false;
146
-		}
147
-	}
148
-
149
-	/**
150
-	 * @param string $path
151
-	 * @return \OC\Files\Node\Folder
152
-	 * @throws \OCP\Files\NotPermittedException
153
-	 */
154
-	public function newFolder($path) {
155
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
156
-			$fullPath = $this->getFullPath($path);
157
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
158
-			$this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
159
-			$this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
160
-			$this->view->mkdir($fullPath);
161
-			$node = new Folder($this->root, $this->view, $fullPath);
162
-			$this->root->emit('\OC\Files', 'postWrite', array($node));
163
-			$this->root->emit('\OC\Files', 'postCreate', array($node));
164
-			return $node;
165
-		} else {
166
-			throw new NotPermittedException('No create permission for folder');
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @return \OC\Files\Node\File
173
-	 * @throws \OCP\Files\NotPermittedException
174
-	 */
175
-	public function newFile($path) {
176
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
177
-			$fullPath = $this->getFullPath($path);
178
-			$nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
179
-			$this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
180
-			$this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
181
-			$this->view->touch($fullPath);
182
-			$node = new File($this->root, $this->view, $fullPath);
183
-			$this->root->emit('\OC\Files', 'postWrite', array($node));
184
-			$this->root->emit('\OC\Files', 'postCreate', array($node));
185
-			return $node;
186
-		} else {
187
-			throw new NotPermittedException('No create permission for path');
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * search for files with the name matching $query
193
-	 *
194
-	 * @param string|ISearchOperator $query
195
-	 * @return \OC\Files\Node\Node[]
196
-	 */
197
-	public function search($query) {
198
-		if (is_string($query)) {
199
-			return $this->searchCommon('search', array('%' . $query . '%'));
200
-		} else {
201
-			return $this->searchCommon('searchQuery', array($query));
202
-		}
203
-	}
204
-
205
-	/**
206
-	 * search for files by mimetype
207
-	 *
208
-	 * @param string $mimetype
209
-	 * @return Node[]
210
-	 */
211
-	public function searchByMime($mimetype) {
212
-		return $this->searchCommon('searchByMime', array($mimetype));
213
-	}
214
-
215
-	/**
216
-	 * search for files by tag
217
-	 *
218
-	 * @param string|int $tag name or tag id
219
-	 * @param string $userId owner of the tags
220
-	 * @return Node[]
221
-	 */
222
-	public function searchByTag($tag, $userId) {
223
-		return $this->searchCommon('searchByTag', array($tag, $userId));
224
-	}
225
-
226
-	/**
227
-	 * @param string $method cache method
228
-	 * @param array $args call args
229
-	 * @return \OC\Files\Node\Node[]
230
-	 */
231
-	private function searchCommon($method, $args) {
232
-		$files = array();
233
-		$rootLength = strlen($this->path);
234
-		$mount = $this->root->getMount($this->path);
235
-		$storage = $mount->getStorage();
236
-		$internalPath = $mount->getInternalPath($this->path);
237
-		$internalPath = rtrim($internalPath, '/');
238
-		if ($internalPath !== '') {
239
-			$internalPath = $internalPath . '/';
240
-		}
241
-		$internalRootLength = strlen($internalPath);
242
-
243
-		$cache = $storage->getCache('');
244
-
245
-		$results = call_user_func_array(array($cache, $method), $args);
246
-		foreach ($results as $result) {
247
-			if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
248
-				$result['internalPath'] = $result['path'];
249
-				$result['path'] = substr($result['path'], $internalRootLength);
250
-				$result['storage'] = $storage;
251
-				$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
252
-			}
253
-		}
254
-
255
-		$mounts = $this->root->getMountsIn($this->path);
256
-		foreach ($mounts as $mount) {
257
-			$storage = $mount->getStorage();
258
-			if ($storage) {
259
-				$cache = $storage->getCache('');
260
-
261
-				$relativeMountPoint = substr($mount->getMountPoint(), $rootLength);
262
-				$results = call_user_func_array(array($cache, $method), $args);
263
-				foreach ($results as $result) {
264
-					$result['internalPath'] = $result['path'];
265
-					$result['path'] = $relativeMountPoint . $result['path'];
266
-					$result['storage'] = $storage;
267
-					$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
268
-				}
269
-			}
270
-		}
271
-
272
-		return array_map(function (FileInfo $file) {
273
-			return $this->createNode($file->getPath(), $file);
274
-		}, $files);
275
-	}
276
-
277
-	/**
278
-	 * @param int $id
279
-	 * @return \OC\Files\Node\Node[]
280
-	 */
281
-	public function getById($id) {
282
-		$mountCache = $this->root->getUserMountCache();
283
-		if (strpos($this->getPath(), '/', 1) > 0) {
284
-			list(, $user) = explode('/', $this->getPath());
285
-		} else {
286
-			$user = null;
287
-		}
288
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
289
-		$mounts = $this->root->getMountsIn($this->path);
290
-		$mounts[] = $this->root->getMount($this->path);
291
-		/** @var IMountPoint[] $folderMounts */
292
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
293
-			return $mountPoint->getMountPoint();
294
-		}, $mounts), $mounts);
295
-
296
-		/** @var ICachedMountInfo[] $mountsContainingFile */
297
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
298
-			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
299
-		}));
300
-
301
-		if (count($mountsContainingFile) === 0) {
302
-			return [];
303
-		}
304
-
305
-		// we only need to get the cache info once, since all mounts we found point to the same storage
306
-
307
-		$mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()];
308
-		$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
309
-		if (!$cacheEntry) {
310
-			return [];
311
-		}
312
-		// cache jails will hide the "true" internal path
313
-		$internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
314
-
315
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
316
-			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
317
-			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
318
-			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
319
-			$absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
320
-			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
321
-				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
322
-				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
323
-			));
324
-		}, $mountsContainingFile);
325
-
326
-		return array_filter($nodes, function (Node $node) {
327
-			return $this->getRelativePath($node->getPath());
328
-		});
329
-	}
330
-
331
-	public function getFreeSpace() {
332
-		return $this->view->free_space($this->path);
333
-	}
334
-
335
-	public function delete() {
336
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
337
-			$this->sendHooks(array('preDelete'));
338
-			$fileInfo = $this->getFileInfo();
339
-			$this->view->rmdir($this->path);
340
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
341
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
342
-			$this->exists = false;
343
-		} else {
344
-			throw new NotPermittedException('No delete permission for path');
345
-		}
346
-	}
347
-
348
-	/**
349
-	 * Add a suffix to the name in case the file exists
350
-	 *
351
-	 * @param string $name
352
-	 * @return string
353
-	 * @throws NotPermittedException
354
-	 */
355
-	public function getNonExistingName($name) {
356
-		$uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
357
-		return trim($this->getRelativePath($uniqueName), '/');
358
-	}
359
-
360
-	/**
361
-	 * @param int $limit
362
-	 * @param int $offset
363
-	 * @return \OCP\Files\Node[]
364
-	 */
365
-	public function getRecent($limit, $offset = 0) {
366
-		$mimetypeLoader = \OC::$server->getMimeTypeLoader();
367
-		$mounts = $this->root->getMountsIn($this->path);
368
-		$mounts[] = $this->getMountPoint();
369
-
370
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
371
-			return $mount->getStorage();
372
-		});
373
-		$storageIds = array_map(function (IMountPoint $mount) {
374
-			return $mount->getStorage()->getCache()->getNumericStorageId();
375
-		}, $mounts);
376
-		/** @var IMountPoint[] $mountMap */
377
-		$mountMap = array_combine($storageIds, $mounts);
378
-		$folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
379
-
380
-		//todo look into options of filtering path based on storage id (only search in files/ for home storage, filter by share root for shared, etc)
381
-
382
-		$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
383
-		$query = $builder
384
-			->select('f.*')
385
-			->from('filecache', 'f')
386
-			->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
387
-			->andWhere($builder->expr()->orX(
388
-			// handle non empty folders separate
389
-				$builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
390
-				$builder->expr()->eq('f.size', new Literal(0))
391
-			))
392
-			->orderBy('f.mtime', 'DESC')
393
-			->setMaxResults($limit)
394
-			->setFirstResult($offset);
395
-
396
-		$result = $query->execute()->fetchAll();
397
-
398
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
399
-			$mount = $mountMap[$entry['storage']];
400
-			$entry['internalPath'] = $entry['path'];
401
-			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
402
-			$entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
403
-			$path = $this->getAbsolutePath($mount, $entry['path']);
404
-			if (is_null($path)) {
405
-				return null;
406
-			}
407
-			$fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
408
-			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
409
-		}, $result));
410
-
411
-		return array_values(array_filter($files, function (Node $node) {
412
-			$relative = $this->getRelativePath($node->getPath());
413
-			return $relative !== null && $relative !== '/';
414
-		}));
415
-	}
416
-
417
-	private function getAbsolutePath(IMountPoint $mount, $path) {
418
-		$storage = $mount->getStorage();
419
-		if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
420
-			/** @var \OC\Files\Storage\Wrapper\Jail $storage */
421
-			$jailRoot = $storage->getUnjailedPath('');
422
-			$rootLength = strlen($jailRoot) + 1;
423
-			if ($path === $jailRoot) {
424
-				return $mount->getMountPoint();
425
-			} else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
426
-				return $mount->getMountPoint() . substr($path, $rootLength);
427
-			} else {
428
-				return null;
429
-			}
430
-		} else {
431
-			return $mount->getMountPoint() . $path;
432
-		}
433
-	}
39
+    /**
40
+     * Creates a Folder that represents a non-existing path
41
+     *
42
+     * @param string $path path
43
+     * @return string non-existing node class
44
+     */
45
+    protected function createNonExistingNode($path) {
46
+        return new NonExistingFolder($this->root, $this->view, $path);
47
+    }
48
+
49
+    /**
50
+     * @param string $path path relative to the folder
51
+     * @return string
52
+     * @throws \OCP\Files\NotPermittedException
53
+     */
54
+    public function getFullPath($path) {
55
+        if (!$this->isValidPath($path)) {
56
+            throw new NotPermittedException('Invalid path');
57
+        }
58
+        return $this->path . $this->normalizePath($path);
59
+    }
60
+
61
+    /**
62
+     * @param string $path
63
+     * @return string
64
+     */
65
+    public function getRelativePath($path) {
66
+        if ($this->path === '' or $this->path === '/') {
67
+            return $this->normalizePath($path);
68
+        }
69
+        if ($path === $this->path) {
70
+            return '/';
71
+        } else if (strpos($path, $this->path . '/') !== 0) {
72
+            return null;
73
+        } else {
74
+            $path = substr($path, strlen($this->path));
75
+            return $this->normalizePath($path);
76
+        }
77
+    }
78
+
79
+    /**
80
+     * check if a node is a (grand-)child of the folder
81
+     *
82
+     * @param \OC\Files\Node\Node $node
83
+     * @return bool
84
+     */
85
+    public function isSubNode($node) {
86
+        return strpos($node->getPath(), $this->path . '/') === 0;
87
+    }
88
+
89
+    /**
90
+     * get the content of this directory
91
+     *
92
+     * @throws \OCP\Files\NotFoundException
93
+     * @return Node[]
94
+     */
95
+    public function getDirectoryListing() {
96
+        $folderContent = $this->view->getDirectoryContent($this->path);
97
+
98
+        return array_map(function (FileInfo $info) {
99
+            if ($info->getMimetype() === 'httpd/unix-directory') {
100
+                return new Folder($this->root, $this->view, $info->getPath(), $info);
101
+            } else {
102
+                return new File($this->root, $this->view, $info->getPath(), $info);
103
+            }
104
+        }, $folderContent);
105
+    }
106
+
107
+    /**
108
+     * @param string $path
109
+     * @param FileInfo $info
110
+     * @return File|Folder
111
+     */
112
+    protected function createNode($path, FileInfo $info = null) {
113
+        if (is_null($info)) {
114
+            $isDir = $this->view->is_dir($path);
115
+        } else {
116
+            $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
117
+        }
118
+        if ($isDir) {
119
+            return new Folder($this->root, $this->view, $path, $info);
120
+        } else {
121
+            return new File($this->root, $this->view, $path, $info);
122
+        }
123
+    }
124
+
125
+    /**
126
+     * Get the node at $path
127
+     *
128
+     * @param string $path
129
+     * @return \OC\Files\Node\Node
130
+     * @throws \OCP\Files\NotFoundException
131
+     */
132
+    public function get($path) {
133
+        return $this->root->get($this->getFullPath($path));
134
+    }
135
+
136
+    /**
137
+     * @param string $path
138
+     * @return bool
139
+     */
140
+    public function nodeExists($path) {
141
+        try {
142
+            $this->get($path);
143
+            return true;
144
+        } catch (NotFoundException $e) {
145
+            return false;
146
+        }
147
+    }
148
+
149
+    /**
150
+     * @param string $path
151
+     * @return \OC\Files\Node\Folder
152
+     * @throws \OCP\Files\NotPermittedException
153
+     */
154
+    public function newFolder($path) {
155
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
156
+            $fullPath = $this->getFullPath($path);
157
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
158
+            $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
159
+            $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
160
+            $this->view->mkdir($fullPath);
161
+            $node = new Folder($this->root, $this->view, $fullPath);
162
+            $this->root->emit('\OC\Files', 'postWrite', array($node));
163
+            $this->root->emit('\OC\Files', 'postCreate', array($node));
164
+            return $node;
165
+        } else {
166
+            throw new NotPermittedException('No create permission for folder');
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @return \OC\Files\Node\File
173
+     * @throws \OCP\Files\NotPermittedException
174
+     */
175
+    public function newFile($path) {
176
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
177
+            $fullPath = $this->getFullPath($path);
178
+            $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
179
+            $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
180
+            $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
181
+            $this->view->touch($fullPath);
182
+            $node = new File($this->root, $this->view, $fullPath);
183
+            $this->root->emit('\OC\Files', 'postWrite', array($node));
184
+            $this->root->emit('\OC\Files', 'postCreate', array($node));
185
+            return $node;
186
+        } else {
187
+            throw new NotPermittedException('No create permission for path');
188
+        }
189
+    }
190
+
191
+    /**
192
+     * search for files with the name matching $query
193
+     *
194
+     * @param string|ISearchOperator $query
195
+     * @return \OC\Files\Node\Node[]
196
+     */
197
+    public function search($query) {
198
+        if (is_string($query)) {
199
+            return $this->searchCommon('search', array('%' . $query . '%'));
200
+        } else {
201
+            return $this->searchCommon('searchQuery', array($query));
202
+        }
203
+    }
204
+
205
+    /**
206
+     * search for files by mimetype
207
+     *
208
+     * @param string $mimetype
209
+     * @return Node[]
210
+     */
211
+    public function searchByMime($mimetype) {
212
+        return $this->searchCommon('searchByMime', array($mimetype));
213
+    }
214
+
215
+    /**
216
+     * search for files by tag
217
+     *
218
+     * @param string|int $tag name or tag id
219
+     * @param string $userId owner of the tags
220
+     * @return Node[]
221
+     */
222
+    public function searchByTag($tag, $userId) {
223
+        return $this->searchCommon('searchByTag', array($tag, $userId));
224
+    }
225
+
226
+    /**
227
+     * @param string $method cache method
228
+     * @param array $args call args
229
+     * @return \OC\Files\Node\Node[]
230
+     */
231
+    private function searchCommon($method, $args) {
232
+        $files = array();
233
+        $rootLength = strlen($this->path);
234
+        $mount = $this->root->getMount($this->path);
235
+        $storage = $mount->getStorage();
236
+        $internalPath = $mount->getInternalPath($this->path);
237
+        $internalPath = rtrim($internalPath, '/');
238
+        if ($internalPath !== '') {
239
+            $internalPath = $internalPath . '/';
240
+        }
241
+        $internalRootLength = strlen($internalPath);
242
+
243
+        $cache = $storage->getCache('');
244
+
245
+        $results = call_user_func_array(array($cache, $method), $args);
246
+        foreach ($results as $result) {
247
+            if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
248
+                $result['internalPath'] = $result['path'];
249
+                $result['path'] = substr($result['path'], $internalRootLength);
250
+                $result['storage'] = $storage;
251
+                $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
252
+            }
253
+        }
254
+
255
+        $mounts = $this->root->getMountsIn($this->path);
256
+        foreach ($mounts as $mount) {
257
+            $storage = $mount->getStorage();
258
+            if ($storage) {
259
+                $cache = $storage->getCache('');
260
+
261
+                $relativeMountPoint = substr($mount->getMountPoint(), $rootLength);
262
+                $results = call_user_func_array(array($cache, $method), $args);
263
+                foreach ($results as $result) {
264
+                    $result['internalPath'] = $result['path'];
265
+                    $result['path'] = $relativeMountPoint . $result['path'];
266
+                    $result['storage'] = $storage;
267
+                    $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
268
+                }
269
+            }
270
+        }
271
+
272
+        return array_map(function (FileInfo $file) {
273
+            return $this->createNode($file->getPath(), $file);
274
+        }, $files);
275
+    }
276
+
277
+    /**
278
+     * @param int $id
279
+     * @return \OC\Files\Node\Node[]
280
+     */
281
+    public function getById($id) {
282
+        $mountCache = $this->root->getUserMountCache();
283
+        if (strpos($this->getPath(), '/', 1) > 0) {
284
+            list(, $user) = explode('/', $this->getPath());
285
+        } else {
286
+            $user = null;
287
+        }
288
+        $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
289
+        $mounts = $this->root->getMountsIn($this->path);
290
+        $mounts[] = $this->root->getMount($this->path);
291
+        /** @var IMountPoint[] $folderMounts */
292
+        $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
293
+            return $mountPoint->getMountPoint();
294
+        }, $mounts), $mounts);
295
+
296
+        /** @var ICachedMountInfo[] $mountsContainingFile */
297
+        $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
298
+            return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
299
+        }));
300
+
301
+        if (count($mountsContainingFile) === 0) {
302
+            return [];
303
+        }
304
+
305
+        // we only need to get the cache info once, since all mounts we found point to the same storage
306
+
307
+        $mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()];
308
+        $cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
309
+        if (!$cacheEntry) {
310
+            return [];
311
+        }
312
+        // cache jails will hide the "true" internal path
313
+        $internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
314
+
315
+        $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
316
+            $mount = $folderMounts[$cachedMountInfo->getMountPoint()];
317
+            $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
318
+            $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
319
+            $absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
320
+            return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
321
+                $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
322
+                \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
323
+            ));
324
+        }, $mountsContainingFile);
325
+
326
+        return array_filter($nodes, function (Node $node) {
327
+            return $this->getRelativePath($node->getPath());
328
+        });
329
+    }
330
+
331
+    public function getFreeSpace() {
332
+        return $this->view->free_space($this->path);
333
+    }
334
+
335
+    public function delete() {
336
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
337
+            $this->sendHooks(array('preDelete'));
338
+            $fileInfo = $this->getFileInfo();
339
+            $this->view->rmdir($this->path);
340
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
341
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
342
+            $this->exists = false;
343
+        } else {
344
+            throw new NotPermittedException('No delete permission for path');
345
+        }
346
+    }
347
+
348
+    /**
349
+     * Add a suffix to the name in case the file exists
350
+     *
351
+     * @param string $name
352
+     * @return string
353
+     * @throws NotPermittedException
354
+     */
355
+    public function getNonExistingName($name) {
356
+        $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
357
+        return trim($this->getRelativePath($uniqueName), '/');
358
+    }
359
+
360
+    /**
361
+     * @param int $limit
362
+     * @param int $offset
363
+     * @return \OCP\Files\Node[]
364
+     */
365
+    public function getRecent($limit, $offset = 0) {
366
+        $mimetypeLoader = \OC::$server->getMimeTypeLoader();
367
+        $mounts = $this->root->getMountsIn($this->path);
368
+        $mounts[] = $this->getMountPoint();
369
+
370
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
371
+            return $mount->getStorage();
372
+        });
373
+        $storageIds = array_map(function (IMountPoint $mount) {
374
+            return $mount->getStorage()->getCache()->getNumericStorageId();
375
+        }, $mounts);
376
+        /** @var IMountPoint[] $mountMap */
377
+        $mountMap = array_combine($storageIds, $mounts);
378
+        $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
379
+
380
+        //todo look into options of filtering path based on storage id (only search in files/ for home storage, filter by share root for shared, etc)
381
+
382
+        $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
383
+        $query = $builder
384
+            ->select('f.*')
385
+            ->from('filecache', 'f')
386
+            ->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
387
+            ->andWhere($builder->expr()->orX(
388
+            // handle non empty folders separate
389
+                $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
390
+                $builder->expr()->eq('f.size', new Literal(0))
391
+            ))
392
+            ->orderBy('f.mtime', 'DESC')
393
+            ->setMaxResults($limit)
394
+            ->setFirstResult($offset);
395
+
396
+        $result = $query->execute()->fetchAll();
397
+
398
+        $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
399
+            $mount = $mountMap[$entry['storage']];
400
+            $entry['internalPath'] = $entry['path'];
401
+            $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
402
+            $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
403
+            $path = $this->getAbsolutePath($mount, $entry['path']);
404
+            if (is_null($path)) {
405
+                return null;
406
+            }
407
+            $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
408
+            return $this->root->createNode($fileInfo->getPath(), $fileInfo);
409
+        }, $result));
410
+
411
+        return array_values(array_filter($files, function (Node $node) {
412
+            $relative = $this->getRelativePath($node->getPath());
413
+            return $relative !== null && $relative !== '/';
414
+        }));
415
+    }
416
+
417
+    private function getAbsolutePath(IMountPoint $mount, $path) {
418
+        $storage = $mount->getStorage();
419
+        if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
420
+            /** @var \OC\Files\Storage\Wrapper\Jail $storage */
421
+            $jailRoot = $storage->getUnjailedPath('');
422
+            $rootLength = strlen($jailRoot) + 1;
423
+            if ($path === $jailRoot) {
424
+                return $mount->getMountPoint();
425
+            } else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
426
+                return $mount->getMountPoint() . substr($path, $rootLength);
427
+            } else {
428
+                return null;
429
+            }
430
+        } else {
431
+            return $mount->getMountPoint() . $path;
432
+        }
433
+    }
434 434
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 		if (!$this->isValidPath($path)) {
56 56
 			throw new NotPermittedException('Invalid path');
57 57
 		}
58
-		return $this->path . $this->normalizePath($path);
58
+		return $this->path.$this->normalizePath($path);
59 59
 	}
60 60
 
61 61
 	/**
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		}
69 69
 		if ($path === $this->path) {
70 70
 			return '/';
71
-		} else if (strpos($path, $this->path . '/') !== 0) {
71
+		} else if (strpos($path, $this->path.'/') !== 0) {
72 72
 			return null;
73 73
 		} else {
74 74
 			$path = substr($path, strlen($this->path));
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 	 * @return bool
84 84
 	 */
85 85
 	public function isSubNode($node) {
86
-		return strpos($node->getPath(), $this->path . '/') === 0;
86
+		return strpos($node->getPath(), $this->path.'/') === 0;
87 87
 	}
88 88
 
89 89
 	/**
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	public function getDirectoryListing() {
96 96
 		$folderContent = $this->view->getDirectoryContent($this->path);
97 97
 
98
-		return array_map(function (FileInfo $info) {
98
+		return array_map(function(FileInfo $info) {
99 99
 			if ($info->getMimetype() === 'httpd/unix-directory') {
100 100
 				return new Folder($this->root, $this->view, $info->getPath(), $info);
101 101
 			} else {
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 	 */
197 197
 	public function search($query) {
198 198
 		if (is_string($query)) {
199
-			return $this->searchCommon('search', array('%' . $query . '%'));
199
+			return $this->searchCommon('search', array('%'.$query.'%'));
200 200
 		} else {
201 201
 			return $this->searchCommon('searchQuery', array($query));
202 202
 		}
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 		$internalPath = $mount->getInternalPath($this->path);
237 237
 		$internalPath = rtrim($internalPath, '/');
238 238
 		if ($internalPath !== '') {
239
-			$internalPath = $internalPath . '/';
239
+			$internalPath = $internalPath.'/';
240 240
 		}
241 241
 		$internalRootLength = strlen($internalPath);
242 242
 
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 				$result['internalPath'] = $result['path'];
249 249
 				$result['path'] = substr($result['path'], $internalRootLength);
250 250
 				$result['storage'] = $storage;
251
-				$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
251
+				$files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount);
252 252
 			}
253 253
 		}
254 254
 
@@ -262,14 +262,14 @@  discard block
 block discarded – undo
262 262
 				$results = call_user_func_array(array($cache, $method), $args);
263 263
 				foreach ($results as $result) {
264 264
 					$result['internalPath'] = $result['path'];
265
-					$result['path'] = $relativeMountPoint . $result['path'];
265
+					$result['path'] = $relativeMountPoint.$result['path'];
266 266
 					$result['storage'] = $storage;
267
-					$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
267
+					$files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount);
268 268
 				}
269 269
 			}
270 270
 		}
271 271
 
272
-		return array_map(function (FileInfo $file) {
272
+		return array_map(function(FileInfo $file) {
273 273
 			return $this->createNode($file->getPath(), $file);
274 274
 		}, $files);
275 275
 	}
@@ -285,16 +285,16 @@  discard block
 block discarded – undo
285 285
 		} else {
286 286
 			$user = null;
287 287
 		}
288
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
288
+		$mountsContainingFile = $mountCache->getMountsForFileId((int) $id, $user);
289 289
 		$mounts = $this->root->getMountsIn($this->path);
290 290
 		$mounts[] = $this->root->getMount($this->path);
291 291
 		/** @var IMountPoint[] $folderMounts */
292
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
292
+		$folderMounts = array_combine(array_map(function(IMountPoint $mountPoint) {
293 293
 			return $mountPoint->getMountPoint();
294 294
 		}, $mounts), $mounts);
295 295
 
296 296
 		/** @var ICachedMountInfo[] $mountsContainingFile */
297
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
297
+		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function(ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
298 298
 			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
299 299
 		}));
300 300
 
@@ -305,25 +305,25 @@  discard block
 block discarded – undo
305 305
 		// we only need to get the cache info once, since all mounts we found point to the same storage
306 306
 
307 307
 		$mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()];
308
-		$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
308
+		$cacheEntry = $mount->getStorage()->getCache()->get((int) $id);
309 309
 		if (!$cacheEntry) {
310 310
 			return [];
311 311
 		}
312 312
 		// cache jails will hide the "true" internal path
313
-		$internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
313
+		$internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath().'/'.$cacheEntry->getPath(), '/');
314 314
 
315
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
315
+		$nodes = array_map(function(ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
316 316
 			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
317 317
 			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
318 318
 			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
319
-			$absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
319
+			$absolutePath = $cachedMountInfo->getMountPoint().$pathRelativeToMount;
320 320
 			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
321 321
 				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
322 322
 				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
323 323
 			));
324 324
 		}, $mountsContainingFile);
325 325
 
326
-		return array_filter($nodes, function (Node $node) {
326
+		return array_filter($nodes, function(Node $node) {
327 327
 			return $this->getRelativePath($node->getPath());
328 328
 		});
329 329
 	}
@@ -367,10 +367,10 @@  discard block
 block discarded – undo
367 367
 		$mounts = $this->root->getMountsIn($this->path);
368 368
 		$mounts[] = $this->getMountPoint();
369 369
 
370
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
370
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
371 371
 			return $mount->getStorage();
372 372
 		});
373
-		$storageIds = array_map(function (IMountPoint $mount) {
373
+		$storageIds = array_map(function(IMountPoint $mount) {
374 374
 			return $mount->getStorage()->getCache()->getNumericStorageId();
375 375
 		}, $mounts);
376 376
 		/** @var IMountPoint[] $mountMap */
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 
396 396
 		$result = $query->execute()->fetchAll();
397 397
 
398
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
398
+		$files = array_filter(array_map(function(array $entry) use ($mountMap, $mimetypeLoader) {
399 399
 			$mount = $mountMap[$entry['storage']];
400 400
 			$entry['internalPath'] = $entry['path'];
401 401
 			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
 			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
409 409
 		}, $result));
410 410
 
411
-		return array_values(array_filter($files, function (Node $node) {
411
+		return array_values(array_filter($files, function(Node $node) {
412 412
 			$relative = $this->getRelativePath($node->getPath());
413 413
 			return $relative !== null && $relative !== '/';
414 414
 		}));
@@ -422,13 +422,13 @@  discard block
 block discarded – undo
422 422
 			$rootLength = strlen($jailRoot) + 1;
423 423
 			if ($path === $jailRoot) {
424 424
 				return $mount->getMountPoint();
425
-			} else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
426
-				return $mount->getMountPoint() . substr($path, $rootLength);
425
+			} else if (substr($path, 0, $rootLength) === $jailRoot.'/') {
426
+				return $mount->getMountPoint().substr($path, $rootLength);
427 427
 			} else {
428 428
 				return null;
429 429
 			}
430 430
 		} else {
431
-			return $mount->getMountPoint() . $path;
431
+			return $mount->getMountPoint().$path;
432 432
 		}
433 433
 	}
434 434
 }
Please login to merge, or discard this patch.
lib/public/Settings/IIconSection.php 2 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -33,6 +33,7 @@
 block discarded – undo
33 33
 	 *
34 34
 	 * @returns string
35 35
 	 * @since 12
36
+	 * @return string
36 37
 	 */
37 38
 	public function getIcon();
38 39
 }
Please login to merge, or discard this patch.
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@
 block discarded – undo
27 27
  * @since 12
28 28
  */
29 29
 interface IIconSection extends ISection {
30
-	/**
31
-	 * returns the relative path to an 16*16 icon describing the section.
32
-	 * e.g. '/core/img/places/files.svg'
33
-	 *
34
-	 * @returns string
35
-	 * @since 12
36
-	 */
37
-	public function getIcon();
30
+    /**
31
+     * returns the relative path to an 16*16 icon describing the section.
32
+     * e.g. '/core/img/places/files.svg'
33
+     *
34
+     * @returns string
35
+     * @since 12
36
+     */
37
+    public function getIcon();
38 38
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/FTP.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -139,6 +139,9 @@
 block discarded – undo
139 139
 		return false;
140 140
 	}
141 141
 
142
+	/**
143
+	 * @param string $path
144
+	 */
142 145
 	public function writeBack($tmpFile, $path) {
143 146
 		$this->uploadFile($tmpFile, $path);
144 147
 		unlink($tmpFile);
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,8 +93,7 @@
 block discarded – undo
93 93
 	public function unlink($path) {
94 94
 		if ($this->is_dir($path)) {
95 95
 			return $this->rmdir($path);
96
-		}
97
-		else {
96
+		} else {
98 97
 			$url = $this->constructUrl($path);
99 98
 			$result = unlink($url);
100 99
 			clearstatcache(true, $url);
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -36,28 +36,28 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\CallbackWrapper;
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39
-class FTP extends StreamWrapper{
39
+class FTP extends StreamWrapper {
40 40
 	private $password;
41 41
 	private $user;
42 42
 	private $host;
43 43
 	private $secure;
44 44
 	private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+	private static $tempFiles = array();
47 47
 
48 48
 	public function __construct($params) {
49 49
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
50
+			$this->host = $params['host'];
51
+			$this->user = $params['user'];
52
+			$this->password = $params['password'];
53 53
 			if (isset($params['secure'])) {
54 54
 				$this->secure = $params['secure'];
55 55
 			} else {
56 56
 				$this->secure = false;
57 57
 			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!=='/') {
60
-				$this->root='/'.$this->root;
58
+			$this->root = isset($params['root']) ? $params['root'] : '/';
59
+			if (!$this->root || $this->root[0] !== '/') {
60
+				$this->root = '/'.$this->root;
61 61
 			}
62 62
 			if (substr($this->root, -1) !== '/') {
63 63
 				$this->root .= '/';
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 		
69 69
 	}
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
71
+	public function getId() {
72
+		return 'ftp::'.$this->user.'@'.$this->host.'/'.$this->root;
73 73
 	}
74 74
 
75 75
 	/**
@@ -78,11 +78,11 @@  discard block
 block discarded – undo
78 78
 	 * @return string
79 79
 	 */
80 80
 	public function constructUrl($path) {
81
-		$url='ftp';
81
+		$url = 'ftp';
82 82
 		if ($this->secure) {
83
-			$url.='s';
83
+			$url .= 's';
84 84
 		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
85
+		$url .= '://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86 86
 		return $url;
87 87
 	}
88 88
 
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
 			return $result;
102 102
 		}
103 103
 	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
104
+	public function fopen($path, $mode) {
105
+		switch ($mode) {
106 106
 			case 'r':
107 107
 			case 'rb':
108 108
 			case 'w':
@@ -122,17 +122,17 @@  discard block
 block discarded – undo
122 122
 			case 'c':
123 123
 			case 'c+':
124 124
 				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
125
+				if (strrpos($path, '.') !== false) {
126
+					$ext = substr($path, strrpos($path, '.'));
127 127
 				} else {
128
-					$ext='';
128
+					$ext = '';
129 129
 				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
130
+				$tmpFile = \OCP\Files::tmpFile($ext);
131 131
 				if ($this->file_exists($path)) {
132 132
 					$this->getFile($path, $tmpFile);
133 133
 				}
134 134
 				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
135
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
136 136
 					$this->writeBack($tmpFile, $path);
137 137
 				});
138 138
 		}
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -38,122 +38,122 @@
 block discarded – undo
38 38
 use Icewind\Streams\RetryWrapper;
39 39
 
40 40
 class FTP extends StreamWrapper{
41
-	private $password;
42
-	private $user;
43
-	private $host;
44
-	private $secure;
45
-	private $root;
41
+    private $password;
42
+    private $user;
43
+    private $host;
44
+    private $secure;
45
+    private $root;
46 46
 
47
-	private static $tempFiles=array();
47
+    private static $tempFiles=array();
48 48
 
49
-	public function __construct($params) {
50
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
-			$this->host=$params['host'];
52
-			$this->user=$params['user'];
53
-			$this->password=$params['password'];
54
-			if (isset($params['secure'])) {
55
-				$this->secure = $params['secure'];
56
-			} else {
57
-				$this->secure = false;
58
-			}
59
-			$this->root=isset($params['root'])?$params['root']:'/';
60
-			if ( ! $this->root || $this->root[0]!=='/') {
61
-				$this->root='/'.$this->root;
62
-			}
63
-			if (substr($this->root, -1) !== '/') {
64
-				$this->root .= '/';
65
-			}
66
-		} else {
67
-			throw new \Exception('Creating FTP storage failed');
68
-		}
49
+    public function __construct($params) {
50
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
+            $this->host=$params['host'];
52
+            $this->user=$params['user'];
53
+            $this->password=$params['password'];
54
+            if (isset($params['secure'])) {
55
+                $this->secure = $params['secure'];
56
+            } else {
57
+                $this->secure = false;
58
+            }
59
+            $this->root=isset($params['root'])?$params['root']:'/';
60
+            if ( ! $this->root || $this->root[0]!=='/') {
61
+                $this->root='/'.$this->root;
62
+            }
63
+            if (substr($this->root, -1) !== '/') {
64
+                $this->root .= '/';
65
+            }
66
+        } else {
67
+            throw new \Exception('Creating FTP storage failed');
68
+        }
69 69
 		
70
-	}
70
+    }
71 71
 
72
-	public function getId(){
73
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
74
-	}
72
+    public function getId(){
73
+        return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
74
+    }
75 75
 
76
-	/**
77
-	 * construct the ftp url
78
-	 * @param string $path
79
-	 * @return string
80
-	 */
81
-	public function constructUrl($path) {
82
-		$url='ftp';
83
-		if ($this->secure) {
84
-			$url.='s';
85
-		}
86
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87
-		return $url;
88
-	}
76
+    /**
77
+     * construct the ftp url
78
+     * @param string $path
79
+     * @return string
80
+     */
81
+    public function constructUrl($path) {
82
+        $url='ftp';
83
+        if ($this->secure) {
84
+            $url.='s';
85
+        }
86
+        $url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87
+        return $url;
88
+    }
89 89
 
90
-	/**
91
-	 * Unlinks file or directory
92
-	 * @param string $path
93
-	 */
94
-	public function unlink($path) {
95
-		if ($this->is_dir($path)) {
96
-			return $this->rmdir($path);
97
-		}
98
-		else {
99
-			$url = $this->constructUrl($path);
100
-			$result = unlink($url);
101
-			clearstatcache(true, $url);
102
-			return $result;
103
-		}
104
-	}
105
-	public function fopen($path,$mode) {
106
-		switch($mode) {
107
-			case 'r':
108
-			case 'rb':
109
-			case 'w':
110
-			case 'wb':
111
-			case 'a':
112
-			case 'ab':
113
-				//these are supported by the wrapper
114
-				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
115
-				$handle = fopen($this->constructUrl($path), $mode, false, $context);
116
-				return RetryWrapper::wrap($handle);
117
-			case 'r+':
118
-			case 'w+':
119
-			case 'wb+':
120
-			case 'a+':
121
-			case 'x':
122
-			case 'x+':
123
-			case 'c':
124
-			case 'c+':
125
-				//emulate these
126
-				if (strrpos($path, '.')!==false) {
127
-					$ext=substr($path, strrpos($path, '.'));
128
-				} else {
129
-					$ext='';
130
-				}
131
-				$tmpFile=\OCP\Files::tmpFile($ext);
132
-				if ($this->file_exists($path)) {
133
-					$this->getFile($path, $tmpFile);
134
-				}
135
-				$handle = fopen($tmpFile, $mode);
136
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
137
-					$this->writeBack($tmpFile, $path);
138
-				});
139
-		}
140
-		return false;
141
-	}
90
+    /**
91
+     * Unlinks file or directory
92
+     * @param string $path
93
+     */
94
+    public function unlink($path) {
95
+        if ($this->is_dir($path)) {
96
+            return $this->rmdir($path);
97
+        }
98
+        else {
99
+            $url = $this->constructUrl($path);
100
+            $result = unlink($url);
101
+            clearstatcache(true, $url);
102
+            return $result;
103
+        }
104
+    }
105
+    public function fopen($path,$mode) {
106
+        switch($mode) {
107
+            case 'r':
108
+            case 'rb':
109
+            case 'w':
110
+            case 'wb':
111
+            case 'a':
112
+            case 'ab':
113
+                //these are supported by the wrapper
114
+                $context = stream_context_create(array('ftp' => array('overwrite' => true)));
115
+                $handle = fopen($this->constructUrl($path), $mode, false, $context);
116
+                return RetryWrapper::wrap($handle);
117
+            case 'r+':
118
+            case 'w+':
119
+            case 'wb+':
120
+            case 'a+':
121
+            case 'x':
122
+            case 'x+':
123
+            case 'c':
124
+            case 'c+':
125
+                //emulate these
126
+                if (strrpos($path, '.')!==false) {
127
+                    $ext=substr($path, strrpos($path, '.'));
128
+                } else {
129
+                    $ext='';
130
+                }
131
+                $tmpFile=\OCP\Files::tmpFile($ext);
132
+                if ($this->file_exists($path)) {
133
+                    $this->getFile($path, $tmpFile);
134
+                }
135
+                $handle = fopen($tmpFile, $mode);
136
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
137
+                    $this->writeBack($tmpFile, $path);
138
+                });
139
+        }
140
+        return false;
141
+    }
142 142
 
143
-	public function writeBack($tmpFile, $path) {
144
-		$this->uploadFile($tmpFile, $path);
145
-		unlink($tmpFile);
146
-	}
143
+    public function writeBack($tmpFile, $path) {
144
+        $this->uploadFile($tmpFile, $path);
145
+        unlink($tmpFile);
146
+    }
147 147
 
148
-	/**
149
-	 * check if php-ftp is installed
150
-	 */
151
-	public static function checkDependencies() {
152
-		if (function_exists('ftp_login')) {
153
-			return true;
154
-		} else {
155
-			return array('ftp');
156
-		}
157
-	}
148
+    /**
149
+     * check if php-ftp is installed
150
+     */
151
+    public static function checkDependencies() {
152
+        if (function_exists('ftp_login')) {
153
+            return true;
154
+        } else {
155
+            return array('ftp');
156
+        }
157
+    }
158 158
 
159 159
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function showAuthenticate($token) {
151 151
 		$share = $this->shareManager->getShareByToken($token);
152 152
 
153
-		if($this->linkShareAuth($share)) {
153
+		if ($this->linkShareAuth($share)) {
154 154
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155 155
 		}
156 156
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 
179 179
 		$authenticate = $this->linkShareAuth($share, $password);
180 180
 
181
-		if($authenticate === true) {
181
+		if ($authenticate === true) {
182 182
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183 183
 		}
184 184
 
@@ -201,15 +201,15 @@  discard block
 block discarded – undo
201 201
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
202 202
 		if ($password !== null) {
203 203
 			if ($this->shareManager->checkPassword($share, $password)) {
204
-				$this->session->set('public_link_authenticated', (string)$share->getId());
204
+				$this->session->set('public_link_authenticated', (string) $share->getId());
205 205
 			} else {
206 206
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
207 207
 				return false;
208 208
 			}
209 209
 		} else {
210 210
 			// not authenticated ?
211
-			if ( ! $this->session->exists('public_link_authenticated')
212
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
211
+			if (!$this->session->exists('public_link_authenticated')
212
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
213 213
 				return false;
214 214
 			}
215 215
 		}
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		$itemType = $itemSource = $uidOwner = '';
231 231
 		$token = $share;
232 232
 		$exception = null;
233
-		if($share instanceof \OCP\Share\IShare) {
233
+		if ($share instanceof \OCP\Share\IShare) {
234 234
 			try {
235 235
 				$token = $share->getToken();
236 236
 				$uidOwner = $share->getSharedBy();
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 			'errorCode' => $errorCode,
250 250
 			'errorMessage' => $errorMessage,
251 251
 		]);
252
-		if(!is_null($exception)) {
252
+		if (!is_null($exception)) {
253 253
 			throw $exception;
254 254
 		}
255 255
 	}
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
376 376
 		$ogPreview = '';
377 377
 		if ($shareTmpl['previewSupported']) {
378
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
378
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
379 379
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
380 380
 			$ogPreview = $shareTmpl['previewImage'];
381 381
 
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
 
413 413
 		// OpenGraph Support: http://ogp.me/
414 414
 		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
415
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
415
+		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName().($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '')]);
416 416
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
417 417
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
418 418
 		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 
447 447
 		$share = $this->shareManager->getShareByToken($token);
448 448
 
449
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
449
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
450 450
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
451 451
 		}
452 452
 
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
 
529 529
 		$this->emitAccessShareHook($share);
530 530
 
531
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
531
+		$server_params = array('head' => $this->request->getMethod() === 'HEAD');
532 532
 
533 533
 		/**
534 534
 		 * Http range requests support
Please login to merge, or discard this patch.
Indentation   +585 added lines, -585 removed lines patch added patch discarded remove patch
@@ -70,593 +70,593 @@
 block discarded – undo
70 70
  */
71 71
 class ShareController extends Controller {
72 72
 
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var IURLGenerator */
76
-	protected $urlGenerator;
77
-	/** @var IUserManager */
78
-	protected $userManager;
79
-	/** @var ILogger */
80
-	protected $logger;
81
-	/** @var \OCP\Activity\IManager */
82
-	protected $activityManager;
83
-	/** @var \OCP\Share\IManager */
84
-	protected $shareManager;
85
-	/** @var ISession */
86
-	protected $session;
87
-	/** @var IPreview */
88
-	protected $previewManager;
89
-	/** @var IRootFolder */
90
-	protected $rootFolder;
91
-	/** @var FederatedShareProvider */
92
-	protected $federatedShareProvider;
93
-	/** @var EventDispatcherInterface */
94
-	protected $eventDispatcher;
95
-	/** @var IL10N */
96
-	protected $l10n;
97
-	/** @var Defaults */
98
-	protected $defaults;
99
-
100
-	/**
101
-	 * @param string $appName
102
-	 * @param IRequest $request
103
-	 * @param IConfig $config
104
-	 * @param IURLGenerator $urlGenerator
105
-	 * @param IUserManager $userManager
106
-	 * @param ILogger $logger
107
-	 * @param \OCP\Activity\IManager $activityManager
108
-	 * @param \OCP\Share\IManager $shareManager
109
-	 * @param ISession $session
110
-	 * @param IPreview $previewManager
111
-	 * @param IRootFolder $rootFolder
112
-	 * @param FederatedShareProvider $federatedShareProvider
113
-	 * @param EventDispatcherInterface $eventDispatcher
114
-	 * @param IL10N $l10n
115
-	 * @param Defaults $defaults
116
-	 */
117
-	public function __construct($appName,
118
-								IRequest $request,
119
-								IConfig $config,
120
-								IURLGenerator $urlGenerator,
121
-								IUserManager $userManager,
122
-								ILogger $logger,
123
-								\OCP\Activity\IManager $activityManager,
124
-								\OCP\Share\IManager $shareManager,
125
-								ISession $session,
126
-								IPreview $previewManager,
127
-								IRootFolder $rootFolder,
128
-								FederatedShareProvider $federatedShareProvider,
129
-								EventDispatcherInterface $eventDispatcher,
130
-								IL10N $l10n,
131
-								Defaults $defaults) {
132
-		parent::__construct($appName, $request);
133
-
134
-		$this->config = $config;
135
-		$this->urlGenerator = $urlGenerator;
136
-		$this->userManager = $userManager;
137
-		$this->logger = $logger;
138
-		$this->activityManager = $activityManager;
139
-		$this->shareManager = $shareManager;
140
-		$this->session = $session;
141
-		$this->previewManager = $previewManager;
142
-		$this->rootFolder = $rootFolder;
143
-		$this->federatedShareProvider = $federatedShareProvider;
144
-		$this->eventDispatcher = $eventDispatcher;
145
-		$this->l10n = $l10n;
146
-		$this->defaults = $defaults;
147
-	}
148
-
149
-	/**
150
-	 * @PublicPage
151
-	 * @NoCSRFRequired
152
-	 *
153
-	 * @param string $token
154
-	 * @return TemplateResponse|RedirectResponse
155
-	 */
156
-	public function showAuthenticate($token) {
157
-		$share = $this->shareManager->getShareByToken($token);
158
-
159
-		if($this->linkShareAuth($share)) {
160
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161
-		}
162
-
163
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
164
-	}
165
-
166
-	/**
167
-	 * @PublicPage
168
-	 * @UseSession
169
-	 * @BruteForceProtection(action=publicLinkAuth)
170
-	 *
171
-	 * Authenticates against password-protected shares
172
-	 * @param string $token
173
-	 * @param string $password
174
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
175
-	 */
176
-	public function authenticate($token, $password = '') {
177
-
178
-		// Check whether share exists
179
-		try {
180
-			$share = $this->shareManager->getShareByToken($token);
181
-		} catch (ShareNotFound $e) {
182
-			return new NotFoundResponse();
183
-		}
184
-
185
-		$authenticate = $this->linkShareAuth($share, $password);
186
-
187
-		if($authenticate === true) {
188
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
189
-		}
190
-
191
-		$response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
192
-		$response->throttle();
193
-		return $response;
194
-	}
195
-
196
-	/**
197
-	 * Authenticate a link item with the given password.
198
-	 * Or use the session if no password is provided.
199
-	 *
200
-	 * This is a modified version of Helper::authenticate
201
-	 * TODO: Try to merge back eventually with Helper::authenticate
202
-	 *
203
-	 * @param \OCP\Share\IShare $share
204
-	 * @param string|null $password
205
-	 * @return bool
206
-	 */
207
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
208
-		if ($password !== null) {
209
-			if ($this->shareManager->checkPassword($share, $password)) {
210
-				$this->session->set('public_link_authenticated', (string)$share->getId());
211
-			} else {
212
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
213
-				return false;
214
-			}
215
-		} else {
216
-			// not authenticated ?
217
-			if ( ! $this->session->exists('public_link_authenticated')
218
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
219
-				return false;
220
-			}
221
-		}
222
-		return true;
223
-	}
224
-
225
-	/**
226
-	 * throws hooks when a share is attempted to be accessed
227
-	 *
228
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
229
-	 * otherwise token
230
-	 * @param int $errorCode
231
-	 * @param string $errorMessage
232
-	 * @throws \OC\HintException
233
-	 * @throws \OC\ServerNotAvailableException
234
-	 */
235
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
236
-		$itemType = $itemSource = $uidOwner = '';
237
-		$token = $share;
238
-		$exception = null;
239
-		if($share instanceof \OCP\Share\IShare) {
240
-			try {
241
-				$token = $share->getToken();
242
-				$uidOwner = $share->getSharedBy();
243
-				$itemType = $share->getNodeType();
244
-				$itemSource = $share->getNodeId();
245
-			} catch (\Exception $e) {
246
-				// we log what we know and pass on the exception afterwards
247
-				$exception = $e;
248
-			}
249
-		}
250
-		\OC_Hook::emit(Share::class, 'share_link_access', [
251
-			'itemType' => $itemType,
252
-			'itemSource' => $itemSource,
253
-			'uidOwner' => $uidOwner,
254
-			'token' => $token,
255
-			'errorCode' => $errorCode,
256
-			'errorMessage' => $errorMessage,
257
-		]);
258
-		if(!is_null($exception)) {
259
-			throw $exception;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * Validate the permissions of the share
265
-	 *
266
-	 * @param Share\IShare $share
267
-	 * @return bool
268
-	 */
269
-	private function validateShare(\OCP\Share\IShare $share) {
270
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
271
-	}
272
-
273
-	/**
274
-	 * @PublicPage
275
-	 * @NoCSRFRequired
276
-	 *
277
-	 * @param string $token
278
-	 * @param string $path
279
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
280
-	 * @throws NotFoundException
281
-	 * @throws \Exception
282
-	 */
283
-	public function showShare($token, $path = '') {
284
-		\OC_User::setIncognitoMode(true);
285
-
286
-		// Check whether share exists
287
-		try {
288
-			$share = $this->shareManager->getShareByToken($token);
289
-		} catch (ShareNotFound $e) {
290
-			$this->emitAccessShareHook($token, 404, 'Share not found');
291
-			return new NotFoundResponse();
292
-		}
293
-
294
-		// Share is password protected - check whether the user is permitted to access the share
295
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
296
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
297
-				array('token' => $token)));
298
-		}
299
-
300
-		if (!$this->validateShare($share)) {
301
-			throw new NotFoundException();
302
-		}
303
-		// We can't get the path of a file share
304
-		try {
305
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
306
-				$this->emitAccessShareHook($share, 404, 'Share not found');
307
-				throw new NotFoundException();
308
-			}
309
-		} catch (\Exception $e) {
310
-			$this->emitAccessShareHook($share, 404, 'Share not found');
311
-			throw $e;
312
-		}
313
-
314
-		$shareTmpl = [];
315
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
316
-		$shareTmpl['owner'] = $share->getShareOwner();
317
-		$shareTmpl['filename'] = $share->getNode()->getName();
318
-		$shareTmpl['directory_path'] = $share->getTarget();
319
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
320
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
321
-		$shareTmpl['dirToken'] = $token;
322
-		$shareTmpl['sharingToken'] = $token;
323
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
324
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
325
-		$shareTmpl['dir'] = '';
326
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
327
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
328
-
329
-		// Show file list
330
-		$hideFileList = false;
331
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
332
-			/** @var \OCP\Files\Folder $rootFolder */
333
-			$rootFolder = $share->getNode();
334
-
335
-			try {
336
-				$folderNode = $rootFolder->get($path);
337
-			} catch (\OCP\Files\NotFoundException $e) {
338
-				$this->emitAccessShareHook($share, 404, 'Share not found');
339
-				throw new NotFoundException();
340
-			}
341
-
342
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
343
-
344
-			/*
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var IURLGenerator */
76
+    protected $urlGenerator;
77
+    /** @var IUserManager */
78
+    protected $userManager;
79
+    /** @var ILogger */
80
+    protected $logger;
81
+    /** @var \OCP\Activity\IManager */
82
+    protected $activityManager;
83
+    /** @var \OCP\Share\IManager */
84
+    protected $shareManager;
85
+    /** @var ISession */
86
+    protected $session;
87
+    /** @var IPreview */
88
+    protected $previewManager;
89
+    /** @var IRootFolder */
90
+    protected $rootFolder;
91
+    /** @var FederatedShareProvider */
92
+    protected $federatedShareProvider;
93
+    /** @var EventDispatcherInterface */
94
+    protected $eventDispatcher;
95
+    /** @var IL10N */
96
+    protected $l10n;
97
+    /** @var Defaults */
98
+    protected $defaults;
99
+
100
+    /**
101
+     * @param string $appName
102
+     * @param IRequest $request
103
+     * @param IConfig $config
104
+     * @param IURLGenerator $urlGenerator
105
+     * @param IUserManager $userManager
106
+     * @param ILogger $logger
107
+     * @param \OCP\Activity\IManager $activityManager
108
+     * @param \OCP\Share\IManager $shareManager
109
+     * @param ISession $session
110
+     * @param IPreview $previewManager
111
+     * @param IRootFolder $rootFolder
112
+     * @param FederatedShareProvider $federatedShareProvider
113
+     * @param EventDispatcherInterface $eventDispatcher
114
+     * @param IL10N $l10n
115
+     * @param Defaults $defaults
116
+     */
117
+    public function __construct($appName,
118
+                                IRequest $request,
119
+                                IConfig $config,
120
+                                IURLGenerator $urlGenerator,
121
+                                IUserManager $userManager,
122
+                                ILogger $logger,
123
+                                \OCP\Activity\IManager $activityManager,
124
+                                \OCP\Share\IManager $shareManager,
125
+                                ISession $session,
126
+                                IPreview $previewManager,
127
+                                IRootFolder $rootFolder,
128
+                                FederatedShareProvider $federatedShareProvider,
129
+                                EventDispatcherInterface $eventDispatcher,
130
+                                IL10N $l10n,
131
+                                Defaults $defaults) {
132
+        parent::__construct($appName, $request);
133
+
134
+        $this->config = $config;
135
+        $this->urlGenerator = $urlGenerator;
136
+        $this->userManager = $userManager;
137
+        $this->logger = $logger;
138
+        $this->activityManager = $activityManager;
139
+        $this->shareManager = $shareManager;
140
+        $this->session = $session;
141
+        $this->previewManager = $previewManager;
142
+        $this->rootFolder = $rootFolder;
143
+        $this->federatedShareProvider = $federatedShareProvider;
144
+        $this->eventDispatcher = $eventDispatcher;
145
+        $this->l10n = $l10n;
146
+        $this->defaults = $defaults;
147
+    }
148
+
149
+    /**
150
+     * @PublicPage
151
+     * @NoCSRFRequired
152
+     *
153
+     * @param string $token
154
+     * @return TemplateResponse|RedirectResponse
155
+     */
156
+    public function showAuthenticate($token) {
157
+        $share = $this->shareManager->getShareByToken($token);
158
+
159
+        if($this->linkShareAuth($share)) {
160
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161
+        }
162
+
163
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
164
+    }
165
+
166
+    /**
167
+     * @PublicPage
168
+     * @UseSession
169
+     * @BruteForceProtection(action=publicLinkAuth)
170
+     *
171
+     * Authenticates against password-protected shares
172
+     * @param string $token
173
+     * @param string $password
174
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
175
+     */
176
+    public function authenticate($token, $password = '') {
177
+
178
+        // Check whether share exists
179
+        try {
180
+            $share = $this->shareManager->getShareByToken($token);
181
+        } catch (ShareNotFound $e) {
182
+            return new NotFoundResponse();
183
+        }
184
+
185
+        $authenticate = $this->linkShareAuth($share, $password);
186
+
187
+        if($authenticate === true) {
188
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
189
+        }
190
+
191
+        $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
192
+        $response->throttle();
193
+        return $response;
194
+    }
195
+
196
+    /**
197
+     * Authenticate a link item with the given password.
198
+     * Or use the session if no password is provided.
199
+     *
200
+     * This is a modified version of Helper::authenticate
201
+     * TODO: Try to merge back eventually with Helper::authenticate
202
+     *
203
+     * @param \OCP\Share\IShare $share
204
+     * @param string|null $password
205
+     * @return bool
206
+     */
207
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
208
+        if ($password !== null) {
209
+            if ($this->shareManager->checkPassword($share, $password)) {
210
+                $this->session->set('public_link_authenticated', (string)$share->getId());
211
+            } else {
212
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
213
+                return false;
214
+            }
215
+        } else {
216
+            // not authenticated ?
217
+            if ( ! $this->session->exists('public_link_authenticated')
218
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
219
+                return false;
220
+            }
221
+        }
222
+        return true;
223
+    }
224
+
225
+    /**
226
+     * throws hooks when a share is attempted to be accessed
227
+     *
228
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
229
+     * otherwise token
230
+     * @param int $errorCode
231
+     * @param string $errorMessage
232
+     * @throws \OC\HintException
233
+     * @throws \OC\ServerNotAvailableException
234
+     */
235
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
236
+        $itemType = $itemSource = $uidOwner = '';
237
+        $token = $share;
238
+        $exception = null;
239
+        if($share instanceof \OCP\Share\IShare) {
240
+            try {
241
+                $token = $share->getToken();
242
+                $uidOwner = $share->getSharedBy();
243
+                $itemType = $share->getNodeType();
244
+                $itemSource = $share->getNodeId();
245
+            } catch (\Exception $e) {
246
+                // we log what we know and pass on the exception afterwards
247
+                $exception = $e;
248
+            }
249
+        }
250
+        \OC_Hook::emit(Share::class, 'share_link_access', [
251
+            'itemType' => $itemType,
252
+            'itemSource' => $itemSource,
253
+            'uidOwner' => $uidOwner,
254
+            'token' => $token,
255
+            'errorCode' => $errorCode,
256
+            'errorMessage' => $errorMessage,
257
+        ]);
258
+        if(!is_null($exception)) {
259
+            throw $exception;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * Validate the permissions of the share
265
+     *
266
+     * @param Share\IShare $share
267
+     * @return bool
268
+     */
269
+    private function validateShare(\OCP\Share\IShare $share) {
270
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
271
+    }
272
+
273
+    /**
274
+     * @PublicPage
275
+     * @NoCSRFRequired
276
+     *
277
+     * @param string $token
278
+     * @param string $path
279
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
280
+     * @throws NotFoundException
281
+     * @throws \Exception
282
+     */
283
+    public function showShare($token, $path = '') {
284
+        \OC_User::setIncognitoMode(true);
285
+
286
+        // Check whether share exists
287
+        try {
288
+            $share = $this->shareManager->getShareByToken($token);
289
+        } catch (ShareNotFound $e) {
290
+            $this->emitAccessShareHook($token, 404, 'Share not found');
291
+            return new NotFoundResponse();
292
+        }
293
+
294
+        // Share is password protected - check whether the user is permitted to access the share
295
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
296
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
297
+                array('token' => $token)));
298
+        }
299
+
300
+        if (!$this->validateShare($share)) {
301
+            throw new NotFoundException();
302
+        }
303
+        // We can't get the path of a file share
304
+        try {
305
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
306
+                $this->emitAccessShareHook($share, 404, 'Share not found');
307
+                throw new NotFoundException();
308
+            }
309
+        } catch (\Exception $e) {
310
+            $this->emitAccessShareHook($share, 404, 'Share not found');
311
+            throw $e;
312
+        }
313
+
314
+        $shareTmpl = [];
315
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
316
+        $shareTmpl['owner'] = $share->getShareOwner();
317
+        $shareTmpl['filename'] = $share->getNode()->getName();
318
+        $shareTmpl['directory_path'] = $share->getTarget();
319
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
320
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
321
+        $shareTmpl['dirToken'] = $token;
322
+        $shareTmpl['sharingToken'] = $token;
323
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
324
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
325
+        $shareTmpl['dir'] = '';
326
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
327
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
328
+
329
+        // Show file list
330
+        $hideFileList = false;
331
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
332
+            /** @var \OCP\Files\Folder $rootFolder */
333
+            $rootFolder = $share->getNode();
334
+
335
+            try {
336
+                $folderNode = $rootFolder->get($path);
337
+            } catch (\OCP\Files\NotFoundException $e) {
338
+                $this->emitAccessShareHook($share, 404, 'Share not found');
339
+                throw new NotFoundException();
340
+            }
341
+
342
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
343
+
344
+            /*
345 345
 			 * The OC_Util methods require a view. This just uses the node API
346 346
 			 */
347
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
348
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
349
-				$freeSpace = max($freeSpace, 0);
350
-			} else {
351
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
352
-			}
353
-
354
-			$hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
355
-			$maxUploadFilesize = $freeSpace;
356
-
357
-			$folder = new Template('files', 'list', '');
358
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
359
-			$folder->assign('dirToken', $token);
360
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
361
-			$folder->assign('isPublic', true);
362
-			$folder->assign('hideFileList', $hideFileList);
363
-			$folder->assign('publicUploadEnabled', 'no');
364
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
365
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
366
-			$folder->assign('freeSpace', $freeSpace);
367
-			$folder->assign('usedSpacePercent', 0);
368
-			$folder->assign('trash', false);
369
-			$shareTmpl['folder'] = $folder->fetchPage();
370
-		}
371
-
372
-		$shareTmpl['hideFileList'] = $hideFileList;
373
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
374
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
375
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
376
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
377
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
378
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
379
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
380
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
381
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
382
-		$ogPreview = '';
383
-		if ($shareTmpl['previewSupported']) {
384
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
385
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
386
-			$ogPreview = $shareTmpl['previewImage'];
387
-
388
-			// We just have direct previews for image files
389
-			if ($share->getNode()->getMimePart() === 'image') {
390
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
391
-
392
-				$ogPreview = $shareTmpl['previewURL'];
393
-
394
-				//Whatapp is kind of picky about their size requirements
395
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
396
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
397
-						't' => $token,
398
-						'x' => 256,
399
-						'y' => 256,
400
-						'a' => true,
401
-					]);
402
-				}
403
-			}
404
-		} else {
405
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
406
-			$ogPreview = $shareTmpl['previewImage'];
407
-		}
408
-
409
-		// Load files we need
410
-		\OCP\Util::addScript('files', 'file-upload');
411
-		\OCP\Util::addStyle('files_sharing', 'publicView');
412
-		\OCP\Util::addScript('files_sharing', 'public');
413
-		\OCP\Util::addScript('files', 'fileactions');
414
-		\OCP\Util::addScript('files', 'fileactionsmenu');
415
-		\OCP\Util::addScript('files', 'jquery.fileupload');
416
-		\OCP\Util::addScript('files_sharing', 'files_drop');
417
-
418
-		if (isset($shareTmpl['folder'])) {
419
-			// JS required for folders
420
-			\OCP\Util::addStyle('files', 'merged');
421
-			\OCP\Util::addScript('files', 'filesummary');
422
-			\OCP\Util::addScript('files', 'breadcrumb');
423
-			\OCP\Util::addScript('files', 'fileinfomodel');
424
-			\OCP\Util::addScript('files', 'newfilemenu');
425
-			\OCP\Util::addScript('files', 'files');
426
-			\OCP\Util::addScript('files', 'filelist');
427
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
428
-		}
429
-
430
-		// OpenGraph Support: http://ogp.me/
431
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
432
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
433
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
434
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
435
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
436
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
437
-
438
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
439
-
440
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
441
-		$csp->addAllowedFrameDomain('\'self\'');
442
-
443
-		$response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
444
-		$response->setHeaderTitle($shareTmpl['filename']);
445
-		$response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
446
-		$response->setHeaderActions([
447
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
448
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
449
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
450
-			new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
451
-		]);
452
-
453
-		$response->setContentSecurityPolicy($csp);
454
-
455
-		$this->emitAccessShareHook($share);
456
-
457
-		return $response;
458
-	}
459
-
460
-	/**
461
-	 * @PublicPage
462
-	 * @NoCSRFRequired
463
-	 *
464
-	 * @param string $token
465
-	 * @param string $files
466
-	 * @param string $path
467
-	 * @param string $downloadStartSecret
468
-	 * @return void|\OCP\AppFramework\Http\Response
469
-	 * @throws NotFoundException
470
-	 */
471
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
472
-		\OC_User::setIncognitoMode(true);
473
-
474
-		$share = $this->shareManager->getShareByToken($token);
475
-
476
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
477
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
478
-		}
479
-
480
-		// Share is password protected - check whether the user is permitted to access the share
481
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
482
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
483
-				['token' => $token]));
484
-		}
485
-
486
-		$files_list = null;
487
-		if (!is_null($files)) { // download selected files
488
-			$files_list = json_decode($files);
489
-			// in case we get only a single file
490
-			if ($files_list === null) {
491
-				$files_list = [$files];
492
-			}
493
-			// Just in case $files is a single int like '1234'
494
-			if (!is_array($files_list)) {
495
-				$files_list = [$files_list];
496
-			}
497
-		}
498
-
499
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
500
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
501
-
502
-		if (!$this->validateShare($share)) {
503
-			throw new NotFoundException();
504
-		}
505
-
506
-		// Single file share
507
-		if ($share->getNode() instanceof \OCP\Files\File) {
508
-			// Single file download
509
-			$this->singleFileDownloaded($share, $share->getNode());
510
-		}
511
-		// Directory share
512
-		else {
513
-			/** @var \OCP\Files\Folder $node */
514
-			$node = $share->getNode();
515
-
516
-			// Try to get the path
517
-			if ($path !== '') {
518
-				try {
519
-					$node = $node->get($path);
520
-				} catch (NotFoundException $e) {
521
-					$this->emitAccessShareHook($share, 404, 'Share not found');
522
-					return new NotFoundResponse();
523
-				}
524
-			}
525
-
526
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
527
-
528
-			if ($node instanceof \OCP\Files\File) {
529
-				// Single file download
530
-				$this->singleFileDownloaded($share, $share->getNode());
531
-			} else if (!empty($files_list)) {
532
-				$this->fileListDownloaded($share, $files_list, $node);
533
-			} else {
534
-				// The folder is downloaded
535
-				$this->singleFileDownloaded($share, $share->getNode());
536
-			}
537
-		}
538
-
539
-		/* FIXME: We should do this all nicely in OCP */
540
-		OC_Util::tearDownFS();
541
-		OC_Util::setupFS($share->getShareOwner());
542
-
543
-		/**
544
-		 * this sets a cookie to be able to recognize the start of the download
545
-		 * the content must not be longer than 32 characters and must only contain
546
-		 * alphanumeric characters
547
-		 */
548
-		if (!empty($downloadStartSecret)
549
-			&& !isset($downloadStartSecret[32])
550
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
551
-
552
-			// FIXME: set on the response once we use an actual app framework response
553
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
554
-		}
555
-
556
-		$this->emitAccessShareHook($share);
557
-
558
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
559
-
560
-		/**
561
-		 * Http range requests support
562
-		 */
563
-		if (isset($_SERVER['HTTP_RANGE'])) {
564
-			$server_params['range'] = $this->request->getHeader('Range');
565
-		}
566
-
567
-		// download selected files
568
-		if (!is_null($files) && $files !== '') {
569
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
570
-			// after dispatching the request which results in a "Cannot modify header information" notice.
571
-			OC_Files::get($originalSharePath, $files_list, $server_params);
572
-			exit();
573
-		} else {
574
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
575
-			// after dispatching the request which results in a "Cannot modify header information" notice.
576
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
577
-			exit();
578
-		}
579
-	}
580
-
581
-	/**
582
-	 * create activity for every downloaded file
583
-	 *
584
-	 * @param Share\IShare $share
585
-	 * @param array $files_list
586
-	 * @param \OCP\Files\Folder $node
587
-	 */
588
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
589
-		foreach ($files_list as $file) {
590
-			$subNode = $node->get($file);
591
-			$this->singleFileDownloaded($share, $subNode);
592
-		}
593
-
594
-	}
595
-
596
-	/**
597
-	 * create activity if a single file was downloaded from a link share
598
-	 *
599
-	 * @param Share\IShare $share
600
-	 */
601
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
602
-
603
-		$fileId = $node->getId();
604
-
605
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
606
-		$userNodeList = $userFolder->getById($fileId);
607
-		$userNode = $userNodeList[0];
608
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
609
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
610
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
611
-
612
-		$parameters = [$userPath];
613
-
614
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
615
-			if ($node instanceof \OCP\Files\File) {
616
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
617
-			} else {
618
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
619
-			}
620
-			$parameters[] = $share->getSharedWith();
621
-		} else {
622
-			if ($node instanceof \OCP\Files\File) {
623
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
624
-			} else {
625
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
626
-			}
627
-		}
628
-
629
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
630
-
631
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
632
-			$parameters[0] = $ownerPath;
633
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
634
-		}
635
-	}
636
-
637
-	/**
638
-	 * publish activity
639
-	 *
640
-	 * @param string $subject
641
-	 * @param array $parameters
642
-	 * @param string $affectedUser
643
-	 * @param int $fileId
644
-	 * @param string $filePath
645
-	 */
646
-	protected function publishActivity($subject,
647
-										array $parameters,
648
-										$affectedUser,
649
-										$fileId,
650
-										$filePath) {
651
-
652
-		$event = $this->activityManager->generateEvent();
653
-		$event->setApp('files_sharing')
654
-			->setType('public_links')
655
-			->setSubject($subject, $parameters)
656
-			->setAffectedUser($affectedUser)
657
-			->setObject('files', $fileId, $filePath);
658
-		$this->activityManager->publish($event);
659
-	}
347
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
348
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
349
+                $freeSpace = max($freeSpace, 0);
350
+            } else {
351
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
352
+            }
353
+
354
+            $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
355
+            $maxUploadFilesize = $freeSpace;
356
+
357
+            $folder = new Template('files', 'list', '');
358
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
359
+            $folder->assign('dirToken', $token);
360
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
361
+            $folder->assign('isPublic', true);
362
+            $folder->assign('hideFileList', $hideFileList);
363
+            $folder->assign('publicUploadEnabled', 'no');
364
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
365
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
366
+            $folder->assign('freeSpace', $freeSpace);
367
+            $folder->assign('usedSpacePercent', 0);
368
+            $folder->assign('trash', false);
369
+            $shareTmpl['folder'] = $folder->fetchPage();
370
+        }
371
+
372
+        $shareTmpl['hideFileList'] = $hideFileList;
373
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
374
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
375
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
376
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
377
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
378
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
379
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
380
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
381
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
382
+        $ogPreview = '';
383
+        if ($shareTmpl['previewSupported']) {
384
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
385
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
386
+            $ogPreview = $shareTmpl['previewImage'];
387
+
388
+            // We just have direct previews for image files
389
+            if ($share->getNode()->getMimePart() === 'image') {
390
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
391
+
392
+                $ogPreview = $shareTmpl['previewURL'];
393
+
394
+                //Whatapp is kind of picky about their size requirements
395
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
396
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
397
+                        't' => $token,
398
+                        'x' => 256,
399
+                        'y' => 256,
400
+                        'a' => true,
401
+                    ]);
402
+                }
403
+            }
404
+        } else {
405
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
406
+            $ogPreview = $shareTmpl['previewImage'];
407
+        }
408
+
409
+        // Load files we need
410
+        \OCP\Util::addScript('files', 'file-upload');
411
+        \OCP\Util::addStyle('files_sharing', 'publicView');
412
+        \OCP\Util::addScript('files_sharing', 'public');
413
+        \OCP\Util::addScript('files', 'fileactions');
414
+        \OCP\Util::addScript('files', 'fileactionsmenu');
415
+        \OCP\Util::addScript('files', 'jquery.fileupload');
416
+        \OCP\Util::addScript('files_sharing', 'files_drop');
417
+
418
+        if (isset($shareTmpl['folder'])) {
419
+            // JS required for folders
420
+            \OCP\Util::addStyle('files', 'merged');
421
+            \OCP\Util::addScript('files', 'filesummary');
422
+            \OCP\Util::addScript('files', 'breadcrumb');
423
+            \OCP\Util::addScript('files', 'fileinfomodel');
424
+            \OCP\Util::addScript('files', 'newfilemenu');
425
+            \OCP\Util::addScript('files', 'files');
426
+            \OCP\Util::addScript('files', 'filelist');
427
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
428
+        }
429
+
430
+        // OpenGraph Support: http://ogp.me/
431
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
432
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
433
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
434
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
435
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
436
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
437
+
438
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
439
+
440
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
441
+        $csp->addAllowedFrameDomain('\'self\'');
442
+
443
+        $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
444
+        $response->setHeaderTitle($shareTmpl['filename']);
445
+        $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
446
+        $response->setHeaderActions([
447
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
448
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
449
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
450
+            new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
451
+        ]);
452
+
453
+        $response->setContentSecurityPolicy($csp);
454
+
455
+        $this->emitAccessShareHook($share);
456
+
457
+        return $response;
458
+    }
459
+
460
+    /**
461
+     * @PublicPage
462
+     * @NoCSRFRequired
463
+     *
464
+     * @param string $token
465
+     * @param string $files
466
+     * @param string $path
467
+     * @param string $downloadStartSecret
468
+     * @return void|\OCP\AppFramework\Http\Response
469
+     * @throws NotFoundException
470
+     */
471
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
472
+        \OC_User::setIncognitoMode(true);
473
+
474
+        $share = $this->shareManager->getShareByToken($token);
475
+
476
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
477
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
478
+        }
479
+
480
+        // Share is password protected - check whether the user is permitted to access the share
481
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
482
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
483
+                ['token' => $token]));
484
+        }
485
+
486
+        $files_list = null;
487
+        if (!is_null($files)) { // download selected files
488
+            $files_list = json_decode($files);
489
+            // in case we get only a single file
490
+            if ($files_list === null) {
491
+                $files_list = [$files];
492
+            }
493
+            // Just in case $files is a single int like '1234'
494
+            if (!is_array($files_list)) {
495
+                $files_list = [$files_list];
496
+            }
497
+        }
498
+
499
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
500
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
501
+
502
+        if (!$this->validateShare($share)) {
503
+            throw new NotFoundException();
504
+        }
505
+
506
+        // Single file share
507
+        if ($share->getNode() instanceof \OCP\Files\File) {
508
+            // Single file download
509
+            $this->singleFileDownloaded($share, $share->getNode());
510
+        }
511
+        // Directory share
512
+        else {
513
+            /** @var \OCP\Files\Folder $node */
514
+            $node = $share->getNode();
515
+
516
+            // Try to get the path
517
+            if ($path !== '') {
518
+                try {
519
+                    $node = $node->get($path);
520
+                } catch (NotFoundException $e) {
521
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
522
+                    return new NotFoundResponse();
523
+                }
524
+            }
525
+
526
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
527
+
528
+            if ($node instanceof \OCP\Files\File) {
529
+                // Single file download
530
+                $this->singleFileDownloaded($share, $share->getNode());
531
+            } else if (!empty($files_list)) {
532
+                $this->fileListDownloaded($share, $files_list, $node);
533
+            } else {
534
+                // The folder is downloaded
535
+                $this->singleFileDownloaded($share, $share->getNode());
536
+            }
537
+        }
538
+
539
+        /* FIXME: We should do this all nicely in OCP */
540
+        OC_Util::tearDownFS();
541
+        OC_Util::setupFS($share->getShareOwner());
542
+
543
+        /**
544
+         * this sets a cookie to be able to recognize the start of the download
545
+         * the content must not be longer than 32 characters and must only contain
546
+         * alphanumeric characters
547
+         */
548
+        if (!empty($downloadStartSecret)
549
+            && !isset($downloadStartSecret[32])
550
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
551
+
552
+            // FIXME: set on the response once we use an actual app framework response
553
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
554
+        }
555
+
556
+        $this->emitAccessShareHook($share);
557
+
558
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
559
+
560
+        /**
561
+         * Http range requests support
562
+         */
563
+        if (isset($_SERVER['HTTP_RANGE'])) {
564
+            $server_params['range'] = $this->request->getHeader('Range');
565
+        }
566
+
567
+        // download selected files
568
+        if (!is_null($files) && $files !== '') {
569
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
570
+            // after dispatching the request which results in a "Cannot modify header information" notice.
571
+            OC_Files::get($originalSharePath, $files_list, $server_params);
572
+            exit();
573
+        } else {
574
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
575
+            // after dispatching the request which results in a "Cannot modify header information" notice.
576
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
577
+            exit();
578
+        }
579
+    }
580
+
581
+    /**
582
+     * create activity for every downloaded file
583
+     *
584
+     * @param Share\IShare $share
585
+     * @param array $files_list
586
+     * @param \OCP\Files\Folder $node
587
+     */
588
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
589
+        foreach ($files_list as $file) {
590
+            $subNode = $node->get($file);
591
+            $this->singleFileDownloaded($share, $subNode);
592
+        }
593
+
594
+    }
595
+
596
+    /**
597
+     * create activity if a single file was downloaded from a link share
598
+     *
599
+     * @param Share\IShare $share
600
+     */
601
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
602
+
603
+        $fileId = $node->getId();
604
+
605
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
606
+        $userNodeList = $userFolder->getById($fileId);
607
+        $userNode = $userNodeList[0];
608
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
609
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
610
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
611
+
612
+        $parameters = [$userPath];
613
+
614
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
615
+            if ($node instanceof \OCP\Files\File) {
616
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
617
+            } else {
618
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
619
+            }
620
+            $parameters[] = $share->getSharedWith();
621
+        } else {
622
+            if ($node instanceof \OCP\Files\File) {
623
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
624
+            } else {
625
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
626
+            }
627
+        }
628
+
629
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
630
+
631
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
632
+            $parameters[0] = $ownerPath;
633
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
634
+        }
635
+    }
636
+
637
+    /**
638
+     * publish activity
639
+     *
640
+     * @param string $subject
641
+     * @param array $parameters
642
+     * @param string $affectedUser
643
+     * @param int $fileId
644
+     * @param string $filePath
645
+     */
646
+    protected function publishActivity($subject,
647
+                                        array $parameters,
648
+                                        $affectedUser,
649
+                                        $fileId,
650
+                                        $filePath) {
651
+
652
+        $event = $this->activityManager->generateEvent();
653
+        $event->setApp('files_sharing')
654
+            ->setType('public_links')
655
+            ->setSubject($subject, $parameters)
656
+            ->setAffectedUser($affectedUser)
657
+            ->setObject('files', $fileId, $filePath);
658
+        $this->activityManager->publish($event);
659
+    }
660 660
 
661 661
 
662 662
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -225,7 +225,7 @@
 block discarded – undo
225 225
 	/**
226 226
 	 * creates a array with all user data
227 227
 	 *
228
-	 * @param $userId
228
+	 * @param string $userId
229 229
 	 * @return array
230 230
 	 * @throws OCSException
231 231
 	 */
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@
 block discarded – undo
335 335
 					}
336 336
 					if($quota === 0) {
337 337
 						$quota = 'default';
338
-					}else if($quota === -1) {
338
+					} else if($quota === -1) {
339 339
 						$quota = 'none';
340 340
 					} else {
341 341
 						$quota = \OCP\Util::humanFileSize($quota);
Please login to merge, or discard this patch.
Indentation   +829 added lines, -829 removed lines patch added patch discarded remove patch
@@ -52,833 +52,833 @@
 block discarded – undo
52 52
 
53 53
 class UsersController extends OCSController {
54 54
 
55
-	/** @var IUserManager */
56
-	private $userManager;
57
-	/** @var IConfig */
58
-	private $config;
59
-	/** @var IAppManager */
60
-	private $appManager;
61
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
62
-	private $groupManager;
63
-	/** @var IUserSession */
64
-	private $userSession;
65
-	/** @var AccountManager */
66
-	private $accountManager;
67
-	/** @var ILogger */
68
-	private $logger;
69
-	/** @var IFactory */
70
-	private $l10nFactory;
71
-	/** @var NewUserMailHelper */
72
-	private $newUserMailHelper;
73
-	/** @var FederatedFileSharingFactory */
74
-	private $federatedFileSharingFactory;
75
-
76
-	/**
77
-	 * @param string $appName
78
-	 * @param IRequest $request
79
-	 * @param IUserManager $userManager
80
-	 * @param IConfig $config
81
-	 * @param IAppManager $appManager
82
-	 * @param IGroupManager $groupManager
83
-	 * @param IUserSession $userSession
84
-	 * @param AccountManager $accountManager
85
-	 * @param ILogger $logger
86
-	 * @param IFactory $l10nFactory
87
-	 * @param NewUserMailHelper $newUserMailHelper
88
-	 * @param FederatedFileSharingFactory $federatedFileSharingFactory
89
-	 */
90
-	public function __construct($appName,
91
-								IRequest $request,
92
-								IUserManager $userManager,
93
-								IConfig $config,
94
-								IAppManager $appManager,
95
-								IGroupManager $groupManager,
96
-								IUserSession $userSession,
97
-								AccountManager $accountManager,
98
-								ILogger $logger,
99
-								IFactory $l10nFactory,
100
-								NewUserMailHelper $newUserMailHelper,
101
-								FederatedFileSharingFactory $federatedFileSharingFactory) {
102
-		parent::__construct($appName, $request);
103
-
104
-		$this->userManager = $userManager;
105
-		$this->config = $config;
106
-		$this->appManager = $appManager;
107
-		$this->groupManager = $groupManager;
108
-		$this->userSession = $userSession;
109
-		$this->accountManager = $accountManager;
110
-		$this->logger = $logger;
111
-		$this->l10nFactory = $l10nFactory;
112
-		$this->newUserMailHelper = $newUserMailHelper;
113
-		$this->federatedFileSharingFactory = $federatedFileSharingFactory;
114
-	}
115
-
116
-	/**
117
-	 * @NoAdminRequired
118
-	 *
119
-	 * returns a list of users
120
-	 *
121
-	 * @param string $search
122
-	 * @param int $limit
123
-	 * @param int $offset
124
-	 * @return DataResponse
125
-	 */
126
-	public function getUsers($search = '', $limit = null, $offset = null) {
127
-		$user = $this->userSession->getUser();
128
-		$users = [];
129
-
130
-		// Admin? Or SubAdmin?
131
-		$uid = $user->getUID();
132
-		$subAdminManager = $this->groupManager->getSubAdmin();
133
-		if($this->groupManager->isAdmin($uid)){
134
-			$users = $this->userManager->search($search, $limit, $offset);
135
-		} else if ($subAdminManager->isSubAdmin($user)) {
136
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
137
-			foreach ($subAdminOfGroups as $key => $group) {
138
-				$subAdminOfGroups[$key] = $group->getGID();
139
-			}
140
-
141
-			if($offset === null) {
142
-				$offset = 0;
143
-			}
144
-
145
-			$users = [];
146
-			foreach ($subAdminOfGroups as $group) {
147
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
148
-			}
149
-
150
-			$users = array_slice($users, $offset, $limit);
151
-		}
152
-
153
-		$users = array_keys($users);
154
-
155
-		return new DataResponse([
156
-			'users' => $users
157
-		]);
158
-	}
159
-
160
-	/**
161
-	 * @PasswordConfirmationRequired
162
-	 * @NoAdminRequired
163
-	 *
164
-	 * @param string $userid
165
-	 * @param string $password
166
-	 * @param array $groups
167
-	 * @return DataResponse
168
-	 * @throws OCSException
169
-	 */
170
-	public function addUser($userid, $password, $groups = null) {
171
-		$user = $this->userSession->getUser();
172
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
173
-		$subAdminManager = $this->groupManager->getSubAdmin();
174
-
175
-		if($this->userManager->userExists($userid)) {
176
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
177
-			throw new OCSException('User already exists', 102);
178
-		}
179
-
180
-		if(is_array($groups)) {
181
-			foreach ($groups as $group) {
182
-				if(!$this->groupManager->groupExists($group)) {
183
-					throw new OCSException('group '.$group.' does not exist', 104);
184
-				}
185
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
186
-					throw new OCSException('insufficient privileges for group '. $group, 105);
187
-				}
188
-			}
189
-		} else {
190
-			if(!$isAdmin) {
191
-				throw new OCSException('no group specified (required for subadmins)', 106);
192
-			}
193
-		}
194
-
195
-		try {
196
-			$newUser = $this->userManager->createUser($userid, $password);
197
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
198
-
199
-			if (is_array($groups)) {
200
-				foreach ($groups as $group) {
201
-					$this->groupManager->get($group)->addUser($newUser);
202
-					$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
203
-				}
204
-			}
205
-			return new DataResponse();
206
-		} catch (HintException $e ) {
207
-			$this->logger->logException($e, [
208
-				'message' => 'Failed addUser attempt with hint exception.',
209
-				'level' => \OCP\Util::WARN,
210
-				'app' => 'ocs_api',
211
-			]);
212
-			throw new OCSException($e->getHint(), 107);
213
-		} catch (\Exception $e) {
214
-			$this->logger->logException($e, [
215
-				'message' => 'Failed addUser attempt with exception.',
216
-				'level' => \OCP\Util::ERROR,
217
-				'app' => 'ocs_api',
218
-			]);
219
-			throw new OCSException('Bad request', 101);
220
-		}
221
-	}
222
-
223
-	/**
224
-	 * @NoAdminRequired
225
-	 * @NoSubAdminRequired
226
-	 *
227
-	 * gets user info
228
-	 *
229
-	 * @param string $userId
230
-	 * @return DataResponse
231
-	 * @throws OCSException
232
-	 */
233
-	public function getUser($userId) {
234
-		$data = $this->getUserData($userId);
235
-		return new DataResponse($data);
236
-	}
237
-
238
-	/**
239
-	 * @NoAdminRequired
240
-	 * @NoSubAdminRequired
241
-	 *
242
-	 * gets user info from the currently logged in user
243
-	 *
244
-	 * @return DataResponse
245
-	 * @throws OCSException
246
-	 */
247
-	public function getCurrentUser() {
248
-		$user = $this->userSession->getUser();
249
-		if ($user) {
250
-			$data =  $this->getUserData($user->getUID());
251
-			// rename "displayname" to "display-name" only for this call to keep
252
-			// the API stable.
253
-			$data['display-name'] = $data['displayname'];
254
-			unset($data['displayname']);
255
-			return new DataResponse($data);
256
-
257
-		}
258
-
259
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
260
-	}
261
-
262
-	/**
263
-	 * creates a array with all user data
264
-	 *
265
-	 * @param $userId
266
-	 * @return array
267
-	 * @throws OCSException
268
-	 */
269
-	protected function getUserData($userId) {
270
-		$currentLoggedInUser = $this->userSession->getUser();
271
-
272
-		$data = [];
273
-
274
-		// Check if the target user exists
275
-		$targetUserObject = $this->userManager->get($userId);
276
-		if($targetUserObject === null) {
277
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
278
-		}
279
-
280
-		// Admin? Or SubAdmin?
281
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
282
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
283
-			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
284
-		} else {
285
-			// Check they are looking up themselves
286
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
287
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
288
-			}
289
-		}
290
-
291
-		$userAccount = $this->accountManager->getUser($targetUserObject);
292
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
293
-		$gids = [];
294
-		foreach ($groups as $group) {
295
-			$gids[] = $group->getDisplayName();
296
-		}
297
-
298
-		// Find the data
299
-		$data['id'] = $targetUserObject->getUID();
300
-		$data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
301
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
302
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
303
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
304
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
305
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
306
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
307
-		$data['groups'] = $gids;
308
-		$data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
309
-
310
-		return $data;
311
-	}
312
-
313
-	/**
314
-	 * @NoAdminRequired
315
-	 * @NoSubAdminRequired
316
-	 */
317
-	public function getEditableFields() {
318
-		$permittedFields = [];
319
-
320
-		// Editing self (display, email)
321
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
322
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
323
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
324
-		}
325
-
326
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
327
-			$federatedFileSharing = $this->federatedFileSharingFactory->get();
328
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
329
-			if ($shareProvider->isLookupServerUploadEnabled()) {
330
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
331
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
332
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
333
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
334
-			}
335
-		}
336
-
337
-		return new DataResponse($permittedFields);
338
-	}
339
-
340
-	/**
341
-	 * @NoAdminRequired
342
-	 * @NoSubAdminRequired
343
-	 * @PasswordConfirmationRequired
344
-	 *
345
-	 * edit users
346
-	 *
347
-	 * @param string $userId
348
-	 * @param string $key
349
-	 * @param string $value
350
-	 * @return DataResponse
351
-	 * @throws OCSException
352
-	 * @throws OCSForbiddenException
353
-	 */
354
-	public function editUser($userId, $key, $value) {
355
-		$currentLoggedInUser = $this->userSession->getUser();
356
-
357
-		$targetUser = $this->userManager->get($userId);
358
-		if($targetUser === null) {
359
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
360
-		}
361
-
362
-		$permittedFields = [];
363
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
364
-			// Editing self (display, email)
365
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
366
-				$permittedFields[] = 'display';
367
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
368
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
369
-			}
370
-
371
-			$permittedFields[] = 'password';
372
-			if ($this->config->getSystemValue('force_language', false) === false ||
373
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
374
-				$permittedFields[] = 'language';
375
-			}
376
-
377
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
378
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
379
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
380
-				if ($shareProvider->isLookupServerUploadEnabled()) {
381
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
382
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
383
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
384
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
385
-				}
386
-			}
387
-
388
-			// If admin they can edit their own quota
389
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
390
-				$permittedFields[] = 'quota';
391
-			}
392
-		} else {
393
-			// Check if admin / subadmin
394
-			$subAdminManager = $this->groupManager->getSubAdmin();
395
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
396
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
397
-				// They have permissions over the user
398
-				$permittedFields[] = 'display';
399
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
400
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
401
-				$permittedFields[] = 'password';
402
-				$permittedFields[] = 'language';
403
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
404
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
405
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
406
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
407
-				$permittedFields[] = 'quota';
408
-			} else {
409
-				// No rights
410
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
411
-			}
412
-		}
413
-		// Check if permitted to edit this field
414
-		if(!in_array($key, $permittedFields)) {
415
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
416
-		}
417
-		// Process the edit
418
-		switch($key) {
419
-			case 'display':
420
-			case AccountManager::PROPERTY_DISPLAYNAME:
421
-				$targetUser->setDisplayName($value);
422
-				break;
423
-			case 'quota':
424
-				$quota = $value;
425
-				if($quota !== 'none' && $quota !== 'default') {
426
-					if (is_numeric($quota)) {
427
-						$quota = (float) $quota;
428
-					} else {
429
-						$quota = \OCP\Util::computerFileSize($quota);
430
-					}
431
-					if ($quota === false) {
432
-						throw new OCSException('Invalid quota value '.$value, 103);
433
-					}
434
-					if($quota === 0) {
435
-						$quota = 'default';
436
-					}else if($quota === -1) {
437
-						$quota = 'none';
438
-					} else {
439
-						$quota = \OCP\Util::humanFileSize($quota);
440
-					}
441
-				}
442
-				$targetUser->setQuota($quota);
443
-				break;
444
-			case 'password':
445
-				$targetUser->setPassword($value);
446
-				break;
447
-			case 'language':
448
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
449
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
450
-					throw new OCSException('Invalid language', 102);
451
-				}
452
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
453
-				break;
454
-			case AccountManager::PROPERTY_EMAIL:
455
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
456
-					$targetUser->setEMailAddress($value);
457
-				} else {
458
-					throw new OCSException('', 102);
459
-				}
460
-				break;
461
-			case AccountManager::PROPERTY_PHONE:
462
-			case AccountManager::PROPERTY_ADDRESS:
463
-			case AccountManager::PROPERTY_WEBSITE:
464
-			case AccountManager::PROPERTY_TWITTER:
465
-				$userAccount = $this->accountManager->getUser($targetUser);
466
-				if ($userAccount[$key]['value'] !== $value) {
467
-					$userAccount[$key]['value'] = $value;
468
-					$this->accountManager->updateUser($targetUser, $userAccount);
469
-				}
470
-				break;
471
-			default:
472
-				throw new OCSException('', 103);
473
-		}
474
-		return new DataResponse();
475
-	}
476
-
477
-	/**
478
-	 * @PasswordConfirmationRequired
479
-	 * @NoAdminRequired
480
-	 *
481
-	 * @param string $userId
482
-	 * @return DataResponse
483
-	 * @throws OCSException
484
-	 * @throws OCSForbiddenException
485
-	 */
486
-	public function deleteUser($userId) {
487
-		$currentLoggedInUser = $this->userSession->getUser();
488
-
489
-		$targetUser = $this->userManager->get($userId);
490
-
491
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
492
-			throw new OCSException('', 101);
493
-		}
494
-
495
-		// If not permitted
496
-		$subAdminManager = $this->groupManager->getSubAdmin();
497
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
498
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
499
-		}
500
-
501
-		// Go ahead with the delete
502
-		if($targetUser->delete()) {
503
-			return new DataResponse();
504
-		} else {
505
-			throw new OCSException('', 101);
506
-		}
507
-	}
508
-
509
-	/**
510
-	 * @PasswordConfirmationRequired
511
-	 * @NoAdminRequired
512
-	 *
513
-	 * @param string $userId
514
-	 * @return DataResponse
515
-	 * @throws OCSException
516
-	 * @throws OCSForbiddenException
517
-	 */
518
-	public function disableUser($userId) {
519
-		return $this->setEnabled($userId, false);
520
-	}
521
-
522
-	/**
523
-	 * @PasswordConfirmationRequired
524
-	 * @NoAdminRequired
525
-	 *
526
-	 * @param string $userId
527
-	 * @return DataResponse
528
-	 * @throws OCSException
529
-	 * @throws OCSForbiddenException
530
-	 */
531
-	public function enableUser($userId) {
532
-		return $this->setEnabled($userId, true);
533
-	}
534
-
535
-	/**
536
-	 * @param string $userId
537
-	 * @param bool $value
538
-	 * @return DataResponse
539
-	 * @throws OCSException
540
-	 * @throws OCSForbiddenException
541
-	 */
542
-	private function setEnabled($userId, $value) {
543
-		$currentLoggedInUser = $this->userSession->getUser();
544
-
545
-		$targetUser = $this->userManager->get($userId);
546
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
547
-			throw new OCSException('', 101);
548
-		}
549
-
550
-		// If not permitted
551
-		$subAdminManager = $this->groupManager->getSubAdmin();
552
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
553
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
554
-		}
555
-
556
-		// enable/disable the user now
557
-		$targetUser->setEnabled($value);
558
-		return new DataResponse();
559
-	}
560
-
561
-	/**
562
-	 * @NoAdminRequired
563
-	 * @NoSubAdminRequired
564
-	 *
565
-	 * @param string $userId
566
-	 * @return DataResponse
567
-	 * @throws OCSException
568
-	 */
569
-	public function getUsersGroups($userId) {
570
-		$loggedInUser = $this->userSession->getUser();
571
-
572
-		$targetUser = $this->userManager->get($userId);
573
-		if($targetUser === null) {
574
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
575
-		}
576
-
577
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
578
-			// Self lookup or admin lookup
579
-			return new DataResponse([
580
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
581
-			]);
582
-		} else {
583
-			$subAdminManager = $this->groupManager->getSubAdmin();
584
-
585
-			// Looking up someone else
586
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
587
-				// Return the group that the method caller is subadmin of for the user in question
588
-				/** @var IGroup[] $getSubAdminsGroups */
589
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
590
-				foreach ($getSubAdminsGroups as $key => $group) {
591
-					$getSubAdminsGroups[$key] = $group->getGID();
592
-				}
593
-				$groups = array_intersect(
594
-					$getSubAdminsGroups,
595
-					$this->groupManager->getUserGroupIds($targetUser)
596
-				);
597
-				return new DataResponse(['groups' => $groups]);
598
-			} else {
599
-				// Not permitted
600
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
601
-			}
602
-		}
603
-
604
-	}
605
-
606
-	/**
607
-	 * @PasswordConfirmationRequired
608
-	 * @NoAdminRequired
609
-	 *
610
-	 * @param string $userId
611
-	 * @param string $groupid
612
-	 * @return DataResponse
613
-	 * @throws OCSException
614
-	 */
615
-	public function addToGroup($userId, $groupid = '') {
616
-		if($groupid === '') {
617
-			throw new OCSException('', 101);
618
-		}
619
-
620
-		$group = $this->groupManager->get($groupid);
621
-		$targetUser = $this->userManager->get($userId);
622
-		if($group === null) {
623
-			throw new OCSException('', 102);
624
-		}
625
-		if($targetUser === null) {
626
-			throw new OCSException('', 103);
627
-		}
628
-
629
-		// If they're not an admin, check they are a subadmin of the group in question
630
-		$loggedInUser = $this->userSession->getUser();
631
-		$subAdminManager = $this->groupManager->getSubAdmin();
632
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
633
-			throw new OCSException('', 104);
634
-		}
635
-
636
-		// Add user to group
637
-		$group->addUser($targetUser);
638
-		return new DataResponse();
639
-	}
640
-
641
-	/**
642
-	 * @PasswordConfirmationRequired
643
-	 * @NoAdminRequired
644
-	 *
645
-	 * @param string $userId
646
-	 * @param string $groupid
647
-	 * @return DataResponse
648
-	 * @throws OCSException
649
-	 */
650
-	public function removeFromGroup($userId, $groupid) {
651
-		$loggedInUser = $this->userSession->getUser();
652
-
653
-		if($groupid === null || trim($groupid) === '') {
654
-			throw new OCSException('', 101);
655
-		}
656
-
657
-		$group = $this->groupManager->get($groupid);
658
-		if($group === null) {
659
-			throw new OCSException('', 102);
660
-		}
661
-
662
-		$targetUser = $this->userManager->get($userId);
663
-		if($targetUser === null) {
664
-			throw new OCSException('', 103);
665
-		}
666
-
667
-		// If they're not an admin, check they are a subadmin of the group in question
668
-		$subAdminManager = $this->groupManager->getSubAdmin();
669
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
670
-			throw new OCSException('', 104);
671
-		}
672
-
673
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
674
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
675
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
676
-				if ($group->getGID() === 'admin') {
677
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
678
-				}
679
-			} else {
680
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
681
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
682
-			}
683
-
684
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
685
-			/** @var IGroup[] $subAdminGroups */
686
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
687
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
688
-				return $subAdminGroup->getGID();
689
-			}, $subAdminGroups);
690
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
691
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
692
-
693
-			if (count($userSubAdminGroups) <= 1) {
694
-				// Subadmin must not be able to remove a user from all their subadmin groups.
695
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
696
-			}
697
-		}
698
-
699
-		// Remove user from group
700
-		$group->removeUser($targetUser);
701
-		return new DataResponse();
702
-	}
703
-
704
-	/**
705
-	 * Creates a subadmin
706
-	 *
707
-	 * @PasswordConfirmationRequired
708
-	 *
709
-	 * @param string $userId
710
-	 * @param string $groupid
711
-	 * @return DataResponse
712
-	 * @throws OCSException
713
-	 */
714
-	public function addSubAdmin($userId, $groupid) {
715
-		$group = $this->groupManager->get($groupid);
716
-		$user = $this->userManager->get($userId);
717
-
718
-		// Check if the user exists
719
-		if($user === null) {
720
-			throw new OCSException('User does not exist', 101);
721
-		}
722
-		// Check if group exists
723
-		if($group === null) {
724
-			throw new OCSException('Group does not exist',  102);
725
-		}
726
-		// Check if trying to make subadmin of admin group
727
-		if($group->getGID() === 'admin') {
728
-			throw new OCSException('Cannot create subadmins for admin group', 103);
729
-		}
730
-
731
-		$subAdminManager = $this->groupManager->getSubAdmin();
732
-
733
-		// We cannot be subadmin twice
734
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
735
-			return new DataResponse();
736
-		}
737
-		// Go
738
-		if($subAdminManager->createSubAdmin($user, $group)) {
739
-			return new DataResponse();
740
-		} else {
741
-			throw new OCSException('Unknown error occurred', 103);
742
-		}
743
-	}
744
-
745
-	/**
746
-	 * Removes a subadmin from a group
747
-	 *
748
-	 * @PasswordConfirmationRequired
749
-	 *
750
-	 * @param string $userId
751
-	 * @param string $groupid
752
-	 * @return DataResponse
753
-	 * @throws OCSException
754
-	 */
755
-	public function removeSubAdmin($userId, $groupid) {
756
-		$group = $this->groupManager->get($groupid);
757
-		$user = $this->userManager->get($userId);
758
-		$subAdminManager = $this->groupManager->getSubAdmin();
759
-
760
-		// Check if the user exists
761
-		if($user === null) {
762
-			throw new OCSException('User does not exist', 101);
763
-		}
764
-		// Check if the group exists
765
-		if($group === null) {
766
-			throw new OCSException('Group does not exist', 101);
767
-		}
768
-		// Check if they are a subadmin of this said group
769
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
770
-			throw new OCSException('User is not a subadmin of this group', 102);
771
-		}
772
-
773
-		// Go
774
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
775
-			return new DataResponse();
776
-		} else {
777
-			throw new OCSException('Unknown error occurred', 103);
778
-		}
779
-	}
780
-
781
-	/**
782
-	 * Get the groups a user is a subadmin of
783
-	 *
784
-	 * @param string $userId
785
-	 * @return DataResponse
786
-	 * @throws OCSException
787
-	 */
788
-	public function getUserSubAdminGroups($userId) {
789
-		$user = $this->userManager->get($userId);
790
-		// Check if the user exists
791
-		if($user === null) {
792
-			throw new OCSException('User does not exist', 101);
793
-		}
794
-
795
-		// Get the subadmin groups
796
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
797
-		foreach ($groups as $key => $group) {
798
-			$groups[$key] = $group->getGID();
799
-		}
800
-
801
-		if(!$groups) {
802
-			throw new OCSException('Unknown error occurred', 102);
803
-		} else {
804
-			return new DataResponse($groups);
805
-		}
806
-	}
807
-
808
-	/**
809
-	 * @param string $userId
810
-	 * @return array
811
-	 * @throws \OCP\Files\NotFoundException
812
-	 */
813
-	protected function fillStorageInfo($userId) {
814
-		try {
815
-			\OC_Util::tearDownFS();
816
-			\OC_Util::setupFS($userId);
817
-			$storage = OC_Helper::getStorageInfo('/');
818
-			$data = [
819
-				'free' => $storage['free'],
820
-				'used' => $storage['used'],
821
-				'total' => $storage['total'],
822
-				'relative' => $storage['relative'],
823
-				'quota' => $storage['quota'],
824
-			];
825
-		} catch (NotFoundException $ex) {
826
-			$data = [];
827
-		}
828
-		return $data;
829
-	}
830
-
831
-	/**
832
-	 * @NoAdminRequired
833
-	 * @PasswordConfirmationRequired
834
-	 *
835
-	 * resend welcome message
836
-	 *
837
-	 * @param string $userId
838
-	 * @return DataResponse
839
-	 * @throws OCSException
840
-	 */
841
-	public function resendWelcomeMessage($userId) {
842
-		$currentLoggedInUser = $this->userSession->getUser();
843
-
844
-		$targetUser = $this->userManager->get($userId);
845
-		if($targetUser === null) {
846
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
847
-		}
848
-
849
-		// Check if admin / subadmin
850
-		$subAdminManager = $this->groupManager->getSubAdmin();
851
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
852
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
853
-			// No rights
854
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
855
-		}
856
-
857
-		$email = $targetUser->getEMailAddress();
858
-		if ($email === '' || $email === null) {
859
-			throw new OCSException('Email address not available', 101);
860
-		}
861
-		$username = $targetUser->getUID();
862
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
863
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
864
-			$lang = 'en';
865
-		}
866
-
867
-		$l10n = $this->l10nFactory->get('settings', $lang);
868
-
869
-		try {
870
-			$this->newUserMailHelper->setL10N($l10n);
871
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
872
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
873
-		} catch(\Exception $e) {
874
-			$this->logger->logException($e, [
875
-				'message' => "Can't send new user mail to $email",
876
-				'level' => \OCP\Util::ERROR,
877
-				'app' => 'settings',
878
-			]);
879
-			throw new OCSException('Sending email failed', 102);
880
-		}
881
-
882
-		return new DataResponse();
883
-	}
55
+    /** @var IUserManager */
56
+    private $userManager;
57
+    /** @var IConfig */
58
+    private $config;
59
+    /** @var IAppManager */
60
+    private $appManager;
61
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
62
+    private $groupManager;
63
+    /** @var IUserSession */
64
+    private $userSession;
65
+    /** @var AccountManager */
66
+    private $accountManager;
67
+    /** @var ILogger */
68
+    private $logger;
69
+    /** @var IFactory */
70
+    private $l10nFactory;
71
+    /** @var NewUserMailHelper */
72
+    private $newUserMailHelper;
73
+    /** @var FederatedFileSharingFactory */
74
+    private $federatedFileSharingFactory;
75
+
76
+    /**
77
+     * @param string $appName
78
+     * @param IRequest $request
79
+     * @param IUserManager $userManager
80
+     * @param IConfig $config
81
+     * @param IAppManager $appManager
82
+     * @param IGroupManager $groupManager
83
+     * @param IUserSession $userSession
84
+     * @param AccountManager $accountManager
85
+     * @param ILogger $logger
86
+     * @param IFactory $l10nFactory
87
+     * @param NewUserMailHelper $newUserMailHelper
88
+     * @param FederatedFileSharingFactory $federatedFileSharingFactory
89
+     */
90
+    public function __construct($appName,
91
+                                IRequest $request,
92
+                                IUserManager $userManager,
93
+                                IConfig $config,
94
+                                IAppManager $appManager,
95
+                                IGroupManager $groupManager,
96
+                                IUserSession $userSession,
97
+                                AccountManager $accountManager,
98
+                                ILogger $logger,
99
+                                IFactory $l10nFactory,
100
+                                NewUserMailHelper $newUserMailHelper,
101
+                                FederatedFileSharingFactory $federatedFileSharingFactory) {
102
+        parent::__construct($appName, $request);
103
+
104
+        $this->userManager = $userManager;
105
+        $this->config = $config;
106
+        $this->appManager = $appManager;
107
+        $this->groupManager = $groupManager;
108
+        $this->userSession = $userSession;
109
+        $this->accountManager = $accountManager;
110
+        $this->logger = $logger;
111
+        $this->l10nFactory = $l10nFactory;
112
+        $this->newUserMailHelper = $newUserMailHelper;
113
+        $this->federatedFileSharingFactory = $federatedFileSharingFactory;
114
+    }
115
+
116
+    /**
117
+     * @NoAdminRequired
118
+     *
119
+     * returns a list of users
120
+     *
121
+     * @param string $search
122
+     * @param int $limit
123
+     * @param int $offset
124
+     * @return DataResponse
125
+     */
126
+    public function getUsers($search = '', $limit = null, $offset = null) {
127
+        $user = $this->userSession->getUser();
128
+        $users = [];
129
+
130
+        // Admin? Or SubAdmin?
131
+        $uid = $user->getUID();
132
+        $subAdminManager = $this->groupManager->getSubAdmin();
133
+        if($this->groupManager->isAdmin($uid)){
134
+            $users = $this->userManager->search($search, $limit, $offset);
135
+        } else if ($subAdminManager->isSubAdmin($user)) {
136
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
137
+            foreach ($subAdminOfGroups as $key => $group) {
138
+                $subAdminOfGroups[$key] = $group->getGID();
139
+            }
140
+
141
+            if($offset === null) {
142
+                $offset = 0;
143
+            }
144
+
145
+            $users = [];
146
+            foreach ($subAdminOfGroups as $group) {
147
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
148
+            }
149
+
150
+            $users = array_slice($users, $offset, $limit);
151
+        }
152
+
153
+        $users = array_keys($users);
154
+
155
+        return new DataResponse([
156
+            'users' => $users
157
+        ]);
158
+    }
159
+
160
+    /**
161
+     * @PasswordConfirmationRequired
162
+     * @NoAdminRequired
163
+     *
164
+     * @param string $userid
165
+     * @param string $password
166
+     * @param array $groups
167
+     * @return DataResponse
168
+     * @throws OCSException
169
+     */
170
+    public function addUser($userid, $password, $groups = null) {
171
+        $user = $this->userSession->getUser();
172
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
173
+        $subAdminManager = $this->groupManager->getSubAdmin();
174
+
175
+        if($this->userManager->userExists($userid)) {
176
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
177
+            throw new OCSException('User already exists', 102);
178
+        }
179
+
180
+        if(is_array($groups)) {
181
+            foreach ($groups as $group) {
182
+                if(!$this->groupManager->groupExists($group)) {
183
+                    throw new OCSException('group '.$group.' does not exist', 104);
184
+                }
185
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
186
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
187
+                }
188
+            }
189
+        } else {
190
+            if(!$isAdmin) {
191
+                throw new OCSException('no group specified (required for subadmins)', 106);
192
+            }
193
+        }
194
+
195
+        try {
196
+            $newUser = $this->userManager->createUser($userid, $password);
197
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
198
+
199
+            if (is_array($groups)) {
200
+                foreach ($groups as $group) {
201
+                    $this->groupManager->get($group)->addUser($newUser);
202
+                    $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
203
+                }
204
+            }
205
+            return new DataResponse();
206
+        } catch (HintException $e ) {
207
+            $this->logger->logException($e, [
208
+                'message' => 'Failed addUser attempt with hint exception.',
209
+                'level' => \OCP\Util::WARN,
210
+                'app' => 'ocs_api',
211
+            ]);
212
+            throw new OCSException($e->getHint(), 107);
213
+        } catch (\Exception $e) {
214
+            $this->logger->logException($e, [
215
+                'message' => 'Failed addUser attempt with exception.',
216
+                'level' => \OCP\Util::ERROR,
217
+                'app' => 'ocs_api',
218
+            ]);
219
+            throw new OCSException('Bad request', 101);
220
+        }
221
+    }
222
+
223
+    /**
224
+     * @NoAdminRequired
225
+     * @NoSubAdminRequired
226
+     *
227
+     * gets user info
228
+     *
229
+     * @param string $userId
230
+     * @return DataResponse
231
+     * @throws OCSException
232
+     */
233
+    public function getUser($userId) {
234
+        $data = $this->getUserData($userId);
235
+        return new DataResponse($data);
236
+    }
237
+
238
+    /**
239
+     * @NoAdminRequired
240
+     * @NoSubAdminRequired
241
+     *
242
+     * gets user info from the currently logged in user
243
+     *
244
+     * @return DataResponse
245
+     * @throws OCSException
246
+     */
247
+    public function getCurrentUser() {
248
+        $user = $this->userSession->getUser();
249
+        if ($user) {
250
+            $data =  $this->getUserData($user->getUID());
251
+            // rename "displayname" to "display-name" only for this call to keep
252
+            // the API stable.
253
+            $data['display-name'] = $data['displayname'];
254
+            unset($data['displayname']);
255
+            return new DataResponse($data);
256
+
257
+        }
258
+
259
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
260
+    }
261
+
262
+    /**
263
+     * creates a array with all user data
264
+     *
265
+     * @param $userId
266
+     * @return array
267
+     * @throws OCSException
268
+     */
269
+    protected function getUserData($userId) {
270
+        $currentLoggedInUser = $this->userSession->getUser();
271
+
272
+        $data = [];
273
+
274
+        // Check if the target user exists
275
+        $targetUserObject = $this->userManager->get($userId);
276
+        if($targetUserObject === null) {
277
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
278
+        }
279
+
280
+        // Admin? Or SubAdmin?
281
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
282
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
283
+            $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
284
+        } else {
285
+            // Check they are looking up themselves
286
+            if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
287
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
288
+            }
289
+        }
290
+
291
+        $userAccount = $this->accountManager->getUser($targetUserObject);
292
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
293
+        $gids = [];
294
+        foreach ($groups as $group) {
295
+            $gids[] = $group->getDisplayName();
296
+        }
297
+
298
+        // Find the data
299
+        $data['id'] = $targetUserObject->getUID();
300
+        $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
301
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
302
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
303
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
304
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
305
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
306
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
307
+        $data['groups'] = $gids;
308
+        $data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
309
+
310
+        return $data;
311
+    }
312
+
313
+    /**
314
+     * @NoAdminRequired
315
+     * @NoSubAdminRequired
316
+     */
317
+    public function getEditableFields() {
318
+        $permittedFields = [];
319
+
320
+        // Editing self (display, email)
321
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
322
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
323
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
324
+        }
325
+
326
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
327
+            $federatedFileSharing = $this->federatedFileSharingFactory->get();
328
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
329
+            if ($shareProvider->isLookupServerUploadEnabled()) {
330
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
331
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
332
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
333
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
334
+            }
335
+        }
336
+
337
+        return new DataResponse($permittedFields);
338
+    }
339
+
340
+    /**
341
+     * @NoAdminRequired
342
+     * @NoSubAdminRequired
343
+     * @PasswordConfirmationRequired
344
+     *
345
+     * edit users
346
+     *
347
+     * @param string $userId
348
+     * @param string $key
349
+     * @param string $value
350
+     * @return DataResponse
351
+     * @throws OCSException
352
+     * @throws OCSForbiddenException
353
+     */
354
+    public function editUser($userId, $key, $value) {
355
+        $currentLoggedInUser = $this->userSession->getUser();
356
+
357
+        $targetUser = $this->userManager->get($userId);
358
+        if($targetUser === null) {
359
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
360
+        }
361
+
362
+        $permittedFields = [];
363
+        if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
364
+            // Editing self (display, email)
365
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
366
+                $permittedFields[] = 'display';
367
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
368
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
369
+            }
370
+
371
+            $permittedFields[] = 'password';
372
+            if ($this->config->getSystemValue('force_language', false) === false ||
373
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
374
+                $permittedFields[] = 'language';
375
+            }
376
+
377
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
378
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
379
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
380
+                if ($shareProvider->isLookupServerUploadEnabled()) {
381
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
382
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
383
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
384
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
385
+                }
386
+            }
387
+
388
+            // If admin they can edit their own quota
389
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
390
+                $permittedFields[] = 'quota';
391
+            }
392
+        } else {
393
+            // Check if admin / subadmin
394
+            $subAdminManager = $this->groupManager->getSubAdmin();
395
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
396
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
397
+                // They have permissions over the user
398
+                $permittedFields[] = 'display';
399
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
400
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
401
+                $permittedFields[] = 'password';
402
+                $permittedFields[] = 'language';
403
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
404
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
405
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
406
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
407
+                $permittedFields[] = 'quota';
408
+            } else {
409
+                // No rights
410
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
411
+            }
412
+        }
413
+        // Check if permitted to edit this field
414
+        if(!in_array($key, $permittedFields)) {
415
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
416
+        }
417
+        // Process the edit
418
+        switch($key) {
419
+            case 'display':
420
+            case AccountManager::PROPERTY_DISPLAYNAME:
421
+                $targetUser->setDisplayName($value);
422
+                break;
423
+            case 'quota':
424
+                $quota = $value;
425
+                if($quota !== 'none' && $quota !== 'default') {
426
+                    if (is_numeric($quota)) {
427
+                        $quota = (float) $quota;
428
+                    } else {
429
+                        $quota = \OCP\Util::computerFileSize($quota);
430
+                    }
431
+                    if ($quota === false) {
432
+                        throw new OCSException('Invalid quota value '.$value, 103);
433
+                    }
434
+                    if($quota === 0) {
435
+                        $quota = 'default';
436
+                    }else if($quota === -1) {
437
+                        $quota = 'none';
438
+                    } else {
439
+                        $quota = \OCP\Util::humanFileSize($quota);
440
+                    }
441
+                }
442
+                $targetUser->setQuota($quota);
443
+                break;
444
+            case 'password':
445
+                $targetUser->setPassword($value);
446
+                break;
447
+            case 'language':
448
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
449
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
450
+                    throw new OCSException('Invalid language', 102);
451
+                }
452
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
453
+                break;
454
+            case AccountManager::PROPERTY_EMAIL:
455
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
456
+                    $targetUser->setEMailAddress($value);
457
+                } else {
458
+                    throw new OCSException('', 102);
459
+                }
460
+                break;
461
+            case AccountManager::PROPERTY_PHONE:
462
+            case AccountManager::PROPERTY_ADDRESS:
463
+            case AccountManager::PROPERTY_WEBSITE:
464
+            case AccountManager::PROPERTY_TWITTER:
465
+                $userAccount = $this->accountManager->getUser($targetUser);
466
+                if ($userAccount[$key]['value'] !== $value) {
467
+                    $userAccount[$key]['value'] = $value;
468
+                    $this->accountManager->updateUser($targetUser, $userAccount);
469
+                }
470
+                break;
471
+            default:
472
+                throw new OCSException('', 103);
473
+        }
474
+        return new DataResponse();
475
+    }
476
+
477
+    /**
478
+     * @PasswordConfirmationRequired
479
+     * @NoAdminRequired
480
+     *
481
+     * @param string $userId
482
+     * @return DataResponse
483
+     * @throws OCSException
484
+     * @throws OCSForbiddenException
485
+     */
486
+    public function deleteUser($userId) {
487
+        $currentLoggedInUser = $this->userSession->getUser();
488
+
489
+        $targetUser = $this->userManager->get($userId);
490
+
491
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
492
+            throw new OCSException('', 101);
493
+        }
494
+
495
+        // If not permitted
496
+        $subAdminManager = $this->groupManager->getSubAdmin();
497
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
498
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
499
+        }
500
+
501
+        // Go ahead with the delete
502
+        if($targetUser->delete()) {
503
+            return new DataResponse();
504
+        } else {
505
+            throw new OCSException('', 101);
506
+        }
507
+    }
508
+
509
+    /**
510
+     * @PasswordConfirmationRequired
511
+     * @NoAdminRequired
512
+     *
513
+     * @param string $userId
514
+     * @return DataResponse
515
+     * @throws OCSException
516
+     * @throws OCSForbiddenException
517
+     */
518
+    public function disableUser($userId) {
519
+        return $this->setEnabled($userId, false);
520
+    }
521
+
522
+    /**
523
+     * @PasswordConfirmationRequired
524
+     * @NoAdminRequired
525
+     *
526
+     * @param string $userId
527
+     * @return DataResponse
528
+     * @throws OCSException
529
+     * @throws OCSForbiddenException
530
+     */
531
+    public function enableUser($userId) {
532
+        return $this->setEnabled($userId, true);
533
+    }
534
+
535
+    /**
536
+     * @param string $userId
537
+     * @param bool $value
538
+     * @return DataResponse
539
+     * @throws OCSException
540
+     * @throws OCSForbiddenException
541
+     */
542
+    private function setEnabled($userId, $value) {
543
+        $currentLoggedInUser = $this->userSession->getUser();
544
+
545
+        $targetUser = $this->userManager->get($userId);
546
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
547
+            throw new OCSException('', 101);
548
+        }
549
+
550
+        // If not permitted
551
+        $subAdminManager = $this->groupManager->getSubAdmin();
552
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
553
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
554
+        }
555
+
556
+        // enable/disable the user now
557
+        $targetUser->setEnabled($value);
558
+        return new DataResponse();
559
+    }
560
+
561
+    /**
562
+     * @NoAdminRequired
563
+     * @NoSubAdminRequired
564
+     *
565
+     * @param string $userId
566
+     * @return DataResponse
567
+     * @throws OCSException
568
+     */
569
+    public function getUsersGroups($userId) {
570
+        $loggedInUser = $this->userSession->getUser();
571
+
572
+        $targetUser = $this->userManager->get($userId);
573
+        if($targetUser === null) {
574
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
575
+        }
576
+
577
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
578
+            // Self lookup or admin lookup
579
+            return new DataResponse([
580
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
581
+            ]);
582
+        } else {
583
+            $subAdminManager = $this->groupManager->getSubAdmin();
584
+
585
+            // Looking up someone else
586
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
587
+                // Return the group that the method caller is subadmin of for the user in question
588
+                /** @var IGroup[] $getSubAdminsGroups */
589
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
590
+                foreach ($getSubAdminsGroups as $key => $group) {
591
+                    $getSubAdminsGroups[$key] = $group->getGID();
592
+                }
593
+                $groups = array_intersect(
594
+                    $getSubAdminsGroups,
595
+                    $this->groupManager->getUserGroupIds($targetUser)
596
+                );
597
+                return new DataResponse(['groups' => $groups]);
598
+            } else {
599
+                // Not permitted
600
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
601
+            }
602
+        }
603
+
604
+    }
605
+
606
+    /**
607
+     * @PasswordConfirmationRequired
608
+     * @NoAdminRequired
609
+     *
610
+     * @param string $userId
611
+     * @param string $groupid
612
+     * @return DataResponse
613
+     * @throws OCSException
614
+     */
615
+    public function addToGroup($userId, $groupid = '') {
616
+        if($groupid === '') {
617
+            throw new OCSException('', 101);
618
+        }
619
+
620
+        $group = $this->groupManager->get($groupid);
621
+        $targetUser = $this->userManager->get($userId);
622
+        if($group === null) {
623
+            throw new OCSException('', 102);
624
+        }
625
+        if($targetUser === null) {
626
+            throw new OCSException('', 103);
627
+        }
628
+
629
+        // If they're not an admin, check they are a subadmin of the group in question
630
+        $loggedInUser = $this->userSession->getUser();
631
+        $subAdminManager = $this->groupManager->getSubAdmin();
632
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
633
+            throw new OCSException('', 104);
634
+        }
635
+
636
+        // Add user to group
637
+        $group->addUser($targetUser);
638
+        return new DataResponse();
639
+    }
640
+
641
+    /**
642
+     * @PasswordConfirmationRequired
643
+     * @NoAdminRequired
644
+     *
645
+     * @param string $userId
646
+     * @param string $groupid
647
+     * @return DataResponse
648
+     * @throws OCSException
649
+     */
650
+    public function removeFromGroup($userId, $groupid) {
651
+        $loggedInUser = $this->userSession->getUser();
652
+
653
+        if($groupid === null || trim($groupid) === '') {
654
+            throw new OCSException('', 101);
655
+        }
656
+
657
+        $group = $this->groupManager->get($groupid);
658
+        if($group === null) {
659
+            throw new OCSException('', 102);
660
+        }
661
+
662
+        $targetUser = $this->userManager->get($userId);
663
+        if($targetUser === null) {
664
+            throw new OCSException('', 103);
665
+        }
666
+
667
+        // If they're not an admin, check they are a subadmin of the group in question
668
+        $subAdminManager = $this->groupManager->getSubAdmin();
669
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
670
+            throw new OCSException('', 104);
671
+        }
672
+
673
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
674
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
675
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
676
+                if ($group->getGID() === 'admin') {
677
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
678
+                }
679
+            } else {
680
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
681
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
682
+            }
683
+
684
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
685
+            /** @var IGroup[] $subAdminGroups */
686
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
687
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
688
+                return $subAdminGroup->getGID();
689
+            }, $subAdminGroups);
690
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
691
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
692
+
693
+            if (count($userSubAdminGroups) <= 1) {
694
+                // Subadmin must not be able to remove a user from all their subadmin groups.
695
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
696
+            }
697
+        }
698
+
699
+        // Remove user from group
700
+        $group->removeUser($targetUser);
701
+        return new DataResponse();
702
+    }
703
+
704
+    /**
705
+     * Creates a subadmin
706
+     *
707
+     * @PasswordConfirmationRequired
708
+     *
709
+     * @param string $userId
710
+     * @param string $groupid
711
+     * @return DataResponse
712
+     * @throws OCSException
713
+     */
714
+    public function addSubAdmin($userId, $groupid) {
715
+        $group = $this->groupManager->get($groupid);
716
+        $user = $this->userManager->get($userId);
717
+
718
+        // Check if the user exists
719
+        if($user === null) {
720
+            throw new OCSException('User does not exist', 101);
721
+        }
722
+        // Check if group exists
723
+        if($group === null) {
724
+            throw new OCSException('Group does not exist',  102);
725
+        }
726
+        // Check if trying to make subadmin of admin group
727
+        if($group->getGID() === 'admin') {
728
+            throw new OCSException('Cannot create subadmins for admin group', 103);
729
+        }
730
+
731
+        $subAdminManager = $this->groupManager->getSubAdmin();
732
+
733
+        // We cannot be subadmin twice
734
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
735
+            return new DataResponse();
736
+        }
737
+        // Go
738
+        if($subAdminManager->createSubAdmin($user, $group)) {
739
+            return new DataResponse();
740
+        } else {
741
+            throw new OCSException('Unknown error occurred', 103);
742
+        }
743
+    }
744
+
745
+    /**
746
+     * Removes a subadmin from a group
747
+     *
748
+     * @PasswordConfirmationRequired
749
+     *
750
+     * @param string $userId
751
+     * @param string $groupid
752
+     * @return DataResponse
753
+     * @throws OCSException
754
+     */
755
+    public function removeSubAdmin($userId, $groupid) {
756
+        $group = $this->groupManager->get($groupid);
757
+        $user = $this->userManager->get($userId);
758
+        $subAdminManager = $this->groupManager->getSubAdmin();
759
+
760
+        // Check if the user exists
761
+        if($user === null) {
762
+            throw new OCSException('User does not exist', 101);
763
+        }
764
+        // Check if the group exists
765
+        if($group === null) {
766
+            throw new OCSException('Group does not exist', 101);
767
+        }
768
+        // Check if they are a subadmin of this said group
769
+        if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
770
+            throw new OCSException('User is not a subadmin of this group', 102);
771
+        }
772
+
773
+        // Go
774
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
775
+            return new DataResponse();
776
+        } else {
777
+            throw new OCSException('Unknown error occurred', 103);
778
+        }
779
+    }
780
+
781
+    /**
782
+     * Get the groups a user is a subadmin of
783
+     *
784
+     * @param string $userId
785
+     * @return DataResponse
786
+     * @throws OCSException
787
+     */
788
+    public function getUserSubAdminGroups($userId) {
789
+        $user = $this->userManager->get($userId);
790
+        // Check if the user exists
791
+        if($user === null) {
792
+            throw new OCSException('User does not exist', 101);
793
+        }
794
+
795
+        // Get the subadmin groups
796
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
797
+        foreach ($groups as $key => $group) {
798
+            $groups[$key] = $group->getGID();
799
+        }
800
+
801
+        if(!$groups) {
802
+            throw new OCSException('Unknown error occurred', 102);
803
+        } else {
804
+            return new DataResponse($groups);
805
+        }
806
+    }
807
+
808
+    /**
809
+     * @param string $userId
810
+     * @return array
811
+     * @throws \OCP\Files\NotFoundException
812
+     */
813
+    protected function fillStorageInfo($userId) {
814
+        try {
815
+            \OC_Util::tearDownFS();
816
+            \OC_Util::setupFS($userId);
817
+            $storage = OC_Helper::getStorageInfo('/');
818
+            $data = [
819
+                'free' => $storage['free'],
820
+                'used' => $storage['used'],
821
+                'total' => $storage['total'],
822
+                'relative' => $storage['relative'],
823
+                'quota' => $storage['quota'],
824
+            ];
825
+        } catch (NotFoundException $ex) {
826
+            $data = [];
827
+        }
828
+        return $data;
829
+    }
830
+
831
+    /**
832
+     * @NoAdminRequired
833
+     * @PasswordConfirmationRequired
834
+     *
835
+     * resend welcome message
836
+     *
837
+     * @param string $userId
838
+     * @return DataResponse
839
+     * @throws OCSException
840
+     */
841
+    public function resendWelcomeMessage($userId) {
842
+        $currentLoggedInUser = $this->userSession->getUser();
843
+
844
+        $targetUser = $this->userManager->get($userId);
845
+        if($targetUser === null) {
846
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
847
+        }
848
+
849
+        // Check if admin / subadmin
850
+        $subAdminManager = $this->groupManager->getSubAdmin();
851
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
852
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
853
+            // No rights
854
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
855
+        }
856
+
857
+        $email = $targetUser->getEMailAddress();
858
+        if ($email === '' || $email === null) {
859
+            throw new OCSException('Email address not available', 101);
860
+        }
861
+        $username = $targetUser->getUID();
862
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
863
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
864
+            $lang = 'en';
865
+        }
866
+
867
+        $l10n = $this->l10nFactory->get('settings', $lang);
868
+
869
+        try {
870
+            $this->newUserMailHelper->setL10N($l10n);
871
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
872
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
873
+        } catch(\Exception $e) {
874
+            $this->logger->logException($e, [
875
+                'message' => "Can't send new user mail to $email",
876
+                'level' => \OCP\Util::ERROR,
877
+                'app' => 'settings',
878
+            ]);
879
+            throw new OCSException('Sending email failed', 102);
880
+        }
881
+
882
+        return new DataResponse();
883
+    }
884 884
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 		// Admin? Or SubAdmin?
131 131
 		$uid = $user->getUID();
132 132
 		$subAdminManager = $this->groupManager->getSubAdmin();
133
-		if($this->groupManager->isAdmin($uid)){
133
+		if ($this->groupManager->isAdmin($uid)) {
134 134
 			$users = $this->userManager->search($search, $limit, $offset);
135 135
 		} else if ($subAdminManager->isSubAdmin($user)) {
136 136
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 				$subAdminOfGroups[$key] = $group->getGID();
139 139
 			}
140 140
 
141
-			if($offset === null) {
141
+			if ($offset === null) {
142 142
 				$offset = 0;
143 143
 			}
144 144
 
@@ -172,38 +172,38 @@  discard block
 block discarded – undo
172 172
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
173 173
 		$subAdminManager = $this->groupManager->getSubAdmin();
174 174
 
175
-		if($this->userManager->userExists($userid)) {
175
+		if ($this->userManager->userExists($userid)) {
176 176
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
177 177
 			throw new OCSException('User already exists', 102);
178 178
 		}
179 179
 
180
-		if(is_array($groups)) {
180
+		if (is_array($groups)) {
181 181
 			foreach ($groups as $group) {
182
-				if(!$this->groupManager->groupExists($group)) {
182
+				if (!$this->groupManager->groupExists($group)) {
183 183
 					throw new OCSException('group '.$group.' does not exist', 104);
184 184
 				}
185
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
186
-					throw new OCSException('insufficient privileges for group '. $group, 105);
185
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
186
+					throw new OCSException('insufficient privileges for group '.$group, 105);
187 187
 				}
188 188
 			}
189 189
 		} else {
190
-			if(!$isAdmin) {
190
+			if (!$isAdmin) {
191 191
 				throw new OCSException('no group specified (required for subadmins)', 106);
192 192
 			}
193 193
 		}
194 194
 
195 195
 		try {
196 196
 			$newUser = $this->userManager->createUser($userid, $password);
197
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
197
+			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
198 198
 
199 199
 			if (is_array($groups)) {
200 200
 				foreach ($groups as $group) {
201 201
 					$this->groupManager->get($group)->addUser($newUser);
202
-					$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
202
+					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
203 203
 				}
204 204
 			}
205 205
 			return new DataResponse();
206
-		} catch (HintException $e ) {
206
+		} catch (HintException $e) {
207 207
 			$this->logger->logException($e, [
208 208
 				'message' => 'Failed addUser attempt with hint exception.',
209 209
 				'level' => \OCP\Util::WARN,
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 	public function getCurrentUser() {
248 248
 		$user = $this->userSession->getUser();
249 249
 		if ($user) {
250
-			$data =  $this->getUserData($user->getUID());
250
+			$data = $this->getUserData($user->getUID());
251 251
 			// rename "displayname" to "display-name" only for this call to keep
252 252
 			// the API stable.
253 253
 			$data['display-name'] = $data['displayname'];
@@ -273,17 +273,17 @@  discard block
 block discarded – undo
273 273
 
274 274
 		// Check if the target user exists
275 275
 		$targetUserObject = $this->userManager->get($userId);
276
-		if($targetUserObject === null) {
276
+		if ($targetUserObject === null) {
277 277
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
278 278
 		}
279 279
 
280 280
 		// Admin? Or SubAdmin?
281
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
281
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
282 282
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
283 283
 			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
284 284
 		} else {
285 285
 			// Check they are looking up themselves
286
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
286
+			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
287 287
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
288 288
 			}
289 289
 		}
@@ -355,12 +355,12 @@  discard block
 block discarded – undo
355 355
 		$currentLoggedInUser = $this->userSession->getUser();
356 356
 
357 357
 		$targetUser = $this->userManager->get($userId);
358
-		if($targetUser === null) {
358
+		if ($targetUser === null) {
359 359
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
360 360
 		}
361 361
 
362 362
 		$permittedFields = [];
363
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
363
+		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
364 364
 			// Editing self (display, email)
365 365
 			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
366 366
 				$permittedFields[] = 'display';
@@ -386,13 +386,13 @@  discard block
 block discarded – undo
386 386
 			}
387 387
 
388 388
 			// If admin they can edit their own quota
389
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
389
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
390 390
 				$permittedFields[] = 'quota';
391 391
 			}
392 392
 		} else {
393 393
 			// Check if admin / subadmin
394 394
 			$subAdminManager = $this->groupManager->getSubAdmin();
395
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
395
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
396 396
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
397 397
 				// They have permissions over the user
398 398
 				$permittedFields[] = 'display';
@@ -411,18 +411,18 @@  discard block
 block discarded – undo
411 411
 			}
412 412
 		}
413 413
 		// Check if permitted to edit this field
414
-		if(!in_array($key, $permittedFields)) {
414
+		if (!in_array($key, $permittedFields)) {
415 415
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
416 416
 		}
417 417
 		// Process the edit
418
-		switch($key) {
418
+		switch ($key) {
419 419
 			case 'display':
420 420
 			case AccountManager::PROPERTY_DISPLAYNAME:
421 421
 				$targetUser->setDisplayName($value);
422 422
 				break;
423 423
 			case 'quota':
424 424
 				$quota = $value;
425
-				if($quota !== 'none' && $quota !== 'default') {
425
+				if ($quota !== 'none' && $quota !== 'default') {
426 426
 					if (is_numeric($quota)) {
427 427
 						$quota = (float) $quota;
428 428
 					} else {
@@ -431,9 +431,9 @@  discard block
 block discarded – undo
431 431
 					if ($quota === false) {
432 432
 						throw new OCSException('Invalid quota value '.$value, 103);
433 433
 					}
434
-					if($quota === 0) {
434
+					if ($quota === 0) {
435 435
 						$quota = 'default';
436
-					}else if($quota === -1) {
436
+					} else if ($quota === -1) {
437 437
 						$quota = 'none';
438 438
 					} else {
439 439
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
453 453
 				break;
454 454
 			case AccountManager::PROPERTY_EMAIL:
455
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
455
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
456 456
 					$targetUser->setEMailAddress($value);
457 457
 				} else {
458 458
 					throw new OCSException('', 102);
@@ -488,18 +488,18 @@  discard block
 block discarded – undo
488 488
 
489 489
 		$targetUser = $this->userManager->get($userId);
490 490
 
491
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
491
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
492 492
 			throw new OCSException('', 101);
493 493
 		}
494 494
 
495 495
 		// If not permitted
496 496
 		$subAdminManager = $this->groupManager->getSubAdmin();
497
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
497
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
498 498
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
499 499
 		}
500 500
 
501 501
 		// Go ahead with the delete
502
-		if($targetUser->delete()) {
502
+		if ($targetUser->delete()) {
503 503
 			return new DataResponse();
504 504
 		} else {
505 505
 			throw new OCSException('', 101);
@@ -543,13 +543,13 @@  discard block
 block discarded – undo
543 543
 		$currentLoggedInUser = $this->userSession->getUser();
544 544
 
545 545
 		$targetUser = $this->userManager->get($userId);
546
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
546
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
547 547
 			throw new OCSException('', 101);
548 548
 		}
549 549
 
550 550
 		// If not permitted
551 551
 		$subAdminManager = $this->groupManager->getSubAdmin();
552
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
552
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
553 553
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
554 554
 		}
555 555
 
@@ -570,11 +570,11 @@  discard block
 block discarded – undo
570 570
 		$loggedInUser = $this->userSession->getUser();
571 571
 
572 572
 		$targetUser = $this->userManager->get($userId);
573
-		if($targetUser === null) {
573
+		if ($targetUser === null) {
574 574
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
575 575
 		}
576 576
 
577
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
577
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
578 578
 			// Self lookup or admin lookup
579 579
 			return new DataResponse([
580 580
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 			$subAdminManager = $this->groupManager->getSubAdmin();
584 584
 
585 585
 			// Looking up someone else
586
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
586
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
587 587
 				// Return the group that the method caller is subadmin of for the user in question
588 588
 				/** @var IGroup[] $getSubAdminsGroups */
589 589
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -613,16 +613,16 @@  discard block
 block discarded – undo
613 613
 	 * @throws OCSException
614 614
 	 */
615 615
 	public function addToGroup($userId, $groupid = '') {
616
-		if($groupid === '') {
616
+		if ($groupid === '') {
617 617
 			throw new OCSException('', 101);
618 618
 		}
619 619
 
620 620
 		$group = $this->groupManager->get($groupid);
621 621
 		$targetUser = $this->userManager->get($userId);
622
-		if($group === null) {
622
+		if ($group === null) {
623 623
 			throw new OCSException('', 102);
624 624
 		}
625
-		if($targetUser === null) {
625
+		if ($targetUser === null) {
626 626
 			throw new OCSException('', 103);
627 627
 		}
628 628
 
@@ -650,17 +650,17 @@  discard block
 block discarded – undo
650 650
 	public function removeFromGroup($userId, $groupid) {
651 651
 		$loggedInUser = $this->userSession->getUser();
652 652
 
653
-		if($groupid === null || trim($groupid) === '') {
653
+		if ($groupid === null || trim($groupid) === '') {
654 654
 			throw new OCSException('', 101);
655 655
 		}
656 656
 
657 657
 		$group = $this->groupManager->get($groupid);
658
-		if($group === null) {
658
+		if ($group === null) {
659 659
 			throw new OCSException('', 102);
660 660
 		}
661 661
 
662 662
 		$targetUser = $this->userManager->get($userId);
663
-		if($targetUser === null) {
663
+		if ($targetUser === null) {
664 664
 			throw new OCSException('', 103);
665 665
 		}
666 666
 
@@ -684,7 +684,7 @@  discard block
 block discarded – undo
684 684
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
685 685
 			/** @var IGroup[] $subAdminGroups */
686 686
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
687
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
687
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
688 688
 				return $subAdminGroup->getGID();
689 689
 			}, $subAdminGroups);
690 690
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -716,15 +716,15 @@  discard block
 block discarded – undo
716 716
 		$user = $this->userManager->get($userId);
717 717
 
718 718
 		// Check if the user exists
719
-		if($user === null) {
719
+		if ($user === null) {
720 720
 			throw new OCSException('User does not exist', 101);
721 721
 		}
722 722
 		// Check if group exists
723
-		if($group === null) {
724
-			throw new OCSException('Group does not exist',  102);
723
+		if ($group === null) {
724
+			throw new OCSException('Group does not exist', 102);
725 725
 		}
726 726
 		// Check if trying to make subadmin of admin group
727
-		if($group->getGID() === 'admin') {
727
+		if ($group->getGID() === 'admin') {
728 728
 			throw new OCSException('Cannot create subadmins for admin group', 103);
729 729
 		}
730 730
 
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
 			return new DataResponse();
736 736
 		}
737 737
 		// Go
738
-		if($subAdminManager->createSubAdmin($user, $group)) {
738
+		if ($subAdminManager->createSubAdmin($user, $group)) {
739 739
 			return new DataResponse();
740 740
 		} else {
741 741
 			throw new OCSException('Unknown error occurred', 103);
@@ -758,20 +758,20 @@  discard block
 block discarded – undo
758 758
 		$subAdminManager = $this->groupManager->getSubAdmin();
759 759
 
760 760
 		// Check if the user exists
761
-		if($user === null) {
761
+		if ($user === null) {
762 762
 			throw new OCSException('User does not exist', 101);
763 763
 		}
764 764
 		// Check if the group exists
765
-		if($group === null) {
765
+		if ($group === null) {
766 766
 			throw new OCSException('Group does not exist', 101);
767 767
 		}
768 768
 		// Check if they are a subadmin of this said group
769
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
769
+		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
770 770
 			throw new OCSException('User is not a subadmin of this group', 102);
771 771
 		}
772 772
 
773 773
 		// Go
774
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
774
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
775 775
 			return new DataResponse();
776 776
 		} else {
777 777
 			throw new OCSException('Unknown error occurred', 103);
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
 	public function getUserSubAdminGroups($userId) {
789 789
 		$user = $this->userManager->get($userId);
790 790
 		// Check if the user exists
791
-		if($user === null) {
791
+		if ($user === null) {
792 792
 			throw new OCSException('User does not exist', 101);
793 793
 		}
794 794
 
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 			$groups[$key] = $group->getGID();
799 799
 		}
800 800
 
801
-		if(!$groups) {
801
+		if (!$groups) {
802 802
 			throw new OCSException('Unknown error occurred', 102);
803 803
 		} else {
804 804
 			return new DataResponse($groups);
@@ -842,13 +842,13 @@  discard block
 block discarded – undo
842 842
 		$currentLoggedInUser = $this->userSession->getUser();
843 843
 
844 844
 		$targetUser = $this->userManager->get($userId);
845
-		if($targetUser === null) {
845
+		if ($targetUser === null) {
846 846
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
847 847
 		}
848 848
 
849 849
 		// Check if admin / subadmin
850 850
 		$subAdminManager = $this->groupManager->getSubAdmin();
851
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
851
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
852 852
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
853 853
 			// No rights
854 854
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 			$this->newUserMailHelper->setL10N($l10n);
871 871
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
872 872
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
873
-		} catch(\Exception $e) {
873
+		} catch (\Exception $e) {
874 874
 			$this->logger->logException($e, [
875 875
 				'message' => "Can't send new user mail to $email",
876 876
 				'level' => \OCP\Util::ERROR,
Please login to merge, or discard this patch.