Passed
Push — master ( 86d308...c3b22f )
by Morris
16:36
created
lib/private/Files/Storage/Wrapper/Encryption.php 1 patch
Indentation   +988 added lines, -988 removed lines patch added patch discarded remove patch
@@ -48,993 +48,993 @@
 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
-					// if we update a encrypted file with a un-encrypted one we change the db flag
416
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
417
-						$cache = $this->storage->getCache();
418
-						if ($cache) {
419
-							$entry = $cache->get($path);
420
-							$cache->update($entry->getId(), ['encrypted' => 0]);
421
-						}
422
-					}
423
-					if ($encryptionEnabled) {
424
-						// if $encryptionModuleId is empty, the default module will be used
425
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
426
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
427
-						$signed = true;
428
-					}
429
-				} else {
430
-					$info = $this->getCache()->get($path);
431
-					// only get encryption module if we found one in the header
432
-					// or if file should be encrypted according to the file cache
433
-					if (!empty($encryptionModuleId)) {
434
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
435
-						$shouldEncrypt = true;
436
-					} else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
437
-						// we come from a old installation. No header and/or no module defined
438
-						// but the file is encrypted. In this case we need to use the
439
-						// OC_DEFAULT_MODULE to read the file
440
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
441
-						$shouldEncrypt = true;
442
-						$targetIsEncrypted = true;
443
-					}
444
-				}
445
-			} catch (ModuleDoesNotExistsException $e) {
446
-				$this->logger->logException($e, [
447
-					'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
448
-					'level' => ILogger::WARN,
449
-					'app' => 'core',
450
-				]);
451
-			}
452
-
453
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
454
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
455
-				if (!$targetExists || !$targetIsEncrypted) {
456
-					$shouldEncrypt = false;
457
-				}
458
-			}
459
-
460
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
461
-				$headerSize = $this->getHeaderSize($path);
462
-				$source = $this->storage->fopen($path, $mode);
463
-				if (!is_resource($source)) {
464
-					return false;
465
-				}
466
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
467
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
468
-					$size, $unencryptedSize, $headerSize, $signed);
469
-				return $handle;
470
-			}
471
-
472
-		}
473
-
474
-		return $this->storage->fopen($path, $mode);
475
-	}
476
-
477
-
478
-	/**
479
-	 * perform some plausibility checks if the the unencrypted size is correct.
480
-	 * If not, we calculate the correct unencrypted size and return it
481
-	 *
482
-	 * @param string $path internal path relative to the storage root
483
-	 * @param int $unencryptedSize size of the unencrypted file
484
-	 *
485
-	 * @return int unencrypted size
486
-	 */
487
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
488
-
489
-		$size = $this->storage->filesize($path);
490
-		$result = $unencryptedSize;
491
-
492
-		if ($unencryptedSize < 0 ||
493
-			($size > 0 && $unencryptedSize === $size)
494
-		) {
495
-			// check if we already calculate the unencrypted size for the
496
-			// given path to avoid recursions
497
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
498
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
499
-				try {
500
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
501
-				} catch (\Exception $e) {
502
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
503
-					$this->logger->logException($e);
504
-				}
505
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
506
-			}
507
-		}
508
-
509
-		return $result;
510
-	}
511
-
512
-	/**
513
-	 * calculate the unencrypted size
514
-	 *
515
-	 * @param string $path internal path relative to the storage root
516
-	 * @param int $size size of the physical file
517
-	 * @param int $unencryptedSize size of the unencrypted file
518
-	 *
519
-	 * @return int calculated unencrypted size
520
-	 */
521
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
522
-
523
-		$headerSize = $this->getHeaderSize($path);
524
-		$header = $this->getHeader($path);
525
-		$encryptionModule = $this->getEncryptionModule($path);
526
-
527
-		$stream = $this->storage->fopen($path, 'r');
528
-
529
-		// if we couldn't open the file we return the old unencrypted size
530
-		if (!is_resource($stream)) {
531
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
532
-			return $unencryptedSize;
533
-		}
534
-
535
-		$newUnencryptedSize = 0;
536
-		$size -= $headerSize;
537
-		$blockSize = $this->util->getBlockSize();
538
-
539
-		// if a header exists we skip it
540
-		if ($headerSize > 0) {
541
-			fread($stream, $headerSize);
542
-		}
543
-
544
-		// fast path, else the calculation for $lastChunkNr is bogus
545
-		if ($size === 0) {
546
-			return 0;
547
-		}
548
-
549
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
550
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
551
-
552
-		// calculate last chunk nr
553
-		// next highest is end of chunks, one subtracted is last one
554
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
555
-
556
-		$lastChunkNr = ceil($size/ $blockSize)-1;
557
-		// calculate last chunk position
558
-		$lastChunkPos = ($lastChunkNr * $blockSize);
559
-		// try to fseek to the last chunk, if it fails we have to read the whole file
560
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
561
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
562
-		}
563
-
564
-		$lastChunkContentEncrypted='';
565
-		$count = $blockSize;
566
-
567
-		while ($count > 0) {
568
-			$data=fread($stream, $blockSize);
569
-			$count=strlen($data);
570
-			$lastChunkContentEncrypted .= $data;
571
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
572
-				$newUnencryptedSize += $unencryptedBlockSize;
573
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
574
-			}
575
-		}
576
-
577
-		fclose($stream);
578
-
579
-		// we have to decrypt the last chunk to get it actual size
580
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
581
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
582
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
583
-
584
-		// calc the real file size with the size of the last chunk
585
-		$newUnencryptedSize += strlen($decryptedLastChunk);
586
-
587
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
588
-
589
-		// write to cache if applicable
590
-		$cache = $this->storage->getCache();
591
-		if ($cache) {
592
-			$entry = $cache->get($path);
593
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
594
-		}
595
-
596
-		return $newUnencryptedSize;
597
-	}
598
-
599
-	/**
600
-	 * @param Storage\IStorage $sourceStorage
601
-	 * @param string $sourceInternalPath
602
-	 * @param string $targetInternalPath
603
-	 * @param bool $preserveMtime
604
-	 * @return bool
605
-	 */
606
-	public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
607
-		if ($sourceStorage === $this) {
608
-			return $this->rename($sourceInternalPath, $targetInternalPath);
609
-		}
610
-
611
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
612
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
613
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
614
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
615
-		// - remove $this->copyBetweenStorage
616
-
617
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
618
-			return false;
619
-		}
620
-
621
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
622
-		if ($result) {
623
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
624
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
625
-			} else {
626
-				$result &= $sourceStorage->unlink($sourceInternalPath);
627
-			}
628
-		}
629
-		return $result;
630
-	}
631
-
632
-
633
-	/**
634
-	 * @param Storage\IStorage $sourceStorage
635
-	 * @param string $sourceInternalPath
636
-	 * @param string $targetInternalPath
637
-	 * @param bool $preserveMtime
638
-	 * @param bool $isRename
639
-	 * @return bool
640
-	 */
641
-	public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
642
-
643
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
644
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
645
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
646
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
647
-		// - remove $this->copyBetweenStorage
648
-
649
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
650
-	}
651
-
652
-	/**
653
-	 * Update the encrypted cache version in the database
654
-	 *
655
-	 * @param Storage\IStorage $sourceStorage
656
-	 * @param string $sourceInternalPath
657
-	 * @param string $targetInternalPath
658
-	 * @param bool $isRename
659
-	 * @param bool $keepEncryptionVersion
660
-	 */
661
-	private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
662
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
663
-		$cacheInformation = [
664
-			'encrypted' => $isEncrypted,
665
-		];
666
-		if($isEncrypted) {
667
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
668
-
669
-			// In case of a move operation from an unencrypted to an encrypted
670
-			// storage the old encrypted version would stay with "0" while the
671
-			// correct value would be "1". Thus we manually set the value to "1"
672
-			// for those cases.
673
-			// See also https://github.com/owncloud/core/issues/23078
674
-			if($encryptedVersion === 0 || !$keepEncryptionVersion) {
675
-				$encryptedVersion = 1;
676
-			}
677
-
678
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
679
-		}
680
-
681
-		// in case of a rename we need to manipulate the source cache because
682
-		// this information will be kept for the new target
683
-		if ($isRename) {
684
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
685
-		} else {
686
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
687
-		}
688
-	}
689
-
690
-	/**
691
-	 * copy file between two storages
692
-	 *
693
-	 * @param Storage\IStorage $sourceStorage
694
-	 * @param string $sourceInternalPath
695
-	 * @param string $targetInternalPath
696
-	 * @param bool $preserveMtime
697
-	 * @param bool $isRename
698
-	 * @return bool
699
-	 * @throws \Exception
700
-	 */
701
-	private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
702
-
703
-		// for versions we have nothing to do, because versions should always use the
704
-		// key from the original file. Just create a 1:1 copy and done
705
-		if ($this->isVersion($targetInternalPath) ||
706
-			$this->isVersion($sourceInternalPath)) {
707
-			// remember that we try to create a version so that we can detect it during
708
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
709
-			// create a 1:1 copy of the file
710
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
711
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
712
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
713
-			if ($result) {
714
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
715
-				// make sure that we update the unencrypted size for the version
716
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
717
-					$this->updateUnencryptedSize(
718
-						$this->getFullPath($targetInternalPath),
719
-						$info['size']
720
-					);
721
-				}
722
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
723
-			}
724
-			return $result;
725
-		}
726
-
727
-		// first copy the keys that we reuse the existing file key on the target location
728
-		// and don't create a new one which would break versions for example.
729
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
730
-		if (count($mount) === 1) {
731
-			$mountPoint = $mount[0]->getMountPoint();
732
-			$source = $mountPoint . '/' . $sourceInternalPath;
733
-			$target = $this->getFullPath($targetInternalPath);
734
-			$this->copyKeys($source, $target);
735
-		} else {
736
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
737
-		}
738
-
739
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
740
-			$dh = $sourceStorage->opendir($sourceInternalPath);
741
-			$result = $this->mkdir($targetInternalPath);
742
-			if (is_resource($dh)) {
743
-				while ($result and ($file = readdir($dh)) !== false) {
744
-					if (!Filesystem::isIgnoredDir($file)) {
745
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
746
-					}
747
-				}
748
-			}
749
-		} else {
750
-			try {
751
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
752
-				$target = $this->fopen($targetInternalPath, 'w');
753
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
754
-				fclose($source);
755
-				fclose($target);
756
-			} catch (\Exception $e) {
757
-				fclose($source);
758
-				fclose($target);
759
-				throw $e;
760
-			}
761
-			if($result) {
762
-				if ($preserveMtime) {
763
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
764
-				}
765
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
766
-			} else {
767
-				// delete partially written target file
768
-				$this->unlink($targetInternalPath);
769
-				// delete cache entry that was created by fopen
770
-				$this->getCache()->remove($targetInternalPath);
771
-			}
772
-		}
773
-		return (bool)$result;
774
-
775
-	}
776
-
777
-	/**
778
-	 * get the path to a local version of the file.
779
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
780
-	 *
781
-	 * @param string $path
782
-	 * @return string
783
-	 */
784
-	public function getLocalFile($path) {
785
-		if ($this->encryptionManager->isEnabled()) {
786
-			$cachedFile = $this->getCachedFile($path);
787
-			if (is_string($cachedFile)) {
788
-				return $cachedFile;
789
-			}
790
-		}
791
-		return $this->storage->getLocalFile($path);
792
-	}
793
-
794
-	/**
795
-	 * Returns the wrapped storage's value for isLocal()
796
-	 *
797
-	 * @return bool wrapped storage's isLocal() value
798
-	 */
799
-	public function isLocal() {
800
-		if ($this->encryptionManager->isEnabled()) {
801
-			return false;
802
-		}
803
-		return $this->storage->isLocal();
804
-	}
805
-
806
-	/**
807
-	 * see http://php.net/manual/en/function.stat.php
808
-	 * only the following keys are required in the result: size and mtime
809
-	 *
810
-	 * @param string $path
811
-	 * @return array
812
-	 */
813
-	public function stat($path) {
814
-		$stat = $this->storage->stat($path);
815
-		$fileSize = $this->filesize($path);
816
-		$stat['size'] = $fileSize;
817
-		$stat[7] = $fileSize;
818
-		return $stat;
819
-	}
820
-
821
-	/**
822
-	 * see http://php.net/manual/en/function.hash.php
823
-	 *
824
-	 * @param string $type
825
-	 * @param string $path
826
-	 * @param bool $raw
827
-	 * @return string
828
-	 */
829
-	public function hash($type, $path, $raw = false) {
830
-		$fh = $this->fopen($path, 'rb');
831
-		$ctx = hash_init($type);
832
-		hash_update_stream($ctx, $fh);
833
-		fclose($fh);
834
-		return hash_final($ctx, $raw);
835
-	}
836
-
837
-	/**
838
-	 * return full path, including mount point
839
-	 *
840
-	 * @param string $path relative to mount point
841
-	 * @return string full path including mount point
842
-	 */
843
-	protected function getFullPath($path) {
844
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
845
-	}
846
-
847
-	/**
848
-	 * read first block of encrypted file, typically this will contain the
849
-	 * encryption header
850
-	 *
851
-	 * @param string $path
852
-	 * @return string
853
-	 */
854
-	protected function readFirstBlock($path) {
855
-		$firstBlock = '';
856
-		if ($this->storage->file_exists($path)) {
857
-			$handle = $this->storage->fopen($path, 'r');
858
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
859
-			fclose($handle);
860
-		}
861
-		return $firstBlock;
862
-	}
863
-
864
-	/**
865
-	 * return header size of given file
866
-	 *
867
-	 * @param string $path
868
-	 * @return int
869
-	 */
870
-	protected function getHeaderSize($path) {
871
-		$headerSize = 0;
872
-		$realFile = $this->util->stripPartialFileExtension($path);
873
-		if ($this->storage->file_exists($realFile)) {
874
-			$path = $realFile;
875
-		}
876
-		$firstBlock = $this->readFirstBlock($path);
877
-
878
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
879
-			$headerSize = $this->util->getHeaderSize();
880
-		}
881
-
882
-		return $headerSize;
883
-	}
884
-
885
-	/**
886
-	 * parse raw header to array
887
-	 *
888
-	 * @param string $rawHeader
889
-	 * @return array
890
-	 */
891
-	protected function parseRawHeader($rawHeader) {
892
-		$result = array();
893
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
894
-			$header = $rawHeader;
895
-			$endAt = strpos($header, Util::HEADER_END);
896
-			if ($endAt !== false) {
897
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
898
-
899
-				// +1 to not start with an ':' which would result in empty element at the beginning
900
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
901
-
902
-				$element = array_shift($exploded);
903
-				while ($element !== Util::HEADER_END) {
904
-					$result[$element] = array_shift($exploded);
905
-					$element = array_shift($exploded);
906
-				}
907
-			}
908
-		}
909
-
910
-		return $result;
911
-	}
912
-
913
-	/**
914
-	 * read header from file
915
-	 *
916
-	 * @param string $path
917
-	 * @return array
918
-	 */
919
-	protected function getHeader($path) {
920
-		$realFile = $this->util->stripPartialFileExtension($path);
921
-		$exists = $this->storage->file_exists($realFile);
922
-		if ($exists) {
923
-			$path = $realFile;
924
-		}
925
-
926
-		$firstBlock = $this->readFirstBlock($path);
927
-		$result = $this->parseRawHeader($firstBlock);
928
-
929
-		// if the header doesn't contain a encryption module we check if it is a
930
-		// legacy file. If true, we add the default encryption module
931
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
932
-			if (!empty($result)) {
933
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
934
-			} else if ($exists) {
935
-				// if the header was empty we have to check first if it is a encrypted file at all
936
-				// We would do query to filecache only if we know that entry in filecache exists
937
-				$info = $this->getCache()->get($path);
938
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
939
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
940
-				}
941
-			}
942
-		}
943
-
944
-		return $result;
945
-	}
946
-
947
-	/**
948
-	 * read encryption module needed to read/write the file located at $path
949
-	 *
950
-	 * @param string $path
951
-	 * @return null|\OCP\Encryption\IEncryptionModule
952
-	 * @throws ModuleDoesNotExistsException
953
-	 * @throws \Exception
954
-	 */
955
-	protected function getEncryptionModule($path) {
956
-		$encryptionModule = null;
957
-		$header = $this->getHeader($path);
958
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
959
-		if (!empty($encryptionModuleId)) {
960
-			try {
961
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
962
-			} catch (ModuleDoesNotExistsException $e) {
963
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
964
-				throw $e;
965
-			}
966
-		}
967
-
968
-		return $encryptionModule;
969
-	}
970
-
971
-	/**
972
-	 * @param string $path
973
-	 * @param int $unencryptedSize
974
-	 */
975
-	public function updateUnencryptedSize($path, $unencryptedSize) {
976
-		$this->unencryptedSize[$path] = $unencryptedSize;
977
-	}
978
-
979
-	/**
980
-	 * copy keys to new location
981
-	 *
982
-	 * @param string $source path relative to data/
983
-	 * @param string $target path relative to data/
984
-	 * @return bool
985
-	 */
986
-	protected function copyKeys($source, $target) {
987
-		if (!$this->util->isExcluded($source)) {
988
-			return $this->keyStorage->copyKeys($source, $target);
989
-		}
990
-
991
-		return false;
992
-	}
993
-
994
-	/**
995
-	 * check if path points to a files version
996
-	 *
997
-	 * @param $path
998
-	 * @return bool
999
-	 */
1000
-	protected function isVersion($path) {
1001
-		$normalized = Filesystem::normalizePath($path);
1002
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1003
-	}
1004
-
1005
-	/**
1006
-	 * check if the given storage should be encrypted or not
1007
-	 *
1008
-	 * @param $path
1009
-	 * @return bool
1010
-	 */
1011
-	protected function shouldEncrypt($path) {
1012
-		$fullPath = $this->getFullPath($path);
1013
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1014
-		if ($mountPointConfig === false) {
1015
-			return false;
1016
-		}
1017
-
1018
-		try {
1019
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1020
-		} catch (ModuleDoesNotExistsException $e) {
1021
-			return false;
1022
-		}
1023
-
1024
-		if ($encryptionModule === null) {
1025
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1026
-		}
1027
-
1028
-		return $encryptionModule->shouldEncrypt($fullPath);
1029
-
1030
-	}
1031
-
1032
-	public function writeStream(string $path, $stream, int $size = null): int {
1033
-		// always fall back to fopen
1034
-		$target = $this->fopen($path, 'w');
1035
-		list($count, $result) = \OC_Helper::streamCopy($stream, $target);
1036
-		fclose($target);
1037
-		return $count;
1038
-	}
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
+                    // if we update a encrypted file with a un-encrypted one we change the db flag
416
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
417
+                        $cache = $this->storage->getCache();
418
+                        if ($cache) {
419
+                            $entry = $cache->get($path);
420
+                            $cache->update($entry->getId(), ['encrypted' => 0]);
421
+                        }
422
+                    }
423
+                    if ($encryptionEnabled) {
424
+                        // if $encryptionModuleId is empty, the default module will be used
425
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
426
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
427
+                        $signed = true;
428
+                    }
429
+                } else {
430
+                    $info = $this->getCache()->get($path);
431
+                    // only get encryption module if we found one in the header
432
+                    // or if file should be encrypted according to the file cache
433
+                    if (!empty($encryptionModuleId)) {
434
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
435
+                        $shouldEncrypt = true;
436
+                    } else if (empty($encryptionModuleId) && $info['encrypted'] === true) {
437
+                        // we come from a old installation. No header and/or no module defined
438
+                        // but the file is encrypted. In this case we need to use the
439
+                        // OC_DEFAULT_MODULE to read the file
440
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
441
+                        $shouldEncrypt = true;
442
+                        $targetIsEncrypted = true;
443
+                    }
444
+                }
445
+            } catch (ModuleDoesNotExistsException $e) {
446
+                $this->logger->logException($e, [
447
+                    'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
448
+                    'level' => ILogger::WARN,
449
+                    'app' => 'core',
450
+                ]);
451
+            }
452
+
453
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
454
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
455
+                if (!$targetExists || !$targetIsEncrypted) {
456
+                    $shouldEncrypt = false;
457
+                }
458
+            }
459
+
460
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
461
+                $headerSize = $this->getHeaderSize($path);
462
+                $source = $this->storage->fopen($path, $mode);
463
+                if (!is_resource($source)) {
464
+                    return false;
465
+                }
466
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
467
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
468
+                    $size, $unencryptedSize, $headerSize, $signed);
469
+                return $handle;
470
+            }
471
+
472
+        }
473
+
474
+        return $this->storage->fopen($path, $mode);
475
+    }
476
+
477
+
478
+    /**
479
+     * perform some plausibility checks if the the unencrypted size is correct.
480
+     * If not, we calculate the correct unencrypted size and return it
481
+     *
482
+     * @param string $path internal path relative to the storage root
483
+     * @param int $unencryptedSize size of the unencrypted file
484
+     *
485
+     * @return int unencrypted size
486
+     */
487
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
488
+
489
+        $size = $this->storage->filesize($path);
490
+        $result = $unencryptedSize;
491
+
492
+        if ($unencryptedSize < 0 ||
493
+            ($size > 0 && $unencryptedSize === $size)
494
+        ) {
495
+            // check if we already calculate the unencrypted size for the
496
+            // given path to avoid recursions
497
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
498
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
499
+                try {
500
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
501
+                } catch (\Exception $e) {
502
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
503
+                    $this->logger->logException($e);
504
+                }
505
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
506
+            }
507
+        }
508
+
509
+        return $result;
510
+    }
511
+
512
+    /**
513
+     * calculate the unencrypted size
514
+     *
515
+     * @param string $path internal path relative to the storage root
516
+     * @param int $size size of the physical file
517
+     * @param int $unencryptedSize size of the unencrypted file
518
+     *
519
+     * @return int calculated unencrypted size
520
+     */
521
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
522
+
523
+        $headerSize = $this->getHeaderSize($path);
524
+        $header = $this->getHeader($path);
525
+        $encryptionModule = $this->getEncryptionModule($path);
526
+
527
+        $stream = $this->storage->fopen($path, 'r');
528
+
529
+        // if we couldn't open the file we return the old unencrypted size
530
+        if (!is_resource($stream)) {
531
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
532
+            return $unencryptedSize;
533
+        }
534
+
535
+        $newUnencryptedSize = 0;
536
+        $size -= $headerSize;
537
+        $blockSize = $this->util->getBlockSize();
538
+
539
+        // if a header exists we skip it
540
+        if ($headerSize > 0) {
541
+            fread($stream, $headerSize);
542
+        }
543
+
544
+        // fast path, else the calculation for $lastChunkNr is bogus
545
+        if ($size === 0) {
546
+            return 0;
547
+        }
548
+
549
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
550
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
551
+
552
+        // calculate last chunk nr
553
+        // next highest is end of chunks, one subtracted is last one
554
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
555
+
556
+        $lastChunkNr = ceil($size/ $blockSize)-1;
557
+        // calculate last chunk position
558
+        $lastChunkPos = ($lastChunkNr * $blockSize);
559
+        // try to fseek to the last chunk, if it fails we have to read the whole file
560
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
561
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
562
+        }
563
+
564
+        $lastChunkContentEncrypted='';
565
+        $count = $blockSize;
566
+
567
+        while ($count > 0) {
568
+            $data=fread($stream, $blockSize);
569
+            $count=strlen($data);
570
+            $lastChunkContentEncrypted .= $data;
571
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
572
+                $newUnencryptedSize += $unencryptedBlockSize;
573
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
574
+            }
575
+        }
576
+
577
+        fclose($stream);
578
+
579
+        // we have to decrypt the last chunk to get it actual size
580
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
581
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
582
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
583
+
584
+        // calc the real file size with the size of the last chunk
585
+        $newUnencryptedSize += strlen($decryptedLastChunk);
586
+
587
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
588
+
589
+        // write to cache if applicable
590
+        $cache = $this->storage->getCache();
591
+        if ($cache) {
592
+            $entry = $cache->get($path);
593
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
594
+        }
595
+
596
+        return $newUnencryptedSize;
597
+    }
598
+
599
+    /**
600
+     * @param Storage\IStorage $sourceStorage
601
+     * @param string $sourceInternalPath
602
+     * @param string $targetInternalPath
603
+     * @param bool $preserveMtime
604
+     * @return bool
605
+     */
606
+    public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
607
+        if ($sourceStorage === $this) {
608
+            return $this->rename($sourceInternalPath, $targetInternalPath);
609
+        }
610
+
611
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
612
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
613
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
614
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
615
+        // - remove $this->copyBetweenStorage
616
+
617
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
618
+            return false;
619
+        }
620
+
621
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
622
+        if ($result) {
623
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
624
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
625
+            } else {
626
+                $result &= $sourceStorage->unlink($sourceInternalPath);
627
+            }
628
+        }
629
+        return $result;
630
+    }
631
+
632
+
633
+    /**
634
+     * @param Storage\IStorage $sourceStorage
635
+     * @param string $sourceInternalPath
636
+     * @param string $targetInternalPath
637
+     * @param bool $preserveMtime
638
+     * @param bool $isRename
639
+     * @return bool
640
+     */
641
+    public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
642
+
643
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
644
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
645
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
646
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
647
+        // - remove $this->copyBetweenStorage
648
+
649
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
650
+    }
651
+
652
+    /**
653
+     * Update the encrypted cache version in the database
654
+     *
655
+     * @param Storage\IStorage $sourceStorage
656
+     * @param string $sourceInternalPath
657
+     * @param string $targetInternalPath
658
+     * @param bool $isRename
659
+     * @param bool $keepEncryptionVersion
660
+     */
661
+    private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
662
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
663
+        $cacheInformation = [
664
+            'encrypted' => $isEncrypted,
665
+        ];
666
+        if($isEncrypted) {
667
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
668
+
669
+            // In case of a move operation from an unencrypted to an encrypted
670
+            // storage the old encrypted version would stay with "0" while the
671
+            // correct value would be "1". Thus we manually set the value to "1"
672
+            // for those cases.
673
+            // See also https://github.com/owncloud/core/issues/23078
674
+            if($encryptedVersion === 0 || !$keepEncryptionVersion) {
675
+                $encryptedVersion = 1;
676
+            }
677
+
678
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
679
+        }
680
+
681
+        // in case of a rename we need to manipulate the source cache because
682
+        // this information will be kept for the new target
683
+        if ($isRename) {
684
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
685
+        } else {
686
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
687
+        }
688
+    }
689
+
690
+    /**
691
+     * copy file between two storages
692
+     *
693
+     * @param Storage\IStorage $sourceStorage
694
+     * @param string $sourceInternalPath
695
+     * @param string $targetInternalPath
696
+     * @param bool $preserveMtime
697
+     * @param bool $isRename
698
+     * @return bool
699
+     * @throws \Exception
700
+     */
701
+    private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
702
+
703
+        // for versions we have nothing to do, because versions should always use the
704
+        // key from the original file. Just create a 1:1 copy and done
705
+        if ($this->isVersion($targetInternalPath) ||
706
+            $this->isVersion($sourceInternalPath)) {
707
+            // remember that we try to create a version so that we can detect it during
708
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
709
+            // create a 1:1 copy of the file
710
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
711
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
712
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
713
+            if ($result) {
714
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
715
+                // make sure that we update the unencrypted size for the version
716
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
717
+                    $this->updateUnencryptedSize(
718
+                        $this->getFullPath($targetInternalPath),
719
+                        $info['size']
720
+                    );
721
+                }
722
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
723
+            }
724
+            return $result;
725
+        }
726
+
727
+        // first copy the keys that we reuse the existing file key on the target location
728
+        // and don't create a new one which would break versions for example.
729
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
730
+        if (count($mount) === 1) {
731
+            $mountPoint = $mount[0]->getMountPoint();
732
+            $source = $mountPoint . '/' . $sourceInternalPath;
733
+            $target = $this->getFullPath($targetInternalPath);
734
+            $this->copyKeys($source, $target);
735
+        } else {
736
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
737
+        }
738
+
739
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
740
+            $dh = $sourceStorage->opendir($sourceInternalPath);
741
+            $result = $this->mkdir($targetInternalPath);
742
+            if (is_resource($dh)) {
743
+                while ($result and ($file = readdir($dh)) !== false) {
744
+                    if (!Filesystem::isIgnoredDir($file)) {
745
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
746
+                    }
747
+                }
748
+            }
749
+        } else {
750
+            try {
751
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
752
+                $target = $this->fopen($targetInternalPath, 'w');
753
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
754
+                fclose($source);
755
+                fclose($target);
756
+            } catch (\Exception $e) {
757
+                fclose($source);
758
+                fclose($target);
759
+                throw $e;
760
+            }
761
+            if($result) {
762
+                if ($preserveMtime) {
763
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
764
+                }
765
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
766
+            } else {
767
+                // delete partially written target file
768
+                $this->unlink($targetInternalPath);
769
+                // delete cache entry that was created by fopen
770
+                $this->getCache()->remove($targetInternalPath);
771
+            }
772
+        }
773
+        return (bool)$result;
774
+
775
+    }
776
+
777
+    /**
778
+     * get the path to a local version of the file.
779
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
780
+     *
781
+     * @param string $path
782
+     * @return string
783
+     */
784
+    public function getLocalFile($path) {
785
+        if ($this->encryptionManager->isEnabled()) {
786
+            $cachedFile = $this->getCachedFile($path);
787
+            if (is_string($cachedFile)) {
788
+                return $cachedFile;
789
+            }
790
+        }
791
+        return $this->storage->getLocalFile($path);
792
+    }
793
+
794
+    /**
795
+     * Returns the wrapped storage's value for isLocal()
796
+     *
797
+     * @return bool wrapped storage's isLocal() value
798
+     */
799
+    public function isLocal() {
800
+        if ($this->encryptionManager->isEnabled()) {
801
+            return false;
802
+        }
803
+        return $this->storage->isLocal();
804
+    }
805
+
806
+    /**
807
+     * see http://php.net/manual/en/function.stat.php
808
+     * only the following keys are required in the result: size and mtime
809
+     *
810
+     * @param string $path
811
+     * @return array
812
+     */
813
+    public function stat($path) {
814
+        $stat = $this->storage->stat($path);
815
+        $fileSize = $this->filesize($path);
816
+        $stat['size'] = $fileSize;
817
+        $stat[7] = $fileSize;
818
+        return $stat;
819
+    }
820
+
821
+    /**
822
+     * see http://php.net/manual/en/function.hash.php
823
+     *
824
+     * @param string $type
825
+     * @param string $path
826
+     * @param bool $raw
827
+     * @return string
828
+     */
829
+    public function hash($type, $path, $raw = false) {
830
+        $fh = $this->fopen($path, 'rb');
831
+        $ctx = hash_init($type);
832
+        hash_update_stream($ctx, $fh);
833
+        fclose($fh);
834
+        return hash_final($ctx, $raw);
835
+    }
836
+
837
+    /**
838
+     * return full path, including mount point
839
+     *
840
+     * @param string $path relative to mount point
841
+     * @return string full path including mount point
842
+     */
843
+    protected function getFullPath($path) {
844
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
845
+    }
846
+
847
+    /**
848
+     * read first block of encrypted file, typically this will contain the
849
+     * encryption header
850
+     *
851
+     * @param string $path
852
+     * @return string
853
+     */
854
+    protected function readFirstBlock($path) {
855
+        $firstBlock = '';
856
+        if ($this->storage->file_exists($path)) {
857
+            $handle = $this->storage->fopen($path, 'r');
858
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
859
+            fclose($handle);
860
+        }
861
+        return $firstBlock;
862
+    }
863
+
864
+    /**
865
+     * return header size of given file
866
+     *
867
+     * @param string $path
868
+     * @return int
869
+     */
870
+    protected function getHeaderSize($path) {
871
+        $headerSize = 0;
872
+        $realFile = $this->util->stripPartialFileExtension($path);
873
+        if ($this->storage->file_exists($realFile)) {
874
+            $path = $realFile;
875
+        }
876
+        $firstBlock = $this->readFirstBlock($path);
877
+
878
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
879
+            $headerSize = $this->util->getHeaderSize();
880
+        }
881
+
882
+        return $headerSize;
883
+    }
884
+
885
+    /**
886
+     * parse raw header to array
887
+     *
888
+     * @param string $rawHeader
889
+     * @return array
890
+     */
891
+    protected function parseRawHeader($rawHeader) {
892
+        $result = array();
893
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
894
+            $header = $rawHeader;
895
+            $endAt = strpos($header, Util::HEADER_END);
896
+            if ($endAt !== false) {
897
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
898
+
899
+                // +1 to not start with an ':' which would result in empty element at the beginning
900
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
901
+
902
+                $element = array_shift($exploded);
903
+                while ($element !== Util::HEADER_END) {
904
+                    $result[$element] = array_shift($exploded);
905
+                    $element = array_shift($exploded);
906
+                }
907
+            }
908
+        }
909
+
910
+        return $result;
911
+    }
912
+
913
+    /**
914
+     * read header from file
915
+     *
916
+     * @param string $path
917
+     * @return array
918
+     */
919
+    protected function getHeader($path) {
920
+        $realFile = $this->util->stripPartialFileExtension($path);
921
+        $exists = $this->storage->file_exists($realFile);
922
+        if ($exists) {
923
+            $path = $realFile;
924
+        }
925
+
926
+        $firstBlock = $this->readFirstBlock($path);
927
+        $result = $this->parseRawHeader($firstBlock);
928
+
929
+        // if the header doesn't contain a encryption module we check if it is a
930
+        // legacy file. If true, we add the default encryption module
931
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
932
+            if (!empty($result)) {
933
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
934
+            } else if ($exists) {
935
+                // if the header was empty we have to check first if it is a encrypted file at all
936
+                // We would do query to filecache only if we know that entry in filecache exists
937
+                $info = $this->getCache()->get($path);
938
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
939
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
940
+                }
941
+            }
942
+        }
943
+
944
+        return $result;
945
+    }
946
+
947
+    /**
948
+     * read encryption module needed to read/write the file located at $path
949
+     *
950
+     * @param string $path
951
+     * @return null|\OCP\Encryption\IEncryptionModule
952
+     * @throws ModuleDoesNotExistsException
953
+     * @throws \Exception
954
+     */
955
+    protected function getEncryptionModule($path) {
956
+        $encryptionModule = null;
957
+        $header = $this->getHeader($path);
958
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
959
+        if (!empty($encryptionModuleId)) {
960
+            try {
961
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
962
+            } catch (ModuleDoesNotExistsException $e) {
963
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
964
+                throw $e;
965
+            }
966
+        }
967
+
968
+        return $encryptionModule;
969
+    }
970
+
971
+    /**
972
+     * @param string $path
973
+     * @param int $unencryptedSize
974
+     */
975
+    public function updateUnencryptedSize($path, $unencryptedSize) {
976
+        $this->unencryptedSize[$path] = $unencryptedSize;
977
+    }
978
+
979
+    /**
980
+     * copy keys to new location
981
+     *
982
+     * @param string $source path relative to data/
983
+     * @param string $target path relative to data/
984
+     * @return bool
985
+     */
986
+    protected function copyKeys($source, $target) {
987
+        if (!$this->util->isExcluded($source)) {
988
+            return $this->keyStorage->copyKeys($source, $target);
989
+        }
990
+
991
+        return false;
992
+    }
993
+
994
+    /**
995
+     * check if path points to a files version
996
+     *
997
+     * @param $path
998
+     * @return bool
999
+     */
1000
+    protected function isVersion($path) {
1001
+        $normalized = Filesystem::normalizePath($path);
1002
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1003
+    }
1004
+
1005
+    /**
1006
+     * check if the given storage should be encrypted or not
1007
+     *
1008
+     * @param $path
1009
+     * @return bool
1010
+     */
1011
+    protected function shouldEncrypt($path) {
1012
+        $fullPath = $this->getFullPath($path);
1013
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1014
+        if ($mountPointConfig === false) {
1015
+            return false;
1016
+        }
1017
+
1018
+        try {
1019
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1020
+        } catch (ModuleDoesNotExistsException $e) {
1021
+            return false;
1022
+        }
1023
+
1024
+        if ($encryptionModule === null) {
1025
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1026
+        }
1027
+
1028
+        return $encryptionModule->shouldEncrypt($fullPath);
1029
+
1030
+    }
1031
+
1032
+    public function writeStream(string $path, $stream, int $size = null): int {
1033
+        // always fall back to fopen
1034
+        $target = $this->fopen($path, 'w');
1035
+        list($count, $result) = \OC_Helper::streamCopy($stream, $target);
1036
+        fclose($target);
1037
+        return $count;
1038
+    }
1039 1039
 
1040 1040
 }
Please login to merge, or discard this patch.