Completed
Push — stable9 ( 11047b...318578 )
by Lukas
20:03 queued 09:36
created
lib/private/files/storage/wrapper/encryption.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -982,7 +982,7 @@
 block discarded – undo
982 982
 	/**
983 983
 	 * check if path points to a files version
984 984
 	 *
985
-	 * @param $path
985
+	 * @param string $path
986 986
 	 * @return bool
987 987
 	 */
988 988
 	protected function isVersion($path) {
Please login to merge, or discard this patch.
Indentation   +944 added lines, -944 removed lines patch added patch discarded remove patch
@@ -46,949 +46,949 @@
 block discarded – undo
46 46
 
47 47
 class Encryption extends Wrapper {
48 48
 
49
-	use LocalTempFileTrait;
50
-
51
-	/** @var string */
52
-	private $mountPoint;
53
-
54
-	/** @var \OC\Encryption\Util */
55
-	private $util;
56
-
57
-	/** @var \OCP\Encryption\IManager */
58
-	private $encryptionManager;
59
-
60
-	/** @var \OCP\ILogger */
61
-	private $logger;
62
-
63
-	/** @var string */
64
-	private $uid;
65
-
66
-	/** @var array */
67
-	protected $unencryptedSize;
68
-
69
-	/** @var \OCP\Encryption\IFile */
70
-	private $fileHelper;
71
-
72
-	/** @var IMountPoint */
73
-	private $mount;
74
-
75
-	/** @var IStorage */
76
-	private $keyStorage;
77
-
78
-	/** @var Update */
79
-	private $update;
80
-
81
-	/** @var Manager */
82
-	private $mountManager;
83
-
84
-	/** @var array remember for which path we execute the repair step to avoid recursions */
85
-	private $fixUnencryptedSizeOf = array();
86
-
87
-	/** @var  ArrayCache */
88
-	private $arrayCache;
89
-
90
-	/**
91
-	 * @param array $parameters
92
-	 * @param IManager $encryptionManager
93
-	 * @param Util $util
94
-	 * @param ILogger $logger
95
-	 * @param IFile $fileHelper
96
-	 * @param string $uid
97
-	 * @param IStorage $keyStorage
98
-	 * @param Update $update
99
-	 * @param Manager $mountManager
100
-	 * @param ArrayCache $arrayCache
101
-	 */
102
-	public function __construct(
103
-			$parameters,
104
-			IManager $encryptionManager = null,
105
-			Util $util = null,
106
-			ILogger $logger = null,
107
-			IFile $fileHelper = null,
108
-			$uid = null,
109
-			IStorage $keyStorage = null,
110
-			Update $update = null,
111
-			Manager $mountManager = null,
112
-			ArrayCache $arrayCache = null
113
-		) {
114
-
115
-		$this->mountPoint = $parameters['mountPoint'];
116
-		$this->mount = $parameters['mount'];
117
-		$this->encryptionManager = $encryptionManager;
118
-		$this->util = $util;
119
-		$this->logger = $logger;
120
-		$this->uid = $uid;
121
-		$this->fileHelper = $fileHelper;
122
-		$this->keyStorage = $keyStorage;
123
-		$this->unencryptedSize = array();
124
-		$this->update = $update;
125
-		$this->mountManager = $mountManager;
126
-		$this->arrayCache = $arrayCache;
127
-		parent::__construct($parameters);
128
-	}
129
-
130
-	/**
131
-	 * see http://php.net/manual/en/function.filesize.php
132
-	 * The result for filesize when called on a folder is required to be 0
133
-	 *
134
-	 * @param string $path
135
-	 * @return int
136
-	 */
137
-	public function filesize($path) {
138
-		$fullPath = $this->getFullPath($path);
139
-
140
-		/** @var CacheEntry $info */
141
-		$info = $this->getCache()->get($path);
142
-		if (isset($this->unencryptedSize[$fullPath])) {
143
-			$size = $this->unencryptedSize[$fullPath];
144
-			// update file cache
145
-			if ($info instanceof ICacheEntry) {
146
-				$info = $info->getData();
147
-				$info['encrypted'] = $info['encryptedVersion'];
148
-			} else {
149
-				if (!is_array($info)) {
150
-					$info = [];
151
-				}
152
-				$info['encrypted'] = true;
153
-			}
154
-
155
-			$info['size'] = $size;
156
-			$this->getCache()->put($path, $info);
157
-
158
-			return $size;
159
-		}
160
-
161
-		if (isset($info['fileid']) && $info['encrypted']) {
162
-			return $this->verifyUnencryptedSize($path, $info['size']);
163
-		}
164
-
165
-		return $this->storage->filesize($path);
166
-	}
167
-
168
-	/**
169
-	 * @param string $path
170
-	 * @return array
171
-	 */
172
-	public function getMetaData($path) {
173
-		$data = $this->storage->getMetaData($path);
174
-		if (is_null($data)) {
175
-			return null;
176
-		}
177
-		$fullPath = $this->getFullPath($path);
178
-		$info = $this->getCache()->get($path);
179
-
180
-		if (isset($this->unencryptedSize[$fullPath])) {
181
-			$data['encrypted'] = true;
182
-			$data['size'] = $this->unencryptedSize[$fullPath];
183
-		} else {
184
-			if (isset($info['fileid']) && $info['encrypted']) {
185
-				$data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
-				$data['encrypted'] = true;
187
-			}
188
-		}
189
-
190
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
-			$data['encryptedVersion'] = $info['encryptedVersion'];
192
-		}
193
-
194
-		return $data;
195
-	}
196
-
197
-	/**
198
-	 * see http://php.net/manual/en/function.file_get_contents.php
199
-	 *
200
-	 * @param string $path
201
-	 * @return string
202
-	 */
203
-	public function file_get_contents($path) {
204
-
205
-		$encryptionModule = $this->getEncryptionModule($path);
206
-
207
-		if ($encryptionModule) {
208
-			$handle = $this->fopen($path, "r");
209
-			if (!$handle) {
210
-				return false;
211
-			}
212
-			$data = stream_get_contents($handle);
213
-			fclose($handle);
214
-			return $data;
215
-		}
216
-		return $this->storage->file_get_contents($path);
217
-	}
218
-
219
-	/**
220
-	 * see http://php.net/manual/en/function.file_put_contents.php
221
-	 *
222
-	 * @param string $path
223
-	 * @param string $data
224
-	 * @return bool
225
-	 */
226
-	public function file_put_contents($path, $data) {
227
-		// file put content will always be translated to a stream write
228
-		$handle = $this->fopen($path, 'w');
229
-		if (is_resource($handle)) {
230
-			$written = fwrite($handle, $data);
231
-			fclose($handle);
232
-			return $written;
233
-		}
234
-
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * see http://php.net/manual/en/function.unlink.php
240
-	 *
241
-	 * @param string $path
242
-	 * @return bool
243
-	 */
244
-	public function unlink($path) {
245
-		$fullPath = $this->getFullPath($path);
246
-		if ($this->util->isExcluded($fullPath)) {
247
-			return $this->storage->unlink($path);
248
-		}
249
-
250
-		$encryptionModule = $this->getEncryptionModule($path);
251
-		if ($encryptionModule) {
252
-			$this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
-		}
254
-
255
-		return $this->storage->unlink($path);
256
-	}
257
-
258
-	/**
259
-	 * see http://php.net/manual/en/function.rename.php
260
-	 *
261
-	 * @param string $path1
262
-	 * @param string $path2
263
-	 * @return bool
264
-	 */
265
-	public function rename($path1, $path2) {
266
-
267
-		$result = $this->storage->rename($path1, $path2);
268
-
269
-		if ($result &&
270
-			// versions always use the keys from the original file, so we can skip
271
-			// this step for versions
272
-			$this->isVersion($path2) === false &&
273
-			$this->encryptionManager->isEnabled()) {
274
-			$source = $this->getFullPath($path1);
275
-			if (!$this->util->isExcluded($source)) {
276
-				$target = $this->getFullPath($path2);
277
-				if (isset($this->unencryptedSize[$source])) {
278
-					$this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
-				}
280
-				$this->keyStorage->renameKeys($source, $target);
281
-				$module = $this->getEncryptionModule($path2);
282
-				if ($module) {
283
-					$module->update($target, $this->uid, []);
284
-				}
285
-			}
286
-		}
287
-
288
-		return $result;
289
-	}
290
-
291
-	/**
292
-	 * see http://php.net/manual/en/function.rmdir.php
293
-	 *
294
-	 * @param string $path
295
-	 * @return bool
296
-	 */
297
-	public function rmdir($path) {
298
-		$result = $this->storage->rmdir($path);
299
-		$fullPath = $this->getFullPath($path);
300
-		if ($result &&
301
-			$this->util->isExcluded($fullPath) === false &&
302
-			$this->encryptionManager->isEnabled()
303
-		) {
304
-			$this->keyStorage->deleteAllFileKeys($fullPath);
305
-		}
306
-
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * check if a file can be read
312
-	 *
313
-	 * @param string $path
314
-	 * @return bool
315
-	 */
316
-	public function isReadable($path) {
317
-
318
-		$isReadable = true;
319
-
320
-		$metaData = $this->getMetaData($path);
321
-		if (
322
-			!$this->is_dir($path) &&
323
-			isset($metaData['encrypted']) &&
324
-			$metaData['encrypted'] === true
325
-		) {
326
-			$fullPath = $this->getFullPath($path);
327
-			$module = $this->getEncryptionModule($path);
328
-			$isReadable = $module->isReadable($fullPath, $this->uid);
329
-		}
330
-
331
-		return $this->storage->isReadable($path) && $isReadable;
332
-	}
333
-
334
-	/**
335
-	 * see http://php.net/manual/en/function.copy.php
336
-	 *
337
-	 * @param string $path1
338
-	 * @param string $path2
339
-	 * @return bool
340
-	 */
341
-	public function copy($path1, $path2) {
342
-
343
-		$source = $this->getFullPath($path1);
344
-
345
-		if ($this->util->isExcluded($source)) {
346
-			return $this->storage->copy($path1, $path2);
347
-		}
348
-
349
-		// need to stream copy file by file in case we copy between a encrypted
350
-		// and a unencrypted storage
351
-		$this->unlink($path2);
352
-		$result = $this->copyFromStorage($this, $path1, $path2);
353
-
354
-		return $result;
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') ? true : false;
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->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
-			}
445
-
446
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
-			if (!$encryptionEnabled || !$this->mount->getOption('encrypt', true)) {
448
-				if (!$targetExists || !$targetIsEncrypted) {
449
-					$shouldEncrypt = false;
450
-				}
451
-			}
452
-
453
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
454
-				$headerSize = $this->getHeaderSize($path);
455
-				$source = $this->storage->fopen($path, $mode);
456
-				if (!is_resource($source)) {
457
-					return false;
458
-				}
459
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
-					$size, $unencryptedSize, $headerSize, $signed);
462
-				return $handle;
463
-			}
464
-
465
-		}
466
-
467
-		return $this->storage->fopen($path, $mode);
468
-	}
469
-
470
-
471
-	/**
472
-	 * perform some plausibility checks if the the unencrypted size is correct.
473
-	 * If not, we calculate the correct unencrypted size and return it
474
-	 *
475
-	 * @param string $path internal path relative to the storage root
476
-	 * @param int $unencryptedSize size of the unencrypted file
477
-	 *
478
-	 * @return int unencrypted size
479
-	 */
480
-	protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
-
482
-		$size = $this->storage->filesize($path);
483
-		$result = $unencryptedSize;
484
-
485
-		if ($unencryptedSize < 0 ||
486
-			($size > 0 && $unencryptedSize === $size)
487
-		) {
488
-			// check if we already calculate the unencrypted size for the
489
-			// given path to avoid recursions
490
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
-				try {
493
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
-				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
-					$this->logger->logException($e);
497
-				}
498
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
-			}
500
-		}
501
-
502
-		return $result;
503
-	}
504
-
505
-	/**
506
-	 * calculate the unencrypted size
507
-	 *
508
-	 * @param string $path internal path relative to the storage root
509
-	 * @param int $size size of the physical file
510
-	 * @param int $unencryptedSize size of the unencrypted file
511
-	 *
512
-	 * @return int calculated unencrypted size
513
-	 */
514
-	protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
-
516
-		$headerSize = $this->getHeaderSize($path);
517
-		$header = $this->getHeader($path);
518
-		$encryptionModule = $this->getEncryptionModule($path);
519
-
520
-		$stream = $this->storage->fopen($path, 'r');
521
-
522
-		// if we couldn't open the file we return the old unencrypted size
523
-		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
-			return $unencryptedSize;
526
-		}
527
-
528
-		$newUnencryptedSize = 0;
529
-		$size -= $headerSize;
530
-		$blockSize = $this->util->getBlockSize();
531
-
532
-		// if a header exists we skip it
533
-		if ($headerSize > 0) {
534
-			fread($stream, $headerSize);
535
-		}
536
-
537
-		// fast path, else the calculation for $lastChunkNr is bogus
538
-		if ($size === 0) {
539
-			return 0;
540
-		}
541
-
542
-		$signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
-
545
-		// calculate last chunk nr
546
-		// next highest is end of chunks, one subtracted is last one
547
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548
-
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
550
-		// calculate last chunk position
551
-		$lastChunkPos = ($lastChunkNr * $blockSize);
552
-		// try to fseek to the last chunk, if it fails we have to read the whole file
553
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
-		}
556
-
557
-		$lastChunkContentEncrypted='';
558
-		$count = $blockSize;
559
-
560
-		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
563
-			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
-				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
-			}
568
-		}
569
-
570
-		fclose($stream);
571
-
572
-		// we have to decrypt the last chunk to get it actual size
573
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
-
577
-		// calc the real file size with the size of the last chunk
578
-		$newUnencryptedSize += strlen($decryptedLastChunk);
579
-
580
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
-
582
-		// write to cache if applicable
583
-		$cache = $this->storage->getCache();
584
-		if ($cache) {
585
-			$entry = $cache->get($path);
586
-			$cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
-		}
588
-
589
-		return $newUnencryptedSize;
590
-	}
591
-
592
-	/**
593
-	 * @param Storage $sourceStorage
594
-	 * @param string $sourceInternalPath
595
-	 * @param string $targetInternalPath
596
-	 * @param bool $preserveMtime
597
-	 * @return bool
598
-	 */
599
-	public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
-		if ($sourceStorage === $this) {
601
-			return $this->rename($sourceInternalPath, $targetInternalPath);
602
-		}
603
-
604
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
607
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
-		// - remove $this->copyBetweenStorage
609
-
610
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
-			return false;
612
-		}
613
-
614
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
-		if ($result) {
616
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
617
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
618
-			} else {
619
-				$result &= $sourceStorage->unlink($sourceInternalPath);
620
-			}
621
-		}
622
-		return $result;
623
-	}
624
-
625
-
626
-	/**
627
-	 * @param Storage $sourceStorage
628
-	 * @param string $sourceInternalPath
629
-	 * @param string $targetInternalPath
630
-	 * @param bool $preserveMtime
631
-	 * @param bool $isRename
632
-	 * @return bool
633
-	 */
634
-	public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
-
636
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
639
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
-		// - remove $this->copyBetweenStorage
641
-
642
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
-	}
644
-
645
-	/**
646
-	 * Update the encrypted cache version in the database
647
-	 *
648
-	 * @param Storage $sourceStorage
649
-	 * @param string $sourceInternalPath
650
-	 * @param string $targetInternalPath
651
-	 * @param bool $isRename
652
-	 */
653
-	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->mount->getOption('encrypt', true) ? 1 : 0;
655
-		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
657
-		];
658
-		if($isEncrypted === 1) {
659
-			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
-
661
-			// In case of a move operation from an unencrypted to an encrypted
662
-			// storage the old encrypted version would stay with "0" while the
663
-			// correct value would be "1". Thus we manually set the value to "1"
664
-			// for those cases.
665
-			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
667
-				$encryptedVersion = 1;
668
-			}
669
-
670
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
671
-		}
672
-
673
-		// in case of a rename we need to manipulate the source cache because
674
-		// this information will be kept for the new target
675
-		if ($isRename) {
676
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
-		} else {
678
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
679
-		}
680
-	}
681
-
682
-	/**
683
-	 * copy file between two storages
684
-	 *
685
-	 * @param Storage $sourceStorage
686
-	 * @param string $sourceInternalPath
687
-	 * @param string $targetInternalPath
688
-	 * @param bool $preserveMtime
689
-	 * @param bool $isRename
690
-	 * @return bool
691
-	 * @throws \Exception
692
-	 */
693
-	private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
-
695
-		// for versions we have nothing to do, because versions should always use the
696
-		// key from the original file. Just create a 1:1 copy and done
697
-		if ($this->isVersion($targetInternalPath) ||
698
-			$this->isVersion($sourceInternalPath)) {
699
-			// remember that we try to create a version so that we can detect it during
700
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
701
-			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
-			if ($result) {
706
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
-				// make sure that we update the unencrypted size for the version
708
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
-					$this->updateUnencryptedSize(
710
-						$this->getFullPath($targetInternalPath),
711
-						$info['size']
712
-					);
713
-				}
714
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
-			}
716
-			return $result;
717
-		}
718
-
719
-		// first copy the keys that we reuse the existing file key on the target location
720
-		// and don't create a new one which would break versions for example.
721
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
-		if (count($mount) === 1) {
723
-			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
725
-			$target = $this->getFullPath($targetInternalPath);
726
-			$this->copyKeys($source, $target);
727
-		} else {
728
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
-		}
730
-
731
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
732
-			$dh = $sourceStorage->opendir($sourceInternalPath);
733
-			$result = $this->mkdir($targetInternalPath);
734
-			if (is_resource($dh)) {
735
-				while ($result and ($file = readdir($dh)) !== false) {
736
-					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
-					}
739
-				}
740
-			}
741
-		} else {
742
-			try {
743
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
-				$target = $this->fopen($targetInternalPath, 'w');
745
-				list(, $result) = \OC_Helper::streamCopy($source, $target);
746
-				fclose($source);
747
-				fclose($target);
748
-			} catch (\Exception $e) {
749
-				fclose($source);
750
-				fclose($target);
751
-				throw $e;
752
-			}
753
-			if($result) {
754
-				if ($preserveMtime) {
755
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
-				}
757
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
-			} else {
759
-				// delete partially written target file
760
-				$this->unlink($targetInternalPath);
761
-				// delete cache entry that was created by fopen
762
-				$this->getCache()->remove($targetInternalPath);
763
-			}
764
-		}
765
-		return (bool)$result;
766
-
767
-	}
768
-
769
-	/**
770
-	 * get the path to a local version of the file.
771
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
772
-	 *
773
-	 * @param string $path
774
-	 * @return string
775
-	 */
776
-	public function getLocalFile($path) {
777
-		if ($this->encryptionManager->isEnabled()) {
778
-			$cachedFile = $this->getCachedFile($path);
779
-			if (is_string($cachedFile)) {
780
-				return $cachedFile;
781
-			}
782
-		}
783
-		return $this->storage->getLocalFile($path);
784
-	}
785
-
786
-	/**
787
-	 * Returns the wrapped storage's value for isLocal()
788
-	 *
789
-	 * @return bool wrapped storage's isLocal() value
790
-	 */
791
-	public function isLocal() {
792
-		if ($this->encryptionManager->isEnabled()) {
793
-			return false;
794
-		}
795
-		return $this->storage->isLocal();
796
-	}
797
-
798
-	/**
799
-	 * see http://php.net/manual/en/function.stat.php
800
-	 * only the following keys are required in the result: size and mtime
801
-	 *
802
-	 * @param string $path
803
-	 * @return array
804
-	 */
805
-	public function stat($path) {
806
-		$stat = $this->storage->stat($path);
807
-		$fileSize = $this->filesize($path);
808
-		$stat['size'] = $fileSize;
809
-		$stat[7] = $fileSize;
810
-		return $stat;
811
-	}
812
-
813
-	/**
814
-	 * see http://php.net/manual/en/function.hash.php
815
-	 *
816
-	 * @param string $type
817
-	 * @param string $path
818
-	 * @param bool $raw
819
-	 * @return string
820
-	 */
821
-	public function hash($type, $path, $raw = false) {
822
-		$fh = $this->fopen($path, 'rb');
823
-		$ctx = hash_init($type);
824
-		hash_update_stream($ctx, $fh);
825
-		fclose($fh);
826
-		return hash_final($ctx, $raw);
827
-	}
828
-
829
-	/**
830
-	 * return full path, including mount point
831
-	 *
832
-	 * @param string $path relative to mount point
833
-	 * @return string full path including mount point
834
-	 */
835
-	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
-	}
838
-
839
-	/**
840
-	 * read first block of encrypted file, typically this will contain the
841
-	 * encryption header
842
-	 *
843
-	 * @param string $path
844
-	 * @return string
845
-	 */
846
-	protected function readFirstBlock($path) {
847
-		$firstBlock = '';
848
-		if ($this->storage->file_exists($path)) {
849
-			$handle = $this->storage->fopen($path, 'r');
850
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
851
-			fclose($handle);
852
-		}
853
-		return $firstBlock;
854
-	}
855
-
856
-	/**
857
-	 * return header size of given file
858
-	 *
859
-	 * @param string $path
860
-	 * @return int
861
-	 */
862
-	protected function getHeaderSize($path) {
863
-		$headerSize = 0;
864
-		$realFile = $this->util->stripPartialFileExtension($path);
865
-		if ($this->storage->file_exists($realFile)) {
866
-			$path = $realFile;
867
-		}
868
-		$firstBlock = $this->readFirstBlock($path);
869
-
870
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
-			$headerSize = strlen($firstBlock);
872
-		}
873
-
874
-		return $headerSize;
875
-	}
876
-
877
-	/**
878
-	 * parse raw header to array
879
-	 *
880
-	 * @param string $rawHeader
881
-	 * @return array
882
-	 */
883
-	protected function parseRawHeader($rawHeader) {
884
-		$result = array();
885
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
-			$header = $rawHeader;
887
-			$endAt = strpos($header, Util::HEADER_END);
888
-			if ($endAt !== false) {
889
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
-
891
-				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
-
894
-				$element = array_shift($exploded);
895
-				while ($element !== Util::HEADER_END) {
896
-					$result[$element] = array_shift($exploded);
897
-					$element = array_shift($exploded);
898
-				}
899
-			}
900
-		}
901
-
902
-		return $result;
903
-	}
904
-
905
-	/**
906
-	 * read header from file
907
-	 *
908
-	 * @param string $path
909
-	 * @return array
910
-	 */
911
-	protected function getHeader($path) {
912
-		$realFile = $this->util->stripPartialFileExtension($path);
913
-		if ($this->storage->file_exists($realFile)) {
914
-			$path = $realFile;
915
-		}
916
-
917
-		$firstBlock = $this->readFirstBlock($path);
918
-		$result = $this->parseRawHeader($firstBlock);
919
-
920
-		// if the header doesn't contain a encryption module we check if it is a
921
-		// legacy file. If true, we add the default encryption module
922
-		if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
-			if (!empty($result)) {
924
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
-			} else {
926
-				// if the header was empty we have to check first if it is a encrypted file at all
927
-				$info = $this->getCache()->get($path);
928
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
-					$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
-				}
931
-			}
932
-		}
933
-
934
-		return $result;
935
-	}
936
-
937
-	/**
938
-	 * read encryption module needed to read/write the file located at $path
939
-	 *
940
-	 * @param string $path
941
-	 * @return null|\OCP\Encryption\IEncryptionModule
942
-	 * @throws ModuleDoesNotExistsException
943
-	 * @throws \Exception
944
-	 */
945
-	protected function getEncryptionModule($path) {
946
-		$encryptionModule = null;
947
-		$header = $this->getHeader($path);
948
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
-		if (!empty($encryptionModuleId)) {
950
-			try {
951
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
-			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
-				throw $e;
955
-			}
956
-		}
957
-		return $encryptionModule;
958
-	}
959
-
960
-	/**
961
-	 * @param string $path
962
-	 * @param int $unencryptedSize
963
-	 */
964
-	public function updateUnencryptedSize($path, $unencryptedSize) {
965
-		$this->unencryptedSize[$path] = $unencryptedSize;
966
-	}
967
-
968
-	/**
969
-	 * copy keys to new location
970
-	 *
971
-	 * @param string $source path relative to data/
972
-	 * @param string $target path relative to data/
973
-	 * @return bool
974
-	 */
975
-	protected function copyKeys($source, $target) {
976
-		if (!$this->util->isExcluded($source)) {
977
-			return $this->keyStorage->copyKeys($source, $target);
978
-		}
979
-
980
-		return false;
981
-	}
982
-
983
-	/**
984
-	 * check if path points to a files version
985
-	 *
986
-	 * @param $path
987
-	 * @return bool
988
-	 */
989
-	protected function isVersion($path) {
990
-		$normalized = Filesystem::normalizePath($path);
991
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
992
-	}
49
+    use LocalTempFileTrait;
50
+
51
+    /** @var string */
52
+    private $mountPoint;
53
+
54
+    /** @var \OC\Encryption\Util */
55
+    private $util;
56
+
57
+    /** @var \OCP\Encryption\IManager */
58
+    private $encryptionManager;
59
+
60
+    /** @var \OCP\ILogger */
61
+    private $logger;
62
+
63
+    /** @var string */
64
+    private $uid;
65
+
66
+    /** @var array */
67
+    protected $unencryptedSize;
68
+
69
+    /** @var \OCP\Encryption\IFile */
70
+    private $fileHelper;
71
+
72
+    /** @var IMountPoint */
73
+    private $mount;
74
+
75
+    /** @var IStorage */
76
+    private $keyStorage;
77
+
78
+    /** @var Update */
79
+    private $update;
80
+
81
+    /** @var Manager */
82
+    private $mountManager;
83
+
84
+    /** @var array remember for which path we execute the repair step to avoid recursions */
85
+    private $fixUnencryptedSizeOf = array();
86
+
87
+    /** @var  ArrayCache */
88
+    private $arrayCache;
89
+
90
+    /**
91
+     * @param array $parameters
92
+     * @param IManager $encryptionManager
93
+     * @param Util $util
94
+     * @param ILogger $logger
95
+     * @param IFile $fileHelper
96
+     * @param string $uid
97
+     * @param IStorage $keyStorage
98
+     * @param Update $update
99
+     * @param Manager $mountManager
100
+     * @param ArrayCache $arrayCache
101
+     */
102
+    public function __construct(
103
+            $parameters,
104
+            IManager $encryptionManager = null,
105
+            Util $util = null,
106
+            ILogger $logger = null,
107
+            IFile $fileHelper = null,
108
+            $uid = null,
109
+            IStorage $keyStorage = null,
110
+            Update $update = null,
111
+            Manager $mountManager = null,
112
+            ArrayCache $arrayCache = null
113
+        ) {
114
+
115
+        $this->mountPoint = $parameters['mountPoint'];
116
+        $this->mount = $parameters['mount'];
117
+        $this->encryptionManager = $encryptionManager;
118
+        $this->util = $util;
119
+        $this->logger = $logger;
120
+        $this->uid = $uid;
121
+        $this->fileHelper = $fileHelper;
122
+        $this->keyStorage = $keyStorage;
123
+        $this->unencryptedSize = array();
124
+        $this->update = $update;
125
+        $this->mountManager = $mountManager;
126
+        $this->arrayCache = $arrayCache;
127
+        parent::__construct($parameters);
128
+    }
129
+
130
+    /**
131
+     * see http://php.net/manual/en/function.filesize.php
132
+     * The result for filesize when called on a folder is required to be 0
133
+     *
134
+     * @param string $path
135
+     * @return int
136
+     */
137
+    public function filesize($path) {
138
+        $fullPath = $this->getFullPath($path);
139
+
140
+        /** @var CacheEntry $info */
141
+        $info = $this->getCache()->get($path);
142
+        if (isset($this->unencryptedSize[$fullPath])) {
143
+            $size = $this->unencryptedSize[$fullPath];
144
+            // update file cache
145
+            if ($info instanceof ICacheEntry) {
146
+                $info = $info->getData();
147
+                $info['encrypted'] = $info['encryptedVersion'];
148
+            } else {
149
+                if (!is_array($info)) {
150
+                    $info = [];
151
+                }
152
+                $info['encrypted'] = true;
153
+            }
154
+
155
+            $info['size'] = $size;
156
+            $this->getCache()->put($path, $info);
157
+
158
+            return $size;
159
+        }
160
+
161
+        if (isset($info['fileid']) && $info['encrypted']) {
162
+            return $this->verifyUnencryptedSize($path, $info['size']);
163
+        }
164
+
165
+        return $this->storage->filesize($path);
166
+    }
167
+
168
+    /**
169
+     * @param string $path
170
+     * @return array
171
+     */
172
+    public function getMetaData($path) {
173
+        $data = $this->storage->getMetaData($path);
174
+        if (is_null($data)) {
175
+            return null;
176
+        }
177
+        $fullPath = $this->getFullPath($path);
178
+        $info = $this->getCache()->get($path);
179
+
180
+        if (isset($this->unencryptedSize[$fullPath])) {
181
+            $data['encrypted'] = true;
182
+            $data['size'] = $this->unencryptedSize[$fullPath];
183
+        } else {
184
+            if (isset($info['fileid']) && $info['encrypted']) {
185
+                $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
186
+                $data['encrypted'] = true;
187
+            }
188
+        }
189
+
190
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
191
+            $data['encryptedVersion'] = $info['encryptedVersion'];
192
+        }
193
+
194
+        return $data;
195
+    }
196
+
197
+    /**
198
+     * see http://php.net/manual/en/function.file_get_contents.php
199
+     *
200
+     * @param string $path
201
+     * @return string
202
+     */
203
+    public function file_get_contents($path) {
204
+
205
+        $encryptionModule = $this->getEncryptionModule($path);
206
+
207
+        if ($encryptionModule) {
208
+            $handle = $this->fopen($path, "r");
209
+            if (!$handle) {
210
+                return false;
211
+            }
212
+            $data = stream_get_contents($handle);
213
+            fclose($handle);
214
+            return $data;
215
+        }
216
+        return $this->storage->file_get_contents($path);
217
+    }
218
+
219
+    /**
220
+     * see http://php.net/manual/en/function.file_put_contents.php
221
+     *
222
+     * @param string $path
223
+     * @param string $data
224
+     * @return bool
225
+     */
226
+    public function file_put_contents($path, $data) {
227
+        // file put content will always be translated to a stream write
228
+        $handle = $this->fopen($path, 'w');
229
+        if (is_resource($handle)) {
230
+            $written = fwrite($handle, $data);
231
+            fclose($handle);
232
+            return $written;
233
+        }
234
+
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * see http://php.net/manual/en/function.unlink.php
240
+     *
241
+     * @param string $path
242
+     * @return bool
243
+     */
244
+    public function unlink($path) {
245
+        $fullPath = $this->getFullPath($path);
246
+        if ($this->util->isExcluded($fullPath)) {
247
+            return $this->storage->unlink($path);
248
+        }
249
+
250
+        $encryptionModule = $this->getEncryptionModule($path);
251
+        if ($encryptionModule) {
252
+            $this->keyStorage->deleteAllFileKeys($this->getFullPath($path));
253
+        }
254
+
255
+        return $this->storage->unlink($path);
256
+    }
257
+
258
+    /**
259
+     * see http://php.net/manual/en/function.rename.php
260
+     *
261
+     * @param string $path1
262
+     * @param string $path2
263
+     * @return bool
264
+     */
265
+    public function rename($path1, $path2) {
266
+
267
+        $result = $this->storage->rename($path1, $path2);
268
+
269
+        if ($result &&
270
+            // versions always use the keys from the original file, so we can skip
271
+            // this step for versions
272
+            $this->isVersion($path2) === false &&
273
+            $this->encryptionManager->isEnabled()) {
274
+            $source = $this->getFullPath($path1);
275
+            if (!$this->util->isExcluded($source)) {
276
+                $target = $this->getFullPath($path2);
277
+                if (isset($this->unencryptedSize[$source])) {
278
+                    $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
279
+                }
280
+                $this->keyStorage->renameKeys($source, $target);
281
+                $module = $this->getEncryptionModule($path2);
282
+                if ($module) {
283
+                    $module->update($target, $this->uid, []);
284
+                }
285
+            }
286
+        }
287
+
288
+        return $result;
289
+    }
290
+
291
+    /**
292
+     * see http://php.net/manual/en/function.rmdir.php
293
+     *
294
+     * @param string $path
295
+     * @return bool
296
+     */
297
+    public function rmdir($path) {
298
+        $result = $this->storage->rmdir($path);
299
+        $fullPath = $this->getFullPath($path);
300
+        if ($result &&
301
+            $this->util->isExcluded($fullPath) === false &&
302
+            $this->encryptionManager->isEnabled()
303
+        ) {
304
+            $this->keyStorage->deleteAllFileKeys($fullPath);
305
+        }
306
+
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * check if a file can be read
312
+     *
313
+     * @param string $path
314
+     * @return bool
315
+     */
316
+    public function isReadable($path) {
317
+
318
+        $isReadable = true;
319
+
320
+        $metaData = $this->getMetaData($path);
321
+        if (
322
+            !$this->is_dir($path) &&
323
+            isset($metaData['encrypted']) &&
324
+            $metaData['encrypted'] === true
325
+        ) {
326
+            $fullPath = $this->getFullPath($path);
327
+            $module = $this->getEncryptionModule($path);
328
+            $isReadable = $module->isReadable($fullPath, $this->uid);
329
+        }
330
+
331
+        return $this->storage->isReadable($path) && $isReadable;
332
+    }
333
+
334
+    /**
335
+     * see http://php.net/manual/en/function.copy.php
336
+     *
337
+     * @param string $path1
338
+     * @param string $path2
339
+     * @return bool
340
+     */
341
+    public function copy($path1, $path2) {
342
+
343
+        $source = $this->getFullPath($path1);
344
+
345
+        if ($this->util->isExcluded($source)) {
346
+            return $this->storage->copy($path1, $path2);
347
+        }
348
+
349
+        // need to stream copy file by file in case we copy between a encrypted
350
+        // and a unencrypted storage
351
+        $this->unlink($path2);
352
+        $result = $this->copyFromStorage($this, $path1, $path2);
353
+
354
+        return $result;
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') ? true : false;
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->warning('Encryption module "' . $encryptionModuleId .
443
+                    '" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
444
+            }
445
+
446
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
447
+            if (!$encryptionEnabled || !$this->mount->getOption('encrypt', true)) {
448
+                if (!$targetExists || !$targetIsEncrypted) {
449
+                    $shouldEncrypt = false;
450
+                }
451
+            }
452
+
453
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
454
+                $headerSize = $this->getHeaderSize($path);
455
+                $source = $this->storage->fopen($path, $mode);
456
+                if (!is_resource($source)) {
457
+                    return false;
458
+                }
459
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
460
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
461
+                    $size, $unencryptedSize, $headerSize, $signed);
462
+                return $handle;
463
+            }
464
+
465
+        }
466
+
467
+        return $this->storage->fopen($path, $mode);
468
+    }
469
+
470
+
471
+    /**
472
+     * perform some plausibility checks if the the unencrypted size is correct.
473
+     * If not, we calculate the correct unencrypted size and return it
474
+     *
475
+     * @param string $path internal path relative to the storage root
476
+     * @param int $unencryptedSize size of the unencrypted file
477
+     *
478
+     * @return int unencrypted size
479
+     */
480
+    protected function verifyUnencryptedSize($path, $unencryptedSize) {
481
+
482
+        $size = $this->storage->filesize($path);
483
+        $result = $unencryptedSize;
484
+
485
+        if ($unencryptedSize < 0 ||
486
+            ($size > 0 && $unencryptedSize === $size)
487
+        ) {
488
+            // check if we already calculate the unencrypted size for the
489
+            // given path to avoid recursions
490
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
491
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
492
+                try {
493
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494
+                } catch (\Exception $e) {
495
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
496
+                    $this->logger->logException($e);
497
+                }
498
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
499
+            }
500
+        }
501
+
502
+        return $result;
503
+    }
504
+
505
+    /**
506
+     * calculate the unencrypted size
507
+     *
508
+     * @param string $path internal path relative to the storage root
509
+     * @param int $size size of the physical file
510
+     * @param int $unencryptedSize size of the unencrypted file
511
+     *
512
+     * @return int calculated unencrypted size
513
+     */
514
+    protected function fixUnencryptedSize($path, $size, $unencryptedSize) {
515
+
516
+        $headerSize = $this->getHeaderSize($path);
517
+        $header = $this->getHeader($path);
518
+        $encryptionModule = $this->getEncryptionModule($path);
519
+
520
+        $stream = $this->storage->fopen($path, 'r');
521
+
522
+        // if we couldn't open the file we return the old unencrypted size
523
+        if (!is_resource($stream)) {
524
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
525
+            return $unencryptedSize;
526
+        }
527
+
528
+        $newUnencryptedSize = 0;
529
+        $size -= $headerSize;
530
+        $blockSize = $this->util->getBlockSize();
531
+
532
+        // if a header exists we skip it
533
+        if ($headerSize > 0) {
534
+            fread($stream, $headerSize);
535
+        }
536
+
537
+        // fast path, else the calculation for $lastChunkNr is bogus
538
+        if ($size === 0) {
539
+            return 0;
540
+        }
541
+
542
+        $signed = (isset($header['signed']) && $header['signed'] === 'true') ? true : false;
543
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
544
+
545
+        // calculate last chunk nr
546
+        // next highest is end of chunks, one subtracted is last one
547
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
548
+
549
+        $lastChunkNr = ceil($size/ $blockSize)-1;
550
+        // calculate last chunk position
551
+        $lastChunkPos = ($lastChunkNr * $blockSize);
552
+        // try to fseek to the last chunk, if it fails we have to read the whole file
553
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
554
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555
+        }
556
+
557
+        $lastChunkContentEncrypted='';
558
+        $count = $blockSize;
559
+
560
+        while ($count > 0) {
561
+            $data=fread($stream, $blockSize);
562
+            $count=strlen($data);
563
+            $lastChunkContentEncrypted .= $data;
564
+            if(strlen($lastChunkContentEncrypted) > $blockSize) {
565
+                $newUnencryptedSize += $unencryptedBlockSize;
566
+                $lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
567
+            }
568
+        }
569
+
570
+        fclose($stream);
571
+
572
+        // we have to decrypt the last chunk to get it actual size
573
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
576
+
577
+        // calc the real file size with the size of the last chunk
578
+        $newUnencryptedSize += strlen($decryptedLastChunk);
579
+
580
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
581
+
582
+        // write to cache if applicable
583
+        $cache = $this->storage->getCache();
584
+        if ($cache) {
585
+            $entry = $cache->get($path);
586
+            $cache->update($entry['fileid'], ['size' => $newUnencryptedSize]);
587
+        }
588
+
589
+        return $newUnencryptedSize;
590
+    }
591
+
592
+    /**
593
+     * @param Storage $sourceStorage
594
+     * @param string $sourceInternalPath
595
+     * @param string $targetInternalPath
596
+     * @param bool $preserveMtime
597
+     * @return bool
598
+     */
599
+    public function moveFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
600
+        if ($sourceStorage === $this) {
601
+            return $this->rename($sourceInternalPath, $targetInternalPath);
602
+        }
603
+
604
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
605
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
606
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
607
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
608
+        // - remove $this->copyBetweenStorage
609
+
610
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
611
+            return false;
612
+        }
613
+
614
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
615
+        if ($result) {
616
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
617
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
618
+            } else {
619
+                $result &= $sourceStorage->unlink($sourceInternalPath);
620
+            }
621
+        }
622
+        return $result;
623
+    }
624
+
625
+
626
+    /**
627
+     * @param Storage $sourceStorage
628
+     * @param string $sourceInternalPath
629
+     * @param string $targetInternalPath
630
+     * @param bool $preserveMtime
631
+     * @param bool $isRename
632
+     * @return bool
633
+     */
634
+    public function copyFromStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
635
+
636
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
637
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
638
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
639
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
640
+        // - remove $this->copyBetweenStorage
641
+
642
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
643
+    }
644
+
645
+    /**
646
+     * Update the encrypted cache version in the database
647
+     *
648
+     * @param Storage $sourceStorage
649
+     * @param string $sourceInternalPath
650
+     * @param string $targetInternalPath
651
+     * @param bool $isRename
652
+     */
653
+    private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->mount->getOption('encrypt', true) ? 1 : 0;
655
+        $cacheInformation = [
656
+            'encrypted' => (bool)$isEncrypted,
657
+        ];
658
+        if($isEncrypted === 1) {
659
+            $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660
+
661
+            // In case of a move operation from an unencrypted to an encrypted
662
+            // storage the old encrypted version would stay with "0" while the
663
+            // correct value would be "1". Thus we manually set the value to "1"
664
+            // for those cases.
665
+            // See also https://github.com/owncloud/core/issues/23078
666
+            if($encryptedVersion === 0) {
667
+                $encryptedVersion = 1;
668
+            }
669
+
670
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
671
+        }
672
+
673
+        // in case of a rename we need to manipulate the source cache because
674
+        // this information will be kept for the new target
675
+        if ($isRename) {
676
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
677
+        } else {
678
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
679
+        }
680
+    }
681
+
682
+    /**
683
+     * copy file between two storages
684
+     *
685
+     * @param Storage $sourceStorage
686
+     * @param string $sourceInternalPath
687
+     * @param string $targetInternalPath
688
+     * @param bool $preserveMtime
689
+     * @param bool $isRename
690
+     * @return bool
691
+     * @throws \Exception
692
+     */
693
+    private function copyBetweenStorage(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
694
+
695
+        // for versions we have nothing to do, because versions should always use the
696
+        // key from the original file. Just create a 1:1 copy and done
697
+        if ($this->isVersion($targetInternalPath) ||
698
+            $this->isVersion($sourceInternalPath)) {
699
+            // remember that we try to create a version so that we can detect it during
700
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
701
+            // create a 1:1 copy of the file
702
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
703
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
705
+            if ($result) {
706
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707
+                // make sure that we update the unencrypted size for the version
708
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
709
+                    $this->updateUnencryptedSize(
710
+                        $this->getFullPath($targetInternalPath),
711
+                        $info['size']
712
+                    );
713
+                }
714
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
715
+            }
716
+            return $result;
717
+        }
718
+
719
+        // first copy the keys that we reuse the existing file key on the target location
720
+        // and don't create a new one which would break versions for example.
721
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722
+        if (count($mount) === 1) {
723
+            $mountPoint = $mount[0]->getMountPoint();
724
+            $source = $mountPoint . '/' . $sourceInternalPath;
725
+            $target = $this->getFullPath($targetInternalPath);
726
+            $this->copyKeys($source, $target);
727
+        } else {
728
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
729
+        }
730
+
731
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
732
+            $dh = $sourceStorage->opendir($sourceInternalPath);
733
+            $result = $this->mkdir($targetInternalPath);
734
+            if (is_resource($dh)) {
735
+                while ($result and ($file = readdir($dh)) !== false) {
736
+                    if (!Filesystem::isIgnoredDir($file)) {
737
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
738
+                    }
739
+                }
740
+            }
741
+        } else {
742
+            try {
743
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
744
+                $target = $this->fopen($targetInternalPath, 'w');
745
+                list(, $result) = \OC_Helper::streamCopy($source, $target);
746
+                fclose($source);
747
+                fclose($target);
748
+            } catch (\Exception $e) {
749
+                fclose($source);
750
+                fclose($target);
751
+                throw $e;
752
+            }
753
+            if($result) {
754
+                if ($preserveMtime) {
755
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756
+                }
757
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename);
758
+            } else {
759
+                // delete partially written target file
760
+                $this->unlink($targetInternalPath);
761
+                // delete cache entry that was created by fopen
762
+                $this->getCache()->remove($targetInternalPath);
763
+            }
764
+        }
765
+        return (bool)$result;
766
+
767
+    }
768
+
769
+    /**
770
+     * get the path to a local version of the file.
771
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
772
+     *
773
+     * @param string $path
774
+     * @return string
775
+     */
776
+    public function getLocalFile($path) {
777
+        if ($this->encryptionManager->isEnabled()) {
778
+            $cachedFile = $this->getCachedFile($path);
779
+            if (is_string($cachedFile)) {
780
+                return $cachedFile;
781
+            }
782
+        }
783
+        return $this->storage->getLocalFile($path);
784
+    }
785
+
786
+    /**
787
+     * Returns the wrapped storage's value for isLocal()
788
+     *
789
+     * @return bool wrapped storage's isLocal() value
790
+     */
791
+    public function isLocal() {
792
+        if ($this->encryptionManager->isEnabled()) {
793
+            return false;
794
+        }
795
+        return $this->storage->isLocal();
796
+    }
797
+
798
+    /**
799
+     * see http://php.net/manual/en/function.stat.php
800
+     * only the following keys are required in the result: size and mtime
801
+     *
802
+     * @param string $path
803
+     * @return array
804
+     */
805
+    public function stat($path) {
806
+        $stat = $this->storage->stat($path);
807
+        $fileSize = $this->filesize($path);
808
+        $stat['size'] = $fileSize;
809
+        $stat[7] = $fileSize;
810
+        return $stat;
811
+    }
812
+
813
+    /**
814
+     * see http://php.net/manual/en/function.hash.php
815
+     *
816
+     * @param string $type
817
+     * @param string $path
818
+     * @param bool $raw
819
+     * @return string
820
+     */
821
+    public function hash($type, $path, $raw = false) {
822
+        $fh = $this->fopen($path, 'rb');
823
+        $ctx = hash_init($type);
824
+        hash_update_stream($ctx, $fh);
825
+        fclose($fh);
826
+        return hash_final($ctx, $raw);
827
+    }
828
+
829
+    /**
830
+     * return full path, including mount point
831
+     *
832
+     * @param string $path relative to mount point
833
+     * @return string full path including mount point
834
+     */
835
+    protected function getFullPath($path) {
836
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
837
+    }
838
+
839
+    /**
840
+     * read first block of encrypted file, typically this will contain the
841
+     * encryption header
842
+     *
843
+     * @param string $path
844
+     * @return string
845
+     */
846
+    protected function readFirstBlock($path) {
847
+        $firstBlock = '';
848
+        if ($this->storage->file_exists($path)) {
849
+            $handle = $this->storage->fopen($path, 'r');
850
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
851
+            fclose($handle);
852
+        }
853
+        return $firstBlock;
854
+    }
855
+
856
+    /**
857
+     * return header size of given file
858
+     *
859
+     * @param string $path
860
+     * @return int
861
+     */
862
+    protected function getHeaderSize($path) {
863
+        $headerSize = 0;
864
+        $realFile = $this->util->stripPartialFileExtension($path);
865
+        if ($this->storage->file_exists($realFile)) {
866
+            $path = $realFile;
867
+        }
868
+        $firstBlock = $this->readFirstBlock($path);
869
+
870
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
871
+            $headerSize = strlen($firstBlock);
872
+        }
873
+
874
+        return $headerSize;
875
+    }
876
+
877
+    /**
878
+     * parse raw header to array
879
+     *
880
+     * @param string $rawHeader
881
+     * @return array
882
+     */
883
+    protected function parseRawHeader($rawHeader) {
884
+        $result = array();
885
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
886
+            $header = $rawHeader;
887
+            $endAt = strpos($header, Util::HEADER_END);
888
+            if ($endAt !== false) {
889
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890
+
891
+                // +1 to not start with an ':' which would result in empty element at the beginning
892
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
893
+
894
+                $element = array_shift($exploded);
895
+                while ($element !== Util::HEADER_END) {
896
+                    $result[$element] = array_shift($exploded);
897
+                    $element = array_shift($exploded);
898
+                }
899
+            }
900
+        }
901
+
902
+        return $result;
903
+    }
904
+
905
+    /**
906
+     * read header from file
907
+     *
908
+     * @param string $path
909
+     * @return array
910
+     */
911
+    protected function getHeader($path) {
912
+        $realFile = $this->util->stripPartialFileExtension($path);
913
+        if ($this->storage->file_exists($realFile)) {
914
+            $path = $realFile;
915
+        }
916
+
917
+        $firstBlock = $this->readFirstBlock($path);
918
+        $result = $this->parseRawHeader($firstBlock);
919
+
920
+        // if the header doesn't contain a encryption module we check if it is a
921
+        // legacy file. If true, we add the default encryption module
922
+        if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
923
+            if (!empty($result)) {
924
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
925
+            } else {
926
+                // if the header was empty we have to check first if it is a encrypted file at all
927
+                $info = $this->getCache()->get($path);
928
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
929
+                    $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
930
+                }
931
+            }
932
+        }
933
+
934
+        return $result;
935
+    }
936
+
937
+    /**
938
+     * read encryption module needed to read/write the file located at $path
939
+     *
940
+     * @param string $path
941
+     * @return null|\OCP\Encryption\IEncryptionModule
942
+     * @throws ModuleDoesNotExistsException
943
+     * @throws \Exception
944
+     */
945
+    protected function getEncryptionModule($path) {
946
+        $encryptionModule = null;
947
+        $header = $this->getHeader($path);
948
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
949
+        if (!empty($encryptionModuleId)) {
950
+            try {
951
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952
+            } catch (ModuleDoesNotExistsException $e) {
953
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
954
+                throw $e;
955
+            }
956
+        }
957
+        return $encryptionModule;
958
+    }
959
+
960
+    /**
961
+     * @param string $path
962
+     * @param int $unencryptedSize
963
+     */
964
+    public function updateUnencryptedSize($path, $unencryptedSize) {
965
+        $this->unencryptedSize[$path] = $unencryptedSize;
966
+    }
967
+
968
+    /**
969
+     * copy keys to new location
970
+     *
971
+     * @param string $source path relative to data/
972
+     * @param string $target path relative to data/
973
+     * @return bool
974
+     */
975
+    protected function copyKeys($source, $target) {
976
+        if (!$this->util->isExcluded($source)) {
977
+            return $this->keyStorage->copyKeys($source, $target);
978
+        }
979
+
980
+        return false;
981
+    }
982
+
983
+    /**
984
+     * check if path points to a files version
985
+     *
986
+     * @param $path
987
+     * @return bool
988
+     */
989
+    protected function isVersion($path) {
990
+        $normalized = Filesystem::normalizePath($path);
991
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
992
+    }
993 993
 
994 994
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 		// check if the file is stored in the array cache, this means that we
369 369
 		// copy a file over to the versions folder, in this case we don't want to
370 370
 		// decrypt it
371
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
372
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
371
+		if ($this->arrayCache->hasKey('encryption_copy_version_'.$path)) {
372
+			$this->arrayCache->remove('encryption_copy_version_'.$path);
373 373
 			return $this->storage->fopen($path, $mode);
374 374
 		}
375 375
 
@@ -439,8 +439,8 @@  discard block
 block discarded – undo
439 439
 					}
440 440
 				}
441 441
 			} catch (ModuleDoesNotExistsException $e) {
442
-				$this->logger->warning('Encryption module "' . $encryptionModuleId .
443
-					'" not found, file will be stored unencrypted (' . $e->getMessage() . ')');
442
+				$this->logger->warning('Encryption module "'.$encryptionModuleId.
443
+					'" not found, file will be stored unencrypted ('.$e->getMessage().')');
444 444
 			}
445 445
 
446 446
 			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 				try {
493 493
 					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
494 494
 				} catch (\Exception $e) {
495
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for '. $path);
495
+					$this->logger->error('Couldn\'t re-calculate unencrypted size for '.$path);
496 496
 					$this->logger->logException($e);
497 497
 				}
498 498
 				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 		// if we couldn't open the file we return the old unencrypted size
523 523
 		if (!is_resource($stream)) {
524
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
524
+			$this->logger->error('Could not open '.$path.'. Recalculation of unencrypted size aborted.');
525 525
 			return $unencryptedSize;
526 526
 		}
527 527
 
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 		// next highest is end of chunks, one subtracted is last one
547 547
 		// we have to read the last chunk, we can't just calculate it (because of padding etc)
548 548
 
549
-		$lastChunkNr = ceil($size/ $blockSize)-1;
549
+		$lastChunkNr = ceil($size / $blockSize) - 1;
550 550
 		// calculate last chunk position
551 551
 		$lastChunkPos = ($lastChunkNr * $blockSize);
552 552
 		// try to fseek to the last chunk, if it fails we have to read the whole file
@@ -554,16 +554,16 @@  discard block
 block discarded – undo
554 554
 			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
555 555
 		}
556 556
 
557
-		$lastChunkContentEncrypted='';
557
+		$lastChunkContentEncrypted = '';
558 558
 		$count = $blockSize;
559 559
 
560 560
 		while ($count > 0) {
561
-			$data=fread($stream, $blockSize);
562
-			$count=strlen($data);
561
+			$data = fread($stream, $blockSize);
562
+			$count = strlen($data);
563 563
 			$lastChunkContentEncrypted .= $data;
564
-			if(strlen($lastChunkContentEncrypted) > $blockSize) {
564
+			if (strlen($lastChunkContentEncrypted) > $blockSize) {
565 565
 				$newUnencryptedSize += $unencryptedBlockSize;
566
-				$lastChunkContentEncrypted=substr($lastChunkContentEncrypted, $blockSize);
566
+				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
567 567
 			}
568 568
 		}
569 569
 
@@ -571,8 +571,8 @@  discard block
 block discarded – undo
571 571
 
572 572
 		// we have to decrypt the last chunk to get it actual size
573 573
 		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
574
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
575
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
574
+		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr.'end');
575
+		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr.'end');
576 576
 
577 577
 		// calc the real file size with the size of the last chunk
578 578
 		$newUnencryptedSize += strlen($decryptedLastChunk);
@@ -653,9 +653,9 @@  discard block
 block discarded – undo
653 653
 	private function updateEncryptedVersion(Storage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename) {
654 654
 		$isEncrypted = $this->encryptionManager->isEnabled() && $this->mount->getOption('encrypt', true) ? 1 : 0;
655 655
 		$cacheInformation = [
656
-			'encrypted' => (bool)$isEncrypted,
656
+			'encrypted' => (bool) $isEncrypted,
657 657
 		];
658
-		if($isEncrypted === 1) {
658
+		if ($isEncrypted === 1) {
659 659
 			$encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
660 660
 
661 661
 			// In case of a move operation from an unencrypted to an encrypted
@@ -663,7 +663,7 @@  discard block
 block discarded – undo
663 663
 			// correct value would be "1". Thus we manually set the value to "1"
664 664
 			// for those cases.
665 665
 			// See also https://github.com/owncloud/core/issues/23078
666
-			if($encryptedVersion === 0) {
666
+			if ($encryptedVersion === 0) {
667 667
 				$encryptedVersion = 1;
668 668
 			}
669 669
 
@@ -699,9 +699,9 @@  discard block
 block discarded – undo
699 699
 			// remember that we try to create a version so that we can detect it during
700 700
 			// fopen($sourceInternalPath) and by-pass the encryption in order to
701 701
 			// create a 1:1 copy of the file
702
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
702
+			$this->arrayCache->set('encryption_copy_version_'.$sourceInternalPath, true);
703 703
 			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
704
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
704
+			$this->arrayCache->remove('encryption_copy_version_'.$sourceInternalPath);
705 705
 			if ($result) {
706 706
 				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
707 707
 				// make sure that we update the unencrypted size for the version
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
 		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
722 722
 		if (count($mount) === 1) {
723 723
 			$mountPoint = $mount[0]->getMountPoint();
724
-			$source = $mountPoint . '/' . $sourceInternalPath;
724
+			$source = $mountPoint.'/'.$sourceInternalPath;
725 725
 			$target = $this->getFullPath($targetInternalPath);
726 726
 			$this->copyKeys($source, $target);
727 727
 		} else {
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 			if (is_resource($dh)) {
735 735
 				while ($result and ($file = readdir($dh)) !== false) {
736 736
 					if (!Filesystem::isIgnoredDir($file)) {
737
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
737
+						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath.'/'.$file, $targetInternalPath.'/'.$file, false, $isRename);
738 738
 					}
739 739
 				}
740 740
 			}
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 				fclose($target);
751 751
 				throw $e;
752 752
 			}
753
-			if($result) {
753
+			if ($result) {
754 754
 				if ($preserveMtime) {
755 755
 					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
756 756
 				}
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 				$this->getCache()->remove($targetInternalPath);
763 763
 			}
764 764
 		}
765
-		return (bool)$result;
765
+		return (bool) $result;
766 766
 
767 767
 	}
768 768
 
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 	 * @return string full path including mount point
834 834
 	 */
835 835
 	protected function getFullPath($path) {
836
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
836
+		return Filesystem::normalizePath($this->mountPoint.'/'.$path);
837 837
 	}
838 838
 
839 839
 	/**
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
890 890
 
891 891
 				// +1 to not start with an ':' which would result in empty element at the beginning
892
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START)+1));
892
+				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
893 893
 
894 894
 				$element = array_shift($exploded);
895 895
 				while ($element !== Util::HEADER_END) {
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
 			try {
951 951
 				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
952 952
 			} catch (ModuleDoesNotExistsException $e) {
953
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
953
+				$this->logger->critical('Encryption module defined in "'.$path.'" not loaded!');
954 954
 				throw $e;
955 955
 			}
956 956
 		}
Please login to merge, or discard this patch.
lib/private/files/storage/wrapper/quota.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@
 block discarded – undo
159 159
 	 * Checks whether the given path is a part file
160 160
 	 *
161 161
 	 * @param string $path Path that may identify a .part file
162
-	 * @return string File path without .part extension
162
+	 * @return boolean File path without .part extension
163 163
 	 * @note this is needed for reusing keys
164 164
 	 */
165 165
 	private function isPartFile($path) {
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -30,172 +30,172 @@
 block discarded – undo
30 30
 
31 31
 class Quota extends Wrapper {
32 32
 
33
-	/**
34
-	 * @var int $quota
35
-	 */
36
-	protected $quota;
37
-
38
-	/**
39
-	 * @var string $sizeRoot
40
-	 */
41
-	protected $sizeRoot;
42
-
43
-	/**
44
-	 * @param array $parameters
45
-	 */
46
-	public function __construct($parameters) {
47
-		$this->storage = $parameters['storage'];
48
-		$this->quota = $parameters['quota'];
49
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
-	}
51
-
52
-	/**
53
-	 * @return int quota value
54
-	 */
55
-	public function getQuota() {
56
-		return $this->quota;
57
-	}
58
-
59
-	/**
60
-	 * @param string $path
61
-	 * @param \OC\Files\Storage\Storage $storage
62
-	 */
63
-	protected function getSize($path, $storage = null) {
64
-		if (is_null($storage)) {
65
-			$cache = $this->getCache();
66
-		} else {
67
-			$cache = $storage->getCache();
68
-		}
69
-		$data = $cache->get($path);
70
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
71
-			return $data['size'];
72
-		} else {
73
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * Get free space as limited by the quota
79
-	 *
80
-	 * @param string $path
81
-	 * @return int
82
-	 */
83
-	public function free_space($path) {
84
-		if ($this->quota < 0) {
85
-			return $this->storage->free_space($path);
86
-		} else {
87
-			$used = $this->getSize($this->sizeRoot);
88
-			if ($used < 0) {
89
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
-			} else {
91
-				$free = $this->storage->free_space($path);
92
-				$quotaFree = max($this->quota - $used, 0);
93
-				// if free space is known
94
-				if ($free >= 0) {
95
-					$free = min($free, $quotaFree);
96
-				} else {
97
-					$free = $quotaFree;
98
-				}
99
-				return $free;
100
-			}
101
-		}
102
-	}
103
-
104
-	/**
105
-	 * see http://php.net/manual/en/function.file_put_contents.php
106
-	 *
107
-	 * @param string $path
108
-	 * @param string $data
109
-	 * @return bool
110
-	 */
111
-	public function file_put_contents($path, $data) {
112
-		$free = $this->free_space('');
113
-		if ($free < 0 or strlen($data) < $free) {
114
-			return $this->storage->file_put_contents($path, $data);
115
-		} else {
116
-			return false;
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * see http://php.net/manual/en/function.copy.php
122
-	 *
123
-	 * @param string $source
124
-	 * @param string $target
125
-	 * @return bool
126
-	 */
127
-	public function copy($source, $target) {
128
-		$free = $this->free_space('');
129
-		if ($free < 0 or $this->getSize($source) < $free) {
130
-			return $this->storage->copy($source, $target);
131
-		} else {
132
-			return false;
133
-		}
134
-	}
135
-
136
-	/**
137
-	 * see http://php.net/manual/en/function.fopen.php
138
-	 *
139
-	 * @param string $path
140
-	 * @param string $mode
141
-	 * @return resource
142
-	 */
143
-	public function fopen($path, $mode) {
144
-		$source = $this->storage->fopen($path, $mode);
145
-
146
-		// don't apply quota for part files
147
-		if (!$this->isPartFile($path)) {
148
-			$free = $this->free_space('');
149
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
-				// only apply quota for files, not metadata, trash or others
151
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
-					return \OC\Files\Stream\Quota::wrap($source, $free);
153
-				}
154
-			}
155
-		}
156
-		return $source;
157
-	}
158
-
159
-	/**
160
-	 * Checks whether the given path is a part file
161
-	 *
162
-	 * @param string $path Path that may identify a .part file
163
-	 * @return string File path without .part extension
164
-	 * @note this is needed for reusing keys
165
-	 */
166
-	private function isPartFile($path) {
167
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
168
-
169
-		return ($extension === 'part');
170
-	}
171
-
172
-	/**
173
-	 * @param \OCP\Files\Storage $sourceStorage
174
-	 * @param string $sourceInternalPath
175
-	 * @param string $targetInternalPath
176
-	 * @return bool
177
-	 */
178
-	public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
-		$free = $this->free_space('');
180
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
-		} else {
183
-			return false;
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * @param \OCP\Files\Storage $sourceStorage
189
-	 * @param string $sourceInternalPath
190
-	 * @param string $targetInternalPath
191
-	 * @return bool
192
-	 */
193
-	public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
-		$free = $this->free_space('');
195
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
-		} else {
198
-			return false;
199
-		}
200
-	}
33
+    /**
34
+     * @var int $quota
35
+     */
36
+    protected $quota;
37
+
38
+    /**
39
+     * @var string $sizeRoot
40
+     */
41
+    protected $sizeRoot;
42
+
43
+    /**
44
+     * @param array $parameters
45
+     */
46
+    public function __construct($parameters) {
47
+        $this->storage = $parameters['storage'];
48
+        $this->quota = $parameters['quota'];
49
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
+    }
51
+
52
+    /**
53
+     * @return int quota value
54
+     */
55
+    public function getQuota() {
56
+        return $this->quota;
57
+    }
58
+
59
+    /**
60
+     * @param string $path
61
+     * @param \OC\Files\Storage\Storage $storage
62
+     */
63
+    protected function getSize($path, $storage = null) {
64
+        if (is_null($storage)) {
65
+            $cache = $this->getCache();
66
+        } else {
67
+            $cache = $storage->getCache();
68
+        }
69
+        $data = $cache->get($path);
70
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
71
+            return $data['size'];
72
+        } else {
73
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
+        }
75
+    }
76
+
77
+    /**
78
+     * Get free space as limited by the quota
79
+     *
80
+     * @param string $path
81
+     * @return int
82
+     */
83
+    public function free_space($path) {
84
+        if ($this->quota < 0) {
85
+            return $this->storage->free_space($path);
86
+        } else {
87
+            $used = $this->getSize($this->sizeRoot);
88
+            if ($used < 0) {
89
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
+            } else {
91
+                $free = $this->storage->free_space($path);
92
+                $quotaFree = max($this->quota - $used, 0);
93
+                // if free space is known
94
+                if ($free >= 0) {
95
+                    $free = min($free, $quotaFree);
96
+                } else {
97
+                    $free = $quotaFree;
98
+                }
99
+                return $free;
100
+            }
101
+        }
102
+    }
103
+
104
+    /**
105
+     * see http://php.net/manual/en/function.file_put_contents.php
106
+     *
107
+     * @param string $path
108
+     * @param string $data
109
+     * @return bool
110
+     */
111
+    public function file_put_contents($path, $data) {
112
+        $free = $this->free_space('');
113
+        if ($free < 0 or strlen($data) < $free) {
114
+            return $this->storage->file_put_contents($path, $data);
115
+        } else {
116
+            return false;
117
+        }
118
+    }
119
+
120
+    /**
121
+     * see http://php.net/manual/en/function.copy.php
122
+     *
123
+     * @param string $source
124
+     * @param string $target
125
+     * @return bool
126
+     */
127
+    public function copy($source, $target) {
128
+        $free = $this->free_space('');
129
+        if ($free < 0 or $this->getSize($source) < $free) {
130
+            return $this->storage->copy($source, $target);
131
+        } else {
132
+            return false;
133
+        }
134
+    }
135
+
136
+    /**
137
+     * see http://php.net/manual/en/function.fopen.php
138
+     *
139
+     * @param string $path
140
+     * @param string $mode
141
+     * @return resource
142
+     */
143
+    public function fopen($path, $mode) {
144
+        $source = $this->storage->fopen($path, $mode);
145
+
146
+        // don't apply quota for part files
147
+        if (!$this->isPartFile($path)) {
148
+            $free = $this->free_space('');
149
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
+                // only apply quota for files, not metadata, trash or others
151
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
153
+                }
154
+            }
155
+        }
156
+        return $source;
157
+    }
158
+
159
+    /**
160
+     * Checks whether the given path is a part file
161
+     *
162
+     * @param string $path Path that may identify a .part file
163
+     * @return string File path without .part extension
164
+     * @note this is needed for reusing keys
165
+     */
166
+    private function isPartFile($path) {
167
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
168
+
169
+        return ($extension === 'part');
170
+    }
171
+
172
+    /**
173
+     * @param \OCP\Files\Storage $sourceStorage
174
+     * @param string $sourceInternalPath
175
+     * @param string $targetInternalPath
176
+     * @return bool
177
+     */
178
+    public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
+        $free = $this->free_space('');
180
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
+        } else {
183
+            return false;
184
+        }
185
+    }
186
+
187
+    /**
188
+     * @param \OCP\Files\Storage $sourceStorage
189
+     * @param string $sourceInternalPath
190
+     * @param string $targetInternalPath
191
+     * @return bool
192
+     */
193
+    public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
+        $free = $this->free_space('');
195
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
+        } else {
198
+            return false;
199
+        }
200
+    }
201 201
 }
Please login to merge, or discard this patch.
lib/private/files/stream/staticstream.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -144,6 +144,9 @@
 block discarded – undo
144 144
 		return true;
145 145
 	}
146 146
 
147
+	/**
148
+	 * @param string $path
149
+	 */
147 150
 	public function url_stat($path) {
148 151
 		if (isset(self::$data[$path])) {
149 152
 			$size = strlen(self::$data[$path]);
Please login to merge, or discard this patch.
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -24,148 +24,148 @@
 block discarded – undo
24 24
 namespace OC\Files\Stream;
25 25
 
26 26
 class StaticStream {
27
-	const MODE_FILE = 0100000;
28
-
29
-	public $context;
30
-	protected static $data = array();
31
-
32
-	protected $path = '';
33
-	protected $pointer = 0;
34
-	protected $writable = false;
35
-
36
-	public function stream_close() {
37
-	}
38
-
39
-	public function stream_eof() {
40
-		return $this->pointer >= strlen(self::$data[$this->path]);
41
-	}
42
-
43
-	public function stream_flush() {
44
-	}
45
-
46
-	public static function clear() {
47
-		self::$data = array();
48
-	}
49
-
50
-	public function stream_open($path, $mode, $options, &$opened_path) {
51
-		switch ($mode[0]) {
52
-			case 'r':
53
-				if (!isset(self::$data[$path])) return false;
54
-				$this->path = $path;
55
-				$this->writable = isset($mode[1]) && $mode[1] == '+';
56
-				break;
57
-			case 'w':
58
-				self::$data[$path] = '';
59
-				$this->path = $path;
60
-				$this->writable = true;
61
-				break;
62
-			case 'a':
63
-				if (!isset(self::$data[$path])) self::$data[$path] = '';
64
-				$this->path = $path;
65
-				$this->writable = true;
66
-				$this->pointer = strlen(self::$data[$path]);
67
-				break;
68
-			case 'x':
69
-				if (isset(self::$data[$path])) return false;
70
-				$this->path = $path;
71
-				$this->writable = true;
72
-				break;
73
-			case 'c':
74
-				if (!isset(self::$data[$path])) self::$data[$path] = '';
75
-				$this->path = $path;
76
-				$this->writable = true;
77
-				break;
78
-			default:
79
-				return false;
80
-		}
81
-		$opened_path = $this->path;
82
-		return true;
83
-	}
84
-
85
-	public function stream_read($count) {
86
-		$bytes = min(strlen(self::$data[$this->path]) - $this->pointer, $count);
87
-		$data = substr(self::$data[$this->path], $this->pointer, $bytes);
88
-		$this->pointer += $bytes;
89
-		return $data;
90
-	}
91
-
92
-	public function stream_seek($offset, $whence = SEEK_SET) {
93
-		$len = strlen(self::$data[$this->path]);
94
-		switch ($whence) {
95
-			case SEEK_SET:
96
-				if ($offset <= $len) {
97
-					$this->pointer = $offset;
98
-					return true;
99
-				}
100
-				break;
101
-			case SEEK_CUR:
102
-				if ($this->pointer + $offset <= $len) {
103
-					$this->pointer += $offset;
104
-					return true;
105
-				}
106
-				break;
107
-			case SEEK_END:
108
-				if ($len + $offset <= $len) {
109
-					$this->pointer = $len + $offset;
110
-					return true;
111
-				}
112
-				break;
113
-		}
114
-		return false;
115
-	}
116
-
117
-	public function stream_stat() {
118
-		return $this->url_stat($this->path);
119
-	}
120
-
121
-	public function stream_tell() {
122
-		return $this->pointer;
123
-	}
124
-
125
-	public function stream_write($data) {
126
-		if (!$this->writable) return 0;
127
-		$size = strlen($data);
128
-		if ($this->stream_eof()) {
129
-			self::$data[$this->path] .= $data;
130
-		} else {
131
-			self::$data[$this->path] = substr_replace(
132
-				self::$data[$this->path],
133
-				$data,
134
-				$this->pointer
135
-			);
136
-		}
137
-		$this->pointer += $size;
138
-		return $size;
139
-	}
140
-
141
-	public function unlink($path) {
142
-		if (isset(self::$data[$path])) {
143
-			unset(self::$data[$path]);
144
-		}
145
-		return true;
146
-	}
147
-
148
-	public function url_stat($path) {
149
-		if (isset(self::$data[$path])) {
150
-			$size = strlen(self::$data[$path]);
151
-			$time = time();
152
-			$data = array(
153
-				'dev' => 0,
154
-				'ino' => 0,
155
-				'mode' => self::MODE_FILE | 0777,
156
-				'nlink' => 1,
157
-				'uid' => 0,
158
-				'gid' => 0,
159
-				'rdev' => '',
160
-				'size' => $size,
161
-				'atime' => $time,
162
-				'mtime' => $time,
163
-				'ctime' => $time,
164
-				'blksize' => -1,
165
-				'blocks' => -1,
166
-			);
167
-			return array_values($data) + $data;
168
-		}
169
-		return false;
170
-	}
27
+    const MODE_FILE = 0100000;
28
+
29
+    public $context;
30
+    protected static $data = array();
31
+
32
+    protected $path = '';
33
+    protected $pointer = 0;
34
+    protected $writable = false;
35
+
36
+    public function stream_close() {
37
+    }
38
+
39
+    public function stream_eof() {
40
+        return $this->pointer >= strlen(self::$data[$this->path]);
41
+    }
42
+
43
+    public function stream_flush() {
44
+    }
45
+
46
+    public static function clear() {
47
+        self::$data = array();
48
+    }
49
+
50
+    public function stream_open($path, $mode, $options, &$opened_path) {
51
+        switch ($mode[0]) {
52
+            case 'r':
53
+                if (!isset(self::$data[$path])) return false;
54
+                $this->path = $path;
55
+                $this->writable = isset($mode[1]) && $mode[1] == '+';
56
+                break;
57
+            case 'w':
58
+                self::$data[$path] = '';
59
+                $this->path = $path;
60
+                $this->writable = true;
61
+                break;
62
+            case 'a':
63
+                if (!isset(self::$data[$path])) self::$data[$path] = '';
64
+                $this->path = $path;
65
+                $this->writable = true;
66
+                $this->pointer = strlen(self::$data[$path]);
67
+                break;
68
+            case 'x':
69
+                if (isset(self::$data[$path])) return false;
70
+                $this->path = $path;
71
+                $this->writable = true;
72
+                break;
73
+            case 'c':
74
+                if (!isset(self::$data[$path])) self::$data[$path] = '';
75
+                $this->path = $path;
76
+                $this->writable = true;
77
+                break;
78
+            default:
79
+                return false;
80
+        }
81
+        $opened_path = $this->path;
82
+        return true;
83
+    }
84
+
85
+    public function stream_read($count) {
86
+        $bytes = min(strlen(self::$data[$this->path]) - $this->pointer, $count);
87
+        $data = substr(self::$data[$this->path], $this->pointer, $bytes);
88
+        $this->pointer += $bytes;
89
+        return $data;
90
+    }
91
+
92
+    public function stream_seek($offset, $whence = SEEK_SET) {
93
+        $len = strlen(self::$data[$this->path]);
94
+        switch ($whence) {
95
+            case SEEK_SET:
96
+                if ($offset <= $len) {
97
+                    $this->pointer = $offset;
98
+                    return true;
99
+                }
100
+                break;
101
+            case SEEK_CUR:
102
+                if ($this->pointer + $offset <= $len) {
103
+                    $this->pointer += $offset;
104
+                    return true;
105
+                }
106
+                break;
107
+            case SEEK_END:
108
+                if ($len + $offset <= $len) {
109
+                    $this->pointer = $len + $offset;
110
+                    return true;
111
+                }
112
+                break;
113
+        }
114
+        return false;
115
+    }
116
+
117
+    public function stream_stat() {
118
+        return $this->url_stat($this->path);
119
+    }
120
+
121
+    public function stream_tell() {
122
+        return $this->pointer;
123
+    }
124
+
125
+    public function stream_write($data) {
126
+        if (!$this->writable) return 0;
127
+        $size = strlen($data);
128
+        if ($this->stream_eof()) {
129
+            self::$data[$this->path] .= $data;
130
+        } else {
131
+            self::$data[$this->path] = substr_replace(
132
+                self::$data[$this->path],
133
+                $data,
134
+                $this->pointer
135
+            );
136
+        }
137
+        $this->pointer += $size;
138
+        return $size;
139
+    }
140
+
141
+    public function unlink($path) {
142
+        if (isset(self::$data[$path])) {
143
+            unset(self::$data[$path]);
144
+        }
145
+        return true;
146
+    }
147
+
148
+    public function url_stat($path) {
149
+        if (isset(self::$data[$path])) {
150
+            $size = strlen(self::$data[$path]);
151
+            $time = time();
152
+            $data = array(
153
+                'dev' => 0,
154
+                'ino' => 0,
155
+                'mode' => self::MODE_FILE | 0777,
156
+                'nlink' => 1,
157
+                'uid' => 0,
158
+                'gid' => 0,
159
+                'rdev' => '',
160
+                'size' => $size,
161
+                'atime' => $time,
162
+                'mtime' => $time,
163
+                'ctime' => $time,
164
+                'blksize' => -1,
165
+                'blocks' => -1,
166
+            );
167
+            return array_values($data) + $data;
168
+        }
169
+        return false;
170
+    }
171 171
 }
Please login to merge, or discard this patch.
Braces   +15 added lines, -5 removed lines patch added patch discarded remove patch
@@ -50,7 +50,9 @@  discard block
 block discarded – undo
50 50
 	public function stream_open($path, $mode, $options, &$opened_path) {
51 51
 		switch ($mode[0]) {
52 52
 			case 'r':
53
-				if (!isset(self::$data[$path])) return false;
53
+				if (!isset(self::$data[$path])) {
54
+				    return false;
55
+				}
54 56
 				$this->path = $path;
55 57
 				$this->writable = isset($mode[1]) && $mode[1] == '+';
56 58
 				break;
@@ -60,18 +62,24 @@  discard block
 block discarded – undo
60 62
 				$this->writable = true;
61 63
 				break;
62 64
 			case 'a':
63
-				if (!isset(self::$data[$path])) self::$data[$path] = '';
65
+				if (!isset(self::$data[$path])) {
66
+				    self::$data[$path] = '';
67
+				}
64 68
 				$this->path = $path;
65 69
 				$this->writable = true;
66 70
 				$this->pointer = strlen(self::$data[$path]);
67 71
 				break;
68 72
 			case 'x':
69
-				if (isset(self::$data[$path])) return false;
73
+				if (isset(self::$data[$path])) {
74
+				    return false;
75
+				}
70 76
 				$this->path = $path;
71 77
 				$this->writable = true;
72 78
 				break;
73 79
 			case 'c':
74
-				if (!isset(self::$data[$path])) self::$data[$path] = '';
80
+				if (!isset(self::$data[$path])) {
81
+				    self::$data[$path] = '';
82
+				}
75 83
 				$this->path = $path;
76 84
 				$this->writable = true;
77 85
 				break;
@@ -123,7 +131,9 @@  discard block
 block discarded – undo
123 131
 	}
124 132
 
125 133
 	public function stream_write($data) {
126
-		if (!$this->writable) return 0;
134
+		if (!$this->writable) {
135
+		    return 0;
136
+		}
127 137
 		$size = strlen($data);
128 138
 		if ($this->stream_eof()) {
129 139
 			self::$data[$this->path] .= $data;
Please login to merge, or discard this patch.
lib/private/files/type/loader.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,6 @@
 block discarded – undo
23 23
 
24 24
 use OCP\Files\IMimeTypeLoader;
25 25
 use OCP\IDBConnection;
26
-
27 26
 use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
28 27
 
29 28
 /**
Please login to merge, or discard this patch.
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -34,141 +34,141 @@
 block discarded – undo
34 34
  */
35 35
 class Loader implements IMimeTypeLoader {
36 36
 
37
-	/** @var IDBConnection */
38
-	private $dbConnection;
39
-
40
-	/** @var array [id => mimetype] */
41
-	protected $mimetypes;
42
-
43
-	/** @var array [mimetype => id] */
44
-	protected $mimetypeIds;
45
-
46
-	/**
47
-	 * @param IDBConnection $dbConnection
48
-	 */
49
-	public function __construct(IDBConnection $dbConnection) {
50
-		$this->dbConnection = $dbConnection;
51
-		$this->mimetypes = [];
52
-		$this->mimetypeIds = [];
53
-	}
54
-
55
-	/**
56
-	 * Get a mimetype from its ID
57
-	 *
58
-	 * @param int $id
59
-	 * @return string|null
60
-	 */
61
-	public function getMimetypeById($id) {
62
-		if (!$this->mimetypes) {
63
-			$this->loadMimetypes();
64
-		}
65
-		if (isset($this->mimetypes[$id])) {
66
-			return $this->mimetypes[$id];
67
-		}
68
-		return null;
69
-	}
70
-
71
-	/**
72
-	 * Get a mimetype ID, adding the mimetype to the DB if it does not exist
73
-	 *
74
-	 * @param string $mimetype
75
-	 * @return int
76
-	 */
77
-	public function getId($mimetype) {
78
-		if (!$this->mimetypeIds) {
79
-			$this->loadMimetypes();
80
-		}
81
-		if (isset($this->mimetypeIds[$mimetype])) {
82
-			return $this->mimetypeIds[$mimetype];
83
-		}
84
-		return $this->store($mimetype);
85
-	}
86
-
87
-	/**
88
-	 * Test if a mimetype exists in the database
89
-	 *
90
-	 * @param string $mimetype
91
-	 * @return bool
92
-	 */
93
-	public function exists($mimetype) {
94
-		if (!$this->mimetypeIds) {
95
-			$this->loadMimetypes();
96
-		}
97
-		return isset($this->mimetypeIds[$mimetype]);
98
-	}
99
-
100
-	/**
101
-	 * Clear all loaded mimetypes, allow for re-loading
102
-	 */
103
-	public function reset() {
104
-		$this->mimetypes = [];
105
-		$this->mimetypeIds = [];
106
-	}
107
-
108
-	/**
109
-	 * Store a mimetype in the DB
110
-	 *
111
-	 * @param string $mimetype
112
-	 * @param int inserted ID
113
-	 */
114
-	protected function store($mimetype) {
115
-		try {
116
-			$qb = $this->dbConnection->getQueryBuilder();
117
-			$qb->insert('mimetypes')
118
-				->values([
119
-					'mimetype' => $qb->createNamedParameter($mimetype)
120
-				]);
121
-			$qb->execute();
122
-		} catch (UniqueConstraintViolationException $e) {
123
-			// something inserted it before us
124
-		}
125
-
126
-		$fetch = $this->dbConnection->getQueryBuilder();
127
-		$fetch->select('id')
128
-			->from('mimetypes')
129
-			->where(
130
-				$fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
131
-			));
132
-		$row = $fetch->execute()->fetch();
133
-
134
-		$this->mimetypes[$row['id']] = $mimetype;
135
-		$this->mimetypeIds[$mimetype] = $row['id'];
136
-		return $row['id'];
137
-	}
138
-
139
-	/**
140
-	 * Load all mimetypes from DB
141
-	 */
142
-	private function loadMimetypes() {
143
-		$qb = $this->dbConnection->getQueryBuilder();
144
-		$qb->select('id', 'mimetype')
145
-			->from('mimetypes');
146
-		$results = $qb->execute()->fetchAll();
147
-
148
-		foreach ($results as $row) {
149
-			$this->mimetypes[$row['id']] = $row['mimetype'];
150
-			$this->mimetypeIds[$row['mimetype']] = $row['id'];
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * Update filecache mimetype based on file extension
156
-	 *
157
-	 * @param string $ext file extension
158
-	 * @param int $mimetypeId
159
-	 * @return int number of changed rows
160
-	 */
161
-	public function updateFilecache($ext, $mimetypeId) {
162
-		$update = $this->dbConnection->getQueryBuilder();
163
-		$update->update('filecache')
164
-			->set('mimetype', $update->createNamedParameter($mimetypeId))
165
-			->where($update->expr()->neq(
166
-				'mimetype', $update->createNamedParameter($mimetypeId)
167
-			))
168
-			->andWhere($update->expr()->like(
169
-				$update->createFunction('LOWER(`name`)'), $update->createNamedParameter($ext)
170
-			));
171
-		return $update->execute();
172
-	}
37
+    /** @var IDBConnection */
38
+    private $dbConnection;
39
+
40
+    /** @var array [id => mimetype] */
41
+    protected $mimetypes;
42
+
43
+    /** @var array [mimetype => id] */
44
+    protected $mimetypeIds;
45
+
46
+    /**
47
+     * @param IDBConnection $dbConnection
48
+     */
49
+    public function __construct(IDBConnection $dbConnection) {
50
+        $this->dbConnection = $dbConnection;
51
+        $this->mimetypes = [];
52
+        $this->mimetypeIds = [];
53
+    }
54
+
55
+    /**
56
+     * Get a mimetype from its ID
57
+     *
58
+     * @param int $id
59
+     * @return string|null
60
+     */
61
+    public function getMimetypeById($id) {
62
+        if (!$this->mimetypes) {
63
+            $this->loadMimetypes();
64
+        }
65
+        if (isset($this->mimetypes[$id])) {
66
+            return $this->mimetypes[$id];
67
+        }
68
+        return null;
69
+    }
70
+
71
+    /**
72
+     * Get a mimetype ID, adding the mimetype to the DB if it does not exist
73
+     *
74
+     * @param string $mimetype
75
+     * @return int
76
+     */
77
+    public function getId($mimetype) {
78
+        if (!$this->mimetypeIds) {
79
+            $this->loadMimetypes();
80
+        }
81
+        if (isset($this->mimetypeIds[$mimetype])) {
82
+            return $this->mimetypeIds[$mimetype];
83
+        }
84
+        return $this->store($mimetype);
85
+    }
86
+
87
+    /**
88
+     * Test if a mimetype exists in the database
89
+     *
90
+     * @param string $mimetype
91
+     * @return bool
92
+     */
93
+    public function exists($mimetype) {
94
+        if (!$this->mimetypeIds) {
95
+            $this->loadMimetypes();
96
+        }
97
+        return isset($this->mimetypeIds[$mimetype]);
98
+    }
99
+
100
+    /**
101
+     * Clear all loaded mimetypes, allow for re-loading
102
+     */
103
+    public function reset() {
104
+        $this->mimetypes = [];
105
+        $this->mimetypeIds = [];
106
+    }
107
+
108
+    /**
109
+     * Store a mimetype in the DB
110
+     *
111
+     * @param string $mimetype
112
+     * @param int inserted ID
113
+     */
114
+    protected function store($mimetype) {
115
+        try {
116
+            $qb = $this->dbConnection->getQueryBuilder();
117
+            $qb->insert('mimetypes')
118
+                ->values([
119
+                    'mimetype' => $qb->createNamedParameter($mimetype)
120
+                ]);
121
+            $qb->execute();
122
+        } catch (UniqueConstraintViolationException $e) {
123
+            // something inserted it before us
124
+        }
125
+
126
+        $fetch = $this->dbConnection->getQueryBuilder();
127
+        $fetch->select('id')
128
+            ->from('mimetypes')
129
+            ->where(
130
+                $fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
131
+            ));
132
+        $row = $fetch->execute()->fetch();
133
+
134
+        $this->mimetypes[$row['id']] = $mimetype;
135
+        $this->mimetypeIds[$mimetype] = $row['id'];
136
+        return $row['id'];
137
+    }
138
+
139
+    /**
140
+     * Load all mimetypes from DB
141
+     */
142
+    private function loadMimetypes() {
143
+        $qb = $this->dbConnection->getQueryBuilder();
144
+        $qb->select('id', 'mimetype')
145
+            ->from('mimetypes');
146
+        $results = $qb->execute()->fetchAll();
147
+
148
+        foreach ($results as $row) {
149
+            $this->mimetypes[$row['id']] = $row['mimetype'];
150
+            $this->mimetypeIds[$row['mimetype']] = $row['id'];
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Update filecache mimetype based on file extension
156
+     *
157
+     * @param string $ext file extension
158
+     * @param int $mimetypeId
159
+     * @return int number of changed rows
160
+     */
161
+    public function updateFilecache($ext, $mimetypeId) {
162
+        $update = $this->dbConnection->getQueryBuilder();
163
+        $update->update('filecache')
164
+            ->set('mimetype', $update->createNamedParameter($mimetypeId))
165
+            ->where($update->expr()->neq(
166
+                'mimetype', $update->createNamedParameter($mimetypeId)
167
+            ))
168
+            ->andWhere($update->expr()->like(
169
+                $update->createFunction('LOWER(`name`)'), $update->createNamedParameter($ext)
170
+            ));
171
+        return $update->execute();
172
+    }
173 173
 
174 174
 }
Please login to merge, or discard this patch.
lib/private/files/view.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * and does not take the chroot into account )
201 201
 	 *
202 202
 	 * @param string $path
203
-	 * @return \OCP\Files\Mount\IMountPoint
203
+	 * @return Mount\MountPoint|null
204 204
 	 */
205 205
 	public function getMount($path) {
206 206
 		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
@@ -948,7 +948,7 @@  discard block
 block discarded – undo
948 948
 
949 949
 	/**
950 950
 	 * @param string $path
951
-	 * @return bool|string
951
+	 * @return string|false
952 952
 	 * @throws \OCP\Files\InvalidPathException
953 953
 	 */
954 954
 	public function toTmpFile($path) {
@@ -2071,7 +2071,7 @@  discard block
 block discarded – undo
2071 2071
 
2072 2072
 	/**
2073 2073
 	 * @param string $filename
2074
-	 * @return array
2074
+	 * @return string[]
2075 2075
 	 * @throws \OC\User\NoUserException
2076 2076
 	 * @throws NotFoundException
2077 2077
 	 */
Please login to merge, or discard this patch.
Indentation   +2009 added lines, -2009 removed lines patch added patch discarded remove patch
@@ -79,2017 +79,2017 @@
 block discarded – undo
79 79
  * \OC\Files\Storage\Storage object
80 80
  */
81 81
 class View {
82
-	/** @var string */
83
-	private $fakeRoot = '';
84
-
85
-	/**
86
-	 * @var \OCP\Lock\ILockingProvider
87
-	 */
88
-	private $lockingProvider;
89
-
90
-	private $lockingEnabled;
91
-
92
-	private $updaterEnabled = true;
93
-
94
-	private $userManager;
95
-
96
-	/**
97
-	 * @param string $root
98
-	 * @throws \Exception If $root contains an invalid path
99
-	 */
100
-	public function __construct($root = '') {
101
-		if (is_null($root)) {
102
-			throw new \InvalidArgumentException('Root can\'t be null');
103
-		}
104
-		if (!Filesystem::isValidPath($root)) {
105
-			throw new \Exception();
106
-		}
107
-
108
-		$this->fakeRoot = $root;
109
-		$this->lockingProvider = \OC::$server->getLockingProvider();
110
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
111
-		$this->userManager = \OC::$server->getUserManager();
112
-	}
113
-
114
-	public function getAbsolutePath($path = '/') {
115
-		if ($path === null) {
116
-			return null;
117
-		}
118
-		$this->assertPathLength($path);
119
-		if ($path === '') {
120
-			$path = '/';
121
-		}
122
-		if ($path[0] !== '/') {
123
-			$path = '/' . $path;
124
-		}
125
-		return $this->fakeRoot . $path;
126
-	}
127
-
128
-	/**
129
-	 * change the root to a fake root
130
-	 *
131
-	 * @param string $fakeRoot
132
-	 * @return boolean|null
133
-	 */
134
-	public function chroot($fakeRoot) {
135
-		if (!$fakeRoot == '') {
136
-			if ($fakeRoot[0] !== '/') {
137
-				$fakeRoot = '/' . $fakeRoot;
138
-			}
139
-		}
140
-		$this->fakeRoot = $fakeRoot;
141
-	}
142
-
143
-	/**
144
-	 * get the fake root
145
-	 *
146
-	 * @return string
147
-	 */
148
-	public function getRoot() {
149
-		return $this->fakeRoot;
150
-	}
151
-
152
-	/**
153
-	 * get path relative to the root of the view
154
-	 *
155
-	 * @param string $path
156
-	 * @return string
157
-	 */
158
-	public function getRelativePath($path) {
159
-		$this->assertPathLength($path);
160
-		if ($this->fakeRoot == '') {
161
-			return $path;
162
-		}
163
-
164
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
165
-			return '/';
166
-		}
167
-
168
-		// missing slashes can cause wrong matches!
169
-		$root = rtrim($this->fakeRoot, '/') . '/';
170
-
171
-		if (strpos($path, $root) !== 0) {
172
-			return null;
173
-		} else {
174
-			$path = substr($path, strlen($this->fakeRoot));
175
-			if (strlen($path) === 0) {
176
-				return '/';
177
-			} else {
178
-				return $path;
179
-			}
180
-		}
181
-	}
182
-
183
-	/**
184
-	 * get the mountpoint of the storage object for a path
185
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
186
-	 * returned mountpoint is relative to the absolute root of the filesystem
187
-	 * and does not take the chroot into account )
188
-	 *
189
-	 * @param string $path
190
-	 * @return string
191
-	 */
192
-	public function getMountPoint($path) {
193
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
194
-	}
195
-
196
-	/**
197
-	 * get the mountpoint of the storage object for a path
198
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
199
-	 * returned mountpoint is relative to the absolute root of the filesystem
200
-	 * and does not take the chroot into account )
201
-	 *
202
-	 * @param string $path
203
-	 * @return \OCP\Files\Mount\IMountPoint
204
-	 */
205
-	public function getMount($path) {
206
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
207
-	}
208
-
209
-	/**
210
-	 * resolve a path to a storage and internal path
211
-	 *
212
-	 * @param string $path
213
-	 * @return array an array consisting of the storage and the internal path
214
-	 */
215
-	public function resolvePath($path) {
216
-		$a = $this->getAbsolutePath($path);
217
-		$p = Filesystem::normalizePath($a);
218
-		return Filesystem::resolvePath($p);
219
-	}
220
-
221
-	/**
222
-	 * return the path to a local version of the file
223
-	 * we need this because we can't know if a file is stored local or not from
224
-	 * outside the filestorage and for some purposes a local file is needed
225
-	 *
226
-	 * @param string $path
227
-	 * @return string
228
-	 */
229
-	public function getLocalFile($path) {
230
-		$parent = substr($path, 0, strrpos($path, '/'));
231
-		$path = $this->getAbsolutePath($path);
232
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
233
-		if (Filesystem::isValidPath($parent) and $storage) {
234
-			return $storage->getLocalFile($internalPath);
235
-		} else {
236
-			return null;
237
-		}
238
-	}
239
-
240
-	/**
241
-	 * @param string $path
242
-	 * @return string
243
-	 */
244
-	public function getLocalFolder($path) {
245
-		$parent = substr($path, 0, strrpos($path, '/'));
246
-		$path = $this->getAbsolutePath($path);
247
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
248
-		if (Filesystem::isValidPath($parent) and $storage) {
249
-			return $storage->getLocalFolder($internalPath);
250
-		} else {
251
-			return null;
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * the following functions operate with arguments and return values identical
257
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
258
-	 * for \OC\Files\Storage\Storage via basicOperation().
259
-	 */
260
-	public function mkdir($path) {
261
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
262
-	}
263
-
264
-	/**
265
-	 * remove mount point
266
-	 *
267
-	 * @param \OC\Files\Mount\MoveableMount $mount
268
-	 * @param string $path relative to data/
269
-	 * @return boolean
270
-	 */
271
-	protected function removeMount($mount, $path) {
272
-		if ($mount instanceof MoveableMount) {
273
-			// cut of /user/files to get the relative path to data/user/files
274
-			$pathParts = explode('/', $path, 4);
275
-			$relPath = '/' . $pathParts[3];
276
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
277
-			\OC_Hook::emit(
278
-				Filesystem::CLASSNAME, "umount",
279
-				array(Filesystem::signal_param_path => $relPath)
280
-			);
281
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
282
-			$result = $mount->removeMount();
283
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
284
-			if ($result) {
285
-				\OC_Hook::emit(
286
-					Filesystem::CLASSNAME, "post_umount",
287
-					array(Filesystem::signal_param_path => $relPath)
288
-				);
289
-			}
290
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
291
-			return $result;
292
-		} else {
293
-			// do not allow deleting the storage's root / the mount point
294
-			// because for some storages it might delete the whole contents
295
-			// but isn't supposed to work that way
296
-			return false;
297
-		}
298
-	}
299
-
300
-	public function disableCacheUpdate() {
301
-		$this->updaterEnabled = false;
302
-	}
303
-
304
-	public function enableCacheUpdate() {
305
-		$this->updaterEnabled = true;
306
-	}
307
-
308
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
309
-		if ($this->updaterEnabled) {
310
-			if (is_null($time)) {
311
-				$time = time();
312
-			}
313
-			$storage->getUpdater()->update($internalPath, $time);
314
-		}
315
-	}
316
-
317
-	protected function removeUpdate(Storage $storage, $internalPath) {
318
-		if ($this->updaterEnabled) {
319
-			$storage->getUpdater()->remove($internalPath);
320
-		}
321
-	}
322
-
323
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
324
-		if ($this->updaterEnabled) {
325
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
326
-		}
327
-	}
328
-
329
-	/**
330
-	 * @param string $path
331
-	 * @return bool|mixed
332
-	 */
333
-	public function rmdir($path) {
334
-		$absolutePath = $this->getAbsolutePath($path);
335
-		$mount = Filesystem::getMountManager()->find($absolutePath);
336
-		if ($mount->getInternalPath($absolutePath) === '') {
337
-			return $this->removeMount($mount, $absolutePath);
338
-		}
339
-		if ($this->is_dir($path)) {
340
-			return $this->basicOperation('rmdir', $path, array('delete'));
341
-		} else {
342
-			return false;
343
-		}
344
-	}
345
-
346
-	/**
347
-	 * @param string $path
348
-	 * @return resource
349
-	 */
350
-	public function opendir($path) {
351
-		return $this->basicOperation('opendir', $path, array('read'));
352
-	}
353
-
354
-	/**
355
-	 * @param $handle
356
-	 * @return mixed
357
-	 */
358
-	public function readdir($handle) {
359
-		$fsLocal = new Storage\Local(array('datadir' => '/'));
360
-		return $fsLocal->readdir($handle);
361
-	}
362
-
363
-	/**
364
-	 * @param string $path
365
-	 * @return bool|mixed
366
-	 */
367
-	public function is_dir($path) {
368
-		if ($path == '/') {
369
-			return true;
370
-		}
371
-		return $this->basicOperation('is_dir', $path);
372
-	}
373
-
374
-	/**
375
-	 * @param string $path
376
-	 * @return bool|mixed
377
-	 */
378
-	public function is_file($path) {
379
-		if ($path == '/') {
380
-			return false;
381
-		}
382
-		return $this->basicOperation('is_file', $path);
383
-	}
384
-
385
-	/**
386
-	 * @param string $path
387
-	 * @return mixed
388
-	 */
389
-	public function stat($path) {
390
-		return $this->basicOperation('stat', $path);
391
-	}
392
-
393
-	/**
394
-	 * @param string $path
395
-	 * @return mixed
396
-	 */
397
-	public function filetype($path) {
398
-		return $this->basicOperation('filetype', $path);
399
-	}
400
-
401
-	/**
402
-	 * @param string $path
403
-	 * @return mixed
404
-	 */
405
-	public function filesize($path) {
406
-		return $this->basicOperation('filesize', $path);
407
-	}
408
-
409
-	/**
410
-	 * @param string $path
411
-	 * @return bool|mixed
412
-	 * @throws \OCP\Files\InvalidPathException
413
-	 */
414
-	public function readfile($path) {
415
-		$this->assertPathLength($path);
416
-		@ob_end_clean();
417
-		$handle = $this->fopen($path, 'rb');
418
-		if ($handle) {
419
-			$chunkSize = 8192; // 8 kB chunks
420
-			while (!feof($handle)) {
421
-				echo fread($handle, $chunkSize);
422
-				flush();
423
-			}
424
-			$size = $this->filesize($path);
425
-			return $size;
426
-		}
427
-		return false;
428
-	}
429
-
430
-	/**
431
-	 * @param string $path
432
-	 * @param int $from 
433
-	 * @param int $to
434
-	 * @return bool|mixed
435
-	 * @throws \OCP\Files\InvalidPathException
436
-	 * @throws \OCP\Files\NotPermittedException
437
-	 */
438
-	public function readfilePart($path, $from, $to) {
439
-		$this->assertPathLength($path);
440
-		@ob_end_clean();
441
-		$handle = $this->fopen($path, 'rb');
442
-		if ($handle) {
443
-			if (fseek($handle, $from) === 0) {
444
-			    $chunkSize = 8192; // 8 kB chunks
445
-			    $end = $to + 1;
446
-			    while (!feof($handle) && ftell($handle) < $end) {
447
-				$len = $end-ftell($handle);
448
-				if ($len > $chunkSize) { 
449
-				    $len = $chunkSize; 
450
-				}
451
-				echo fread($handle, $len);
452
-				flush();
453
-			    }
454
-			    $size = ftell($handle) - $from;
455
-			    return $size;
456
-			}
457
-
458
-			throw new \OCP\Files\NotPermittedException('fseek error');
459
-		}
460
-		return false;
461
-	}
462
-
463
-	/**
464
-	 * @param string $path
465
-	 * @return mixed
466
-	 */
467
-	public function isCreatable($path) {
468
-		return $this->basicOperation('isCreatable', $path);
469
-	}
470
-
471
-	/**
472
-	 * @param string $path
473
-	 * @return mixed
474
-	 */
475
-	public function isReadable($path) {
476
-		return $this->basicOperation('isReadable', $path);
477
-	}
478
-
479
-	/**
480
-	 * @param string $path
481
-	 * @return mixed
482
-	 */
483
-	public function isUpdatable($path) {
484
-		return $this->basicOperation('isUpdatable', $path);
485
-	}
486
-
487
-	/**
488
-	 * @param string $path
489
-	 * @return bool|mixed
490
-	 */
491
-	public function isDeletable($path) {
492
-		$absolutePath = $this->getAbsolutePath($path);
493
-		$mount = Filesystem::getMountManager()->find($absolutePath);
494
-		if ($mount->getInternalPath($absolutePath) === '') {
495
-			return $mount instanceof MoveableMount;
496
-		}
497
-		return $this->basicOperation('isDeletable', $path);
498
-	}
499
-
500
-	/**
501
-	 * @param string $path
502
-	 * @return mixed
503
-	 */
504
-	public function isSharable($path) {
505
-		return $this->basicOperation('isSharable', $path);
506
-	}
507
-
508
-	/**
509
-	 * @param string $path
510
-	 * @return bool|mixed
511
-	 */
512
-	public function file_exists($path) {
513
-		if ($path == '/') {
514
-			return true;
515
-		}
516
-		return $this->basicOperation('file_exists', $path);
517
-	}
518
-
519
-	/**
520
-	 * @param string $path
521
-	 * @return mixed
522
-	 */
523
-	public function filemtime($path) {
524
-		return $this->basicOperation('filemtime', $path);
525
-	}
526
-
527
-	/**
528
-	 * @param string $path
529
-	 * @param int|string $mtime
530
-	 * @return bool
531
-	 */
532
-	public function touch($path, $mtime = null) {
533
-		if (!is_null($mtime) and !is_numeric($mtime)) {
534
-			$mtime = strtotime($mtime);
535
-		}
536
-
537
-		$hooks = array('touch');
538
-
539
-		if (!$this->file_exists($path)) {
540
-			$hooks[] = 'create';
541
-			$hooks[] = 'write';
542
-		}
543
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
544
-		if (!$result) {
545
-			// If create file fails because of permissions on external storage like SMB folders,
546
-			// check file exists and return false if not.
547
-			if (!$this->file_exists($path)) {
548
-				return false;
549
-			}
550
-			if (is_null($mtime)) {
551
-				$mtime = time();
552
-			}
553
-			//if native touch fails, we emulate it by changing the mtime in the cache
554
-			$this->putFileInfo($path, array('mtime' => $mtime));
555
-		}
556
-		return true;
557
-	}
558
-
559
-	/**
560
-	 * @param string $path
561
-	 * @return mixed
562
-	 */
563
-	public function file_get_contents($path) {
564
-		return $this->basicOperation('file_get_contents', $path, array('read'));
565
-	}
566
-
567
-	/**
568
-	 * @param bool $exists
569
-	 * @param string $path
570
-	 * @param bool $run
571
-	 */
572
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
573
-		if (!$exists) {
574
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
575
-				Filesystem::signal_param_path => $this->getHookPath($path),
576
-				Filesystem::signal_param_run => &$run,
577
-			));
578
-		} else {
579
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
580
-				Filesystem::signal_param_path => $this->getHookPath($path),
581
-				Filesystem::signal_param_run => &$run,
582
-			));
583
-		}
584
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
585
-			Filesystem::signal_param_path => $this->getHookPath($path),
586
-			Filesystem::signal_param_run => &$run,
587
-		));
588
-	}
589
-
590
-	/**
591
-	 * @param bool $exists
592
-	 * @param string $path
593
-	 */
594
-	protected function emit_file_hooks_post($exists, $path) {
595
-		if (!$exists) {
596
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
597
-				Filesystem::signal_param_path => $this->getHookPath($path),
598
-			));
599
-		} else {
600
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
601
-				Filesystem::signal_param_path => $this->getHookPath($path),
602
-			));
603
-		}
604
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
605
-			Filesystem::signal_param_path => $this->getHookPath($path),
606
-		));
607
-	}
608
-
609
-	/**
610
-	 * @param string $path
611
-	 * @param mixed $data
612
-	 * @return bool|mixed
613
-	 * @throws \Exception
614
-	 */
615
-	public function file_put_contents($path, $data) {
616
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
617
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
618
-			if (Filesystem::isValidPath($path)
619
-				and !Filesystem::isFileBlacklisted($path)
620
-			) {
621
-				$path = $this->getRelativePath($absolutePath);
622
-
623
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
624
-
625
-				$exists = $this->file_exists($path);
626
-				$run = true;
627
-				if ($this->shouldEmitHooks($path)) {
628
-					$this->emit_file_hooks_pre($exists, $path, $run);
629
-				}
630
-				if (!$run) {
631
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
632
-					return false;
633
-				}
634
-
635
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
636
-
637
-				/** @var \OC\Files\Storage\Storage $storage */
638
-				list($storage, $internalPath) = $this->resolvePath($path);
639
-				$target = $storage->fopen($internalPath, 'w');
640
-				if ($target) {
641
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
642
-					fclose($target);
643
-					fclose($data);
644
-
645
-					$this->writeUpdate($storage, $internalPath);
646
-
647
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
648
-
649
-					if ($this->shouldEmitHooks($path) && $result !== false) {
650
-						$this->emit_file_hooks_post($exists, $path);
651
-					}
652
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
653
-					return $result;
654
-				} else {
655
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
656
-					return false;
657
-				}
658
-			} else {
659
-				return false;
660
-			}
661
-		} else {
662
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
663
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
664
-		}
665
-	}
666
-
667
-	/**
668
-	 * @param string $path
669
-	 * @return bool|mixed
670
-	 */
671
-	public function unlink($path) {
672
-		if ($path === '' || $path === '/') {
673
-			// do not allow deleting the root
674
-			return false;
675
-		}
676
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
677
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
678
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
679
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
680
-			return $this->removeMount($mount, $absolutePath);
681
-		}
682
-		return $this->basicOperation('unlink', $path, array('delete'));
683
-	}
684
-
685
-	/**
686
-	 * @param string $directory
687
-	 * @return bool|mixed
688
-	 */
689
-	public function deleteAll($directory) {
690
-		return $this->rmdir($directory);
691
-	}
692
-
693
-	/**
694
-	 * Rename/move a file or folder from the source path to target path.
695
-	 *
696
-	 * @param string $path1 source path
697
-	 * @param string $path2 target path
698
-	 *
699
-	 * @return bool|mixed
700
-	 */
701
-	public function rename($path1, $path2) {
702
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
703
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
704
-		$result = false;
705
-		if (
706
-			Filesystem::isValidPath($path2)
707
-			and Filesystem::isValidPath($path1)
708
-			and !Filesystem::isFileBlacklisted($path2)
709
-		) {
710
-			$path1 = $this->getRelativePath($absolutePath1);
711
-			$path2 = $this->getRelativePath($absolutePath2);
712
-			$exists = $this->file_exists($path2);
713
-
714
-			if ($path1 == null or $path2 == null) {
715
-				return false;
716
-			}
717
-
718
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
719
-			try {
720
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
721
-			} catch (LockedException $e) {
722
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
723
-				throw $e;
724
-			}
725
-
726
-			$run = true;
727
-			if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
728
-				// if it was a rename from a part file to a regular file it was a write and not a rename operation
729
-				$this->emit_file_hooks_pre($exists, $path2, $run);
730
-			} elseif ($this->shouldEmitHooks($path1)) {
731
-				\OC_Hook::emit(
732
-					Filesystem::CLASSNAME, Filesystem::signal_rename,
733
-					array(
734
-						Filesystem::signal_param_oldpath => $this->getHookPath($path1),
735
-						Filesystem::signal_param_newpath => $this->getHookPath($path2),
736
-						Filesystem::signal_param_run => &$run
737
-					)
738
-				);
739
-			}
740
-			if ($run) {
741
-				$this->verifyPath(dirname($path2), basename($path2));
742
-
743
-				$manager = Filesystem::getMountManager();
744
-				$mount1 = $this->getMount($path1);
745
-				$mount2 = $this->getMount($path2);
746
-				$storage1 = $mount1->getStorage();
747
-				$storage2 = $mount2->getStorage();
748
-				$internalPath1 = $mount1->getInternalPath($absolutePath1);
749
-				$internalPath2 = $mount2->getInternalPath($absolutePath2);
750
-
751
-				$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
752
-				$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
753
-
754
-				if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
755
-					if ($this->isTargetAllowed($absolutePath2)) {
756
-						/**
757
-						 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
758
-						 */
759
-						$sourceMountPoint = $mount1->getMountPoint();
760
-						$result = $mount1->moveMount($absolutePath2);
761
-						$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
762
-					} else {
763
-						$result = false;
764
-					}
765
-					// moving a file/folder within the same mount point
766
-				} elseif ($storage1 === $storage2) {
767
-					if ($storage1) {
768
-						$result = $storage1->rename($internalPath1, $internalPath2);
769
-					} else {
770
-						$result = false;
771
-					}
772
-					// moving a file/folder between storages (from $storage1 to $storage2)
773
-				} else {
774
-					$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
775
-				}
776
-
777
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
778
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
779
-
780
-					$this->writeUpdate($storage2, $internalPath2);
781
-				} else if ($result) {
782
-					if ($internalPath1 !== '') { // dont do a cache update for moved mounts
783
-						$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
784
-					}
785
-				}
786
-
787
-				$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
788
-				$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
789
-
790
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
791
-					if ($this->shouldEmitHooks()) {
792
-						$this->emit_file_hooks_post($exists, $path2);
793
-					}
794
-				} elseif ($result) {
795
-					if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
796
-						\OC_Hook::emit(
797
-							Filesystem::CLASSNAME,
798
-							Filesystem::signal_post_rename,
799
-							array(
800
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
801
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
802
-							)
803
-						);
804
-					}
805
-				}
806
-			}
807
-			$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
808
-			$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
809
-		}
810
-		return $result;
811
-	}
812
-
813
-	/**
814
-	 * Copy a file/folder from the source path to target path
815
-	 *
816
-	 * @param string $path1 source path
817
-	 * @param string $path2 target path
818
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
819
-	 *
820
-	 * @return bool|mixed
821
-	 */
822
-	public function copy($path1, $path2, $preserveMtime = false) {
823
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
824
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
825
-		$result = false;
826
-		if (
827
-			Filesystem::isValidPath($path2)
828
-			and Filesystem::isValidPath($path1)
829
-			and !Filesystem::isFileBlacklisted($path2)
830
-		) {
831
-			$path1 = $this->getRelativePath($absolutePath1);
832
-			$path2 = $this->getRelativePath($absolutePath2);
833
-
834
-			if ($path1 == null or $path2 == null) {
835
-				return false;
836
-			}
837
-			$run = true;
838
-
839
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
840
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
841
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
842
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
843
-
844
-			try {
845
-
846
-				$exists = $this->file_exists($path2);
847
-				if ($this->shouldEmitHooks()) {
848
-					\OC_Hook::emit(
849
-						Filesystem::CLASSNAME,
850
-						Filesystem::signal_copy,
851
-						array(
852
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
853
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
854
-							Filesystem::signal_param_run => &$run
855
-						)
856
-					);
857
-					$this->emit_file_hooks_pre($exists, $path2, $run);
858
-				}
859
-				if ($run) {
860
-					$mount1 = $this->getMount($path1);
861
-					$mount2 = $this->getMount($path2);
862
-					$storage1 = $mount1->getStorage();
863
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
864
-					$storage2 = $mount2->getStorage();
865
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
866
-
867
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
868
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
869
-
870
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
871
-						if ($storage1) {
872
-							$result = $storage1->copy($internalPath1, $internalPath2);
873
-						} else {
874
-							$result = false;
875
-						}
876
-					} else {
877
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
878
-					}
879
-
880
-					$this->writeUpdate($storage2, $internalPath2);
881
-
882
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
883
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
884
-
885
-					if ($this->shouldEmitHooks() && $result !== false) {
886
-						\OC_Hook::emit(
887
-							Filesystem::CLASSNAME,
888
-							Filesystem::signal_post_copy,
889
-							array(
890
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
891
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
892
-							)
893
-						);
894
-						$this->emit_file_hooks_post($exists, $path2);
895
-					}
896
-
897
-				}
898
-			} catch (\Exception $e) {
899
-				$this->unlockFile($path2, $lockTypePath2);
900
-				$this->unlockFile($path1, $lockTypePath1);
901
-				throw $e;
902
-			}
903
-
904
-			$this->unlockFile($path2, $lockTypePath2);
905
-			$this->unlockFile($path1, $lockTypePath1);
906
-
907
-		}
908
-		return $result;
909
-	}
910
-
911
-	/**
912
-	 * @param string $path
913
-	 * @param string $mode
914
-	 * @return resource
915
-	 */
916
-	public function fopen($path, $mode) {
917
-		$hooks = array();
918
-		switch ($mode) {
919
-			case 'r':
920
-			case 'rb':
921
-				$hooks[] = 'read';
922
-				break;
923
-			case 'r+':
924
-			case 'rb+':
925
-			case 'w+':
926
-			case 'wb+':
927
-			case 'x+':
928
-			case 'xb+':
929
-			case 'a+':
930
-			case 'ab+':
931
-				$hooks[] = 'read';
932
-				$hooks[] = 'write';
933
-				break;
934
-			case 'w':
935
-			case 'wb':
936
-			case 'x':
937
-			case 'xb':
938
-			case 'a':
939
-			case 'ab':
940
-				$hooks[] = 'write';
941
-				break;
942
-			default:
943
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
944
-		}
945
-
946
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
947
-	}
948
-
949
-	/**
950
-	 * @param string $path
951
-	 * @return bool|string
952
-	 * @throws \OCP\Files\InvalidPathException
953
-	 */
954
-	public function toTmpFile($path) {
955
-		$this->assertPathLength($path);
956
-		if (Filesystem::isValidPath($path)) {
957
-			$source = $this->fopen($path, 'r');
958
-			if ($source) {
959
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
960
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
961
-				file_put_contents($tmpFile, $source);
962
-				return $tmpFile;
963
-			} else {
964
-				return false;
965
-			}
966
-		} else {
967
-			return false;
968
-		}
969
-	}
970
-
971
-	/**
972
-	 * @param string $tmpFile
973
-	 * @param string $path
974
-	 * @return bool|mixed
975
-	 * @throws \OCP\Files\InvalidPathException
976
-	 */
977
-	public function fromTmpFile($tmpFile, $path) {
978
-		$this->assertPathLength($path);
979
-		if (Filesystem::isValidPath($path)) {
980
-
981
-			// Get directory that the file is going into
982
-			$filePath = dirname($path);
983
-
984
-			// Create the directories if any
985
-			if (!$this->file_exists($filePath)) {
986
-				$this->mkdir($filePath);
987
-			}
988
-
989
-			$source = fopen($tmpFile, 'r');
990
-			if ($source) {
991
-				$result = $this->file_put_contents($path, $source);
992
-				// $this->file_put_contents() might have already closed
993
-				// the resource, so we check it, before trying to close it
994
-				// to avoid messages in the error log.
995
-				if (is_resource($source)) {
996
-					fclose($source);
997
-				}
998
-				unlink($tmpFile);
999
-				return $result;
1000
-			} else {
1001
-				return false;
1002
-			}
1003
-		} else {
1004
-			return false;
1005
-		}
1006
-	}
1007
-
1008
-
1009
-	/**
1010
-	 * @param string $path
1011
-	 * @return mixed
1012
-	 * @throws \OCP\Files\InvalidPathException
1013
-	 */
1014
-	public function getMimeType($path) {
1015
-		$this->assertPathLength($path);
1016
-		return $this->basicOperation('getMimeType', $path);
1017
-	}
1018
-
1019
-	/**
1020
-	 * @param string $type
1021
-	 * @param string $path
1022
-	 * @param bool $raw
1023
-	 * @return bool|null|string
1024
-	 */
1025
-	public function hash($type, $path, $raw = false) {
1026
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1027
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1028
-		if (Filesystem::isValidPath($path)) {
1029
-			$path = $this->getRelativePath($absolutePath);
1030
-			if ($path == null) {
1031
-				return false;
1032
-			}
1033
-			if ($this->shouldEmitHooks($path)) {
1034
-				\OC_Hook::emit(
1035
-					Filesystem::CLASSNAME,
1036
-					Filesystem::signal_read,
1037
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1038
-				);
1039
-			}
1040
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1041
-			if ($storage) {
1042
-				$result = $storage->hash($type, $internalPath, $raw);
1043
-				return $result;
1044
-			}
1045
-		}
1046
-		return null;
1047
-	}
1048
-
1049
-	/**
1050
-	 * @param string $path
1051
-	 * @return mixed
1052
-	 * @throws \OCP\Files\InvalidPathException
1053
-	 */
1054
-	public function free_space($path = '/') {
1055
-		$this->assertPathLength($path);
1056
-		return $this->basicOperation('free_space', $path);
1057
-	}
1058
-
1059
-	/**
1060
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1061
-	 *
1062
-	 * @param string $operation
1063
-	 * @param string $path
1064
-	 * @param array $hooks (optional)
1065
-	 * @param mixed $extraParam (optional)
1066
-	 * @return mixed
1067
-	 * @throws \Exception
1068
-	 *
1069
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1070
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1071
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1072
-	 */
1073
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1074
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1075
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1076
-		if (Filesystem::isValidPath($path)
1077
-			and !Filesystem::isFileBlacklisted($path)
1078
-		) {
1079
-			$path = $this->getRelativePath($absolutePath);
1080
-			if ($path == null) {
1081
-				return false;
1082
-			}
1083
-
1084
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1085
-				// always a shared lock during pre-hooks so the hook can read the file
1086
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1087
-			}
1088
-
1089
-			$run = $this->runHooks($hooks, $path);
1090
-			/** @var \OC\Files\Storage\Storage $storage */
1091
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1092
-			if ($run and $storage) {
1093
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1094
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1095
-				}
1096
-				try {
1097
-					if (!is_null($extraParam)) {
1098
-						$result = $storage->$operation($internalPath, $extraParam);
1099
-					} else {
1100
-						$result = $storage->$operation($internalPath);
1101
-					}
1102
-				} catch (\Exception $e) {
1103
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1104
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1105
-					} else if (in_array('read', $hooks)) {
1106
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1107
-					}
1108
-					throw $e;
1109
-				}
1110
-
1111
-				if ($result && in_array('delete', $hooks) and $result) {
1112
-					$this->removeUpdate($storage, $internalPath);
1113
-				}
1114
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1115
-					$this->writeUpdate($storage, $internalPath);
1116
-				}
1117
-				if ($result && in_array('touch', $hooks)) {
1118
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1119
-				}
1120
-
1121
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1122
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1123
-				}
1124
-
1125
-				$unlockLater = false;
1126
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1127
-					$unlockLater = true;
1128
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1129
-						if (in_array('write', $hooks)) {
1130
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1131
-						} else if (in_array('read', $hooks)) {
1132
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1133
-						}
1134
-					});
1135
-				}
1136
-
1137
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1138
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1139
-						$this->runHooks($hooks, $path, true);
1140
-					}
1141
-				}
1142
-
1143
-				if (!$unlockLater
1144
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1145
-				) {
1146
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1147
-				}
1148
-				return $result;
1149
-			} else {
1150
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1151
-			}
1152
-		}
1153
-		return null;
1154
-	}
1155
-
1156
-	/**
1157
-	 * get the path relative to the default root for hook usage
1158
-	 *
1159
-	 * @param string $path
1160
-	 * @return string
1161
-	 */
1162
-	private function getHookPath($path) {
1163
-		if (!Filesystem::getView()) {
1164
-			return $path;
1165
-		}
1166
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1167
-	}
1168
-
1169
-	private function shouldEmitHooks($path = '') {
1170
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1171
-			return false;
1172
-		}
1173
-		if (!Filesystem::$loaded) {
1174
-			return false;
1175
-		}
1176
-		$defaultRoot = Filesystem::getRoot();
1177
-		if ($defaultRoot === null) {
1178
-			return false;
1179
-		}
1180
-		if ($this->fakeRoot === $defaultRoot) {
1181
-			return true;
1182
-		}
1183
-		$fullPath = $this->getAbsolutePath($path);
1184
-
1185
-		if ($fullPath === $defaultRoot) {
1186
-			return true;
1187
-		}
1188
-
1189
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1190
-	}
1191
-
1192
-	/**
1193
-	 * @param string[] $hooks
1194
-	 * @param string $path
1195
-	 * @param bool $post
1196
-	 * @return bool
1197
-	 */
1198
-	private function runHooks($hooks, $path, $post = false) {
1199
-		$relativePath = $path;
1200
-		$path = $this->getHookPath($path);
1201
-		$prefix = ($post) ? 'post_' : '';
1202
-		$run = true;
1203
-		if ($this->shouldEmitHooks($relativePath)) {
1204
-			foreach ($hooks as $hook) {
1205
-				if ($hook != 'read') {
1206
-					\OC_Hook::emit(
1207
-						Filesystem::CLASSNAME,
1208
-						$prefix . $hook,
1209
-						array(
1210
-							Filesystem::signal_param_run => &$run,
1211
-							Filesystem::signal_param_path => $path
1212
-						)
1213
-					);
1214
-				} elseif (!$post) {
1215
-					\OC_Hook::emit(
1216
-						Filesystem::CLASSNAME,
1217
-						$prefix . $hook,
1218
-						array(
1219
-							Filesystem::signal_param_path => $path
1220
-						)
1221
-					);
1222
-				}
1223
-			}
1224
-		}
1225
-		return $run;
1226
-	}
1227
-
1228
-	/**
1229
-	 * check if a file or folder has been updated since $time
1230
-	 *
1231
-	 * @param string $path
1232
-	 * @param int $time
1233
-	 * @return bool
1234
-	 */
1235
-	public function hasUpdated($path, $time) {
1236
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1237
-	}
1238
-
1239
-	/**
1240
-	 * @param string $ownerId
1241
-	 * @return \OC\User\User
1242
-	 */
1243
-	private function getUserObjectForOwner($ownerId) {
1244
-		$owner = $this->userManager->get($ownerId);
1245
-		if ($owner instanceof IUser) {
1246
-			return $owner;
1247
-		} else {
1248
-			return new User($ownerId, null);
1249
-		}
1250
-	}
1251
-
1252
-	/**
1253
-	 * Get file info from cache
1254
-	 *
1255
-	 * If the file is not in cached it will be scanned
1256
-	 * If the file has changed on storage the cache will be updated
1257
-	 *
1258
-	 * @param \OC\Files\Storage\Storage $storage
1259
-	 * @param string $internalPath
1260
-	 * @param string $relativePath
1261
-	 * @return array|bool
1262
-	 */
1263
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1264
-		$cache = $storage->getCache($internalPath);
1265
-		$data = $cache->get($internalPath);
1266
-		$watcher = $storage->getWatcher($internalPath);
1267
-
1268
-		try {
1269
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1270
-			if (!$data || $data['size'] === -1) {
1271
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1272
-				if (!$storage->file_exists($internalPath)) {
1273
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1274
-					return false;
1275
-				}
1276
-				$scanner = $storage->getScanner($internalPath);
1277
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1278
-				$data = $cache->get($internalPath);
1279
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1280
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1281
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1282
-				$watcher->update($internalPath, $data);
1283
-				$storage->getPropagator()->propagateChange($internalPath, time());
1284
-				$data = $cache->get($internalPath);
1285
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1286
-			}
1287
-		} catch (LockedException $e) {
1288
-			// if the file is locked we just use the old cache info
1289
-		}
1290
-
1291
-		return $data;
1292
-	}
1293
-
1294
-	/**
1295
-	 * get the filesystem info
1296
-	 *
1297
-	 * @param string $path
1298
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1299
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1300
-	 * defaults to true
1301
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1302
-	 */
1303
-	public function getFileInfo($path, $includeMountPoints = true) {
1304
-		$this->assertPathLength($path);
1305
-		if (!Filesystem::isValidPath($path)) {
1306
-			return false;
1307
-		}
1308
-		if (Cache\Scanner::isPartialFile($path)) {
1309
-			return $this->getPartFileInfo($path);
1310
-		}
1311
-		$relativePath = $path;
1312
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1313
-
1314
-		$mount = Filesystem::getMountManager()->find($path);
1315
-		$storage = $mount->getStorage();
1316
-		$internalPath = $mount->getInternalPath($path);
1317
-		if ($storage) {
1318
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1319
-
1320
-			if (!$data instanceof ICacheEntry) {
1321
-				return false;
1322
-			}
1323
-
1324
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1325
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1326
-			}
1327
-
1328
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1329
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1330
-
1331
-			if ($data and isset($data['fileid'])) {
1332
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1333
-					//add the sizes of other mount points to the folder
1334
-					$extOnly = ($includeMountPoints === 'ext');
1335
-					$mounts = Filesystem::getMountManager()->findIn($path);
1336
-					foreach ($mounts as $mount) {
1337
-						$subStorage = $mount->getStorage();
1338
-						if ($subStorage) {
1339
-							// exclude shared storage ?
1340
-							if ($extOnly && $subStorage instanceof \OC\Files\Storage\Shared) {
1341
-								continue;
1342
-							}
1343
-							$subCache = $subStorage->getCache('');
1344
-							$rootEntry = $subCache->get('');
1345
-							$info->addSubEntry($rootEntry, $mount->getMountPoint());
1346
-						}
1347
-					}
1348
-				}
1349
-			}
1350
-
1351
-			return $info;
1352
-		}
1353
-
1354
-		return false;
1355
-	}
1356
-
1357
-	/**
1358
-	 * get the content of a directory
1359
-	 *
1360
-	 * @param string $directory path under datadirectory
1361
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1362
-	 * @return FileInfo[]
1363
-	 */
1364
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1365
-		$this->assertPathLength($directory);
1366
-		if (!Filesystem::isValidPath($directory)) {
1367
-			return [];
1368
-		}
1369
-		$path = $this->getAbsolutePath($directory);
1370
-		$path = Filesystem::normalizePath($path);
1371
-		$mount = $this->getMount($directory);
1372
-		$storage = $mount->getStorage();
1373
-		$internalPath = $mount->getInternalPath($path);
1374
-		if ($storage) {
1375
-			$cache = $storage->getCache($internalPath);
1376
-			$user = \OC_User::getUser();
1377
-
1378
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1379
-
1380
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1381
-				return [];
1382
-			}
1383
-
1384
-			$folderId = $data['fileid'];
1385
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1386
-
1387
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1388
-			/**
1389
-			 * @var \OC\Files\FileInfo[] $files
1390
-			 */
1391
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1392
-				if ($sharingDisabled) {
1393
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1394
-				}
1395
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1396
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1397
-			}, $contents);
1398
-
1399
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1400
-			$mounts = Filesystem::getMountManager()->findIn($path);
1401
-			$dirLength = strlen($path);
1402
-			foreach ($mounts as $mount) {
1403
-				$mountPoint = $mount->getMountPoint();
1404
-				$subStorage = $mount->getStorage();
1405
-				if ($subStorage) {
1406
-					$subCache = $subStorage->getCache('');
1407
-
1408
-					$rootEntry = $subCache->get('');
1409
-					if (!$rootEntry) {
1410
-						$subScanner = $subStorage->getScanner('');
1411
-						try {
1412
-							$subScanner->scanFile('');
1413
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1414
-							continue;
1415
-						} catch (\OCP\Files\StorageInvalidException $e) {
1416
-							continue;
1417
-						} catch (\Exception $e) {
1418
-							// sometimes when the storage is not available it can be any exception
1419
-							\OCP\Util::writeLog(
1420
-								'core',
1421
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1422
-								get_class($e) . ': ' . $e->getMessage(),
1423
-								\OCP\Util::ERROR
1424
-							);
1425
-							continue;
1426
-						}
1427
-						$rootEntry = $subCache->get('');
1428
-					}
1429
-
1430
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1431
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1432
-						if ($pos = strpos($relativePath, '/')) {
1433
-							//mountpoint inside subfolder add size to the correct folder
1434
-							$entryName = substr($relativePath, 0, $pos);
1435
-							foreach ($files as &$entry) {
1436
-								if ($entry->getName() === $entryName) {
1437
-									$entry->addSubEntry($rootEntry, $mountPoint);
1438
-								}
1439
-							}
1440
-						} else { //mountpoint in this folder, add an entry for it
1441
-							$rootEntry['name'] = $relativePath;
1442
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1443
-							$permissions = $rootEntry['permissions'];
1444
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1445
-							// for shared files/folders we use the permissions given by the owner
1446
-							if ($mount instanceof MoveableMount) {
1447
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1448
-							} else {
1449
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1450
-							}
1451
-
1452
-							//remove any existing entry with the same name
1453
-							foreach ($files as $i => $file) {
1454
-								if ($file['name'] === $rootEntry['name']) {
1455
-									unset($files[$i]);
1456
-									break;
1457
-								}
1458
-							}
1459
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1460
-
1461
-							// if sharing was disabled for the user we remove the share permissions
1462
-							if (\OCP\Util::isSharingDisabledForUser()) {
1463
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1464
-							}
1465
-
1466
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1467
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1468
-						}
1469
-					}
1470
-				}
1471
-			}
1472
-
1473
-			if ($mimetype_filter) {
1474
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1475
-					if (strpos($mimetype_filter, '/')) {
1476
-						return $file->getMimetype() === $mimetype_filter;
1477
-					} else {
1478
-						return $file->getMimePart() === $mimetype_filter;
1479
-					}
1480
-				});
1481
-			}
1482
-
1483
-			return $files;
1484
-		} else {
1485
-			return [];
1486
-		}
1487
-	}
1488
-
1489
-	/**
1490
-	 * change file metadata
1491
-	 *
1492
-	 * @param string $path
1493
-	 * @param array|\OCP\Files\FileInfo $data
1494
-	 * @return int
1495
-	 *
1496
-	 * returns the fileid of the updated file
1497
-	 */
1498
-	public function putFileInfo($path, $data) {
1499
-		$this->assertPathLength($path);
1500
-		if ($data instanceof FileInfo) {
1501
-			$data = $data->getData();
1502
-		}
1503
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1504
-		/**
1505
-		 * @var \OC\Files\Storage\Storage $storage
1506
-		 * @var string $internalPath
1507
-		 */
1508
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1509
-		if ($storage) {
1510
-			$cache = $storage->getCache($path);
1511
-
1512
-			if (!$cache->inCache($internalPath)) {
1513
-				$scanner = $storage->getScanner($internalPath);
1514
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1515
-			}
1516
-
1517
-			return $cache->put($internalPath, $data);
1518
-		} else {
1519
-			return -1;
1520
-		}
1521
-	}
1522
-
1523
-	/**
1524
-	 * search for files with the name matching $query
1525
-	 *
1526
-	 * @param string $query
1527
-	 * @return FileInfo[]
1528
-	 */
1529
-	public function search($query) {
1530
-		return $this->searchCommon('search', array('%' . $query . '%'));
1531
-	}
1532
-
1533
-	/**
1534
-	 * search for files with the name matching $query
1535
-	 *
1536
-	 * @param string $query
1537
-	 * @return FileInfo[]
1538
-	 */
1539
-	public function searchRaw($query) {
1540
-		return $this->searchCommon('search', array($query));
1541
-	}
1542
-
1543
-	/**
1544
-	 * search for files by mimetype
1545
-	 *
1546
-	 * @param string $mimetype
1547
-	 * @return FileInfo[]
1548
-	 */
1549
-	public function searchByMime($mimetype) {
1550
-		return $this->searchCommon('searchByMime', array($mimetype));
1551
-	}
1552
-
1553
-	/**
1554
-	 * search for files by tag
1555
-	 *
1556
-	 * @param string|int $tag name or tag id
1557
-	 * @param string $userId owner of the tags
1558
-	 * @return FileInfo[]
1559
-	 */
1560
-	public function searchByTag($tag, $userId) {
1561
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1562
-	}
1563
-
1564
-	/**
1565
-	 * @param string $method cache method
1566
-	 * @param array $args
1567
-	 * @return FileInfo[]
1568
-	 */
1569
-	private function searchCommon($method, $args) {
1570
-		$files = array();
1571
-		$rootLength = strlen($this->fakeRoot);
1572
-
1573
-		$mount = $this->getMount('');
1574
-		$mountPoint = $mount->getMountPoint();
1575
-		$storage = $mount->getStorage();
1576
-		if ($storage) {
1577
-			$cache = $storage->getCache('');
1578
-
1579
-			$results = call_user_func_array(array($cache, $method), $args);
1580
-			foreach ($results as $result) {
1581
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1582
-					$internalPath = $result['path'];
1583
-					$path = $mountPoint . $result['path'];
1584
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1585
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1586
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1587
-				}
1588
-			}
1589
-
1590
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1591
-			foreach ($mounts as $mount) {
1592
-				$mountPoint = $mount->getMountPoint();
1593
-				$storage = $mount->getStorage();
1594
-				if ($storage) {
1595
-					$cache = $storage->getCache('');
1596
-
1597
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1598
-					$results = call_user_func_array(array($cache, $method), $args);
1599
-					if ($results) {
1600
-						foreach ($results as $result) {
1601
-							$internalPath = $result['path'];
1602
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1603
-							$path = rtrim($mountPoint . $internalPath, '/');
1604
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1605
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1606
-						}
1607
-					}
1608
-				}
1609
-			}
1610
-		}
1611
-		return $files;
1612
-	}
1613
-
1614
-	/**
1615
-	 * Get the owner for a file or folder
1616
-	 *
1617
-	 * @param string $path
1618
-	 * @return string the user id of the owner
1619
-	 * @throws NotFoundException
1620
-	 */
1621
-	public function getOwner($path) {
1622
-		$info = $this->getFileInfo($path);
1623
-		if (!$info) {
1624
-			throw new NotFoundException($path . ' not found while trying to get owner');
1625
-		}
1626
-		return $info->getOwner()->getUID();
1627
-	}
1628
-
1629
-	/**
1630
-	 * get the ETag for a file or folder
1631
-	 *
1632
-	 * @param string $path
1633
-	 * @return string
1634
-	 */
1635
-	public function getETag($path) {
1636
-		/**
1637
-		 * @var Storage\Storage $storage
1638
-		 * @var string $internalPath
1639
-		 */
1640
-		list($storage, $internalPath) = $this->resolvePath($path);
1641
-		if ($storage) {
1642
-			return $storage->getETag($internalPath);
1643
-		} else {
1644
-			return null;
1645
-		}
1646
-	}
1647
-
1648
-	/**
1649
-	 * Get the path of a file by id, relative to the view
1650
-	 *
1651
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1652
-	 *
1653
-	 * @param int $id
1654
-	 * @throws NotFoundException
1655
-	 * @return string
1656
-	 */
1657
-	public function getPath($id) {
1658
-		$id = (int)$id;
1659
-		$manager = Filesystem::getMountManager();
1660
-		$mounts = $manager->findIn($this->fakeRoot);
1661
-		$mounts[] = $manager->find($this->fakeRoot);
1662
-		// reverse the array so we start with the storage this view is in
1663
-		// which is the most likely to contain the file we're looking for
1664
-		$mounts = array_reverse($mounts);
1665
-		foreach ($mounts as $mount) {
1666
-			/**
1667
-			 * @var \OC\Files\Mount\MountPoint $mount
1668
-			 */
1669
-			if ($mount->getStorage()) {
1670
-				$cache = $mount->getStorage()->getCache();
1671
-				$internalPath = $cache->getPathById($id);
1672
-				if (is_string($internalPath)) {
1673
-					$fullPath = $mount->getMountPoint() . $internalPath;
1674
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1675
-						return $path;
1676
-					}
1677
-				}
1678
-			}
1679
-		}
1680
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1681
-	}
1682
-
1683
-	/**
1684
-	 * @param string $path
1685
-	 * @throws InvalidPathException
1686
-	 */
1687
-	private function assertPathLength($path) {
1688
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1689
-		// Check for the string length - performed using isset() instead of strlen()
1690
-		// because isset() is about 5x-40x faster.
1691
-		if (isset($path[$maxLen])) {
1692
-			$pathLen = strlen($path);
1693
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1694
-		}
1695
-	}
1696
-
1697
-	/**
1698
-	 * check if it is allowed to move a mount point to a given target.
1699
-	 * It is not allowed to move a mount point into a different mount point or
1700
-	 * into an already shared folder
1701
-	 *
1702
-	 * @param string $target path
1703
-	 * @return boolean
1704
-	 */
1705
-	private function isTargetAllowed($target) {
1706
-
1707
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1708
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1709
-			\OCP\Util::writeLog('files',
1710
-				'It is not allowed to move one mount point into another one',
1711
-				\OCP\Util::DEBUG);
1712
-			return false;
1713
-		}
1714
-
1715
-		// note: cannot use the view because the target is already locked
1716
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1717
-		if ($fileId === -1) {
1718
-			// target might not exist, need to check parent instead
1719
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1720
-		}
1721
-
1722
-		// check if any of the parents were shared by the current owner (include collections)
1723
-		$shares = \OCP\Share::getItemShared(
1724
-			'folder',
1725
-			$fileId,
1726
-			\OCP\Share::FORMAT_NONE,
1727
-			null,
1728
-			true
1729
-		);
1730
-
1731
-		if (count($shares) > 0) {
1732
-			\OCP\Util::writeLog('files',
1733
-				'It is not allowed to move one mount point into a shared folder',
1734
-				\OCP\Util::DEBUG);
1735
-			return false;
1736
-		}
1737
-
1738
-		return true;
1739
-	}
1740
-
1741
-	/**
1742
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1743
-	 *
1744
-	 * @param string $path
1745
-	 * @return \OCP\Files\FileInfo
1746
-	 */
1747
-	private function getPartFileInfo($path) {
1748
-		$mount = $this->getMount($path);
1749
-		$storage = $mount->getStorage();
1750
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1751
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1752
-		return new FileInfo(
1753
-			$this->getAbsolutePath($path),
1754
-			$storage,
1755
-			$internalPath,
1756
-			[
1757
-				'fileid' => null,
1758
-				'mimetype' => $storage->getMimeType($internalPath),
1759
-				'name' => basename($path),
1760
-				'etag' => null,
1761
-				'size' => $storage->filesize($internalPath),
1762
-				'mtime' => $storage->filemtime($internalPath),
1763
-				'encrypted' => false,
1764
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1765
-			],
1766
-			$mount,
1767
-			$owner
1768
-		);
1769
-	}
1770
-
1771
-	/**
1772
-	 * @param string $path
1773
-	 * @param string $fileName
1774
-	 * @throws InvalidPathException
1775
-	 */
1776
-	public function verifyPath($path, $fileName) {
1777
-
1778
-		$l10n = \OC::$server->getL10N('lib');
1779
-
1780
-		// verify empty and dot files
1781
-		$trimmed = trim($fileName);
1782
-		if ($trimmed === '') {
1783
-			throw new InvalidPathException($l10n->t('Empty filename is not allowed'));
1784
-		}
1785
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1786
-			throw new InvalidPathException($l10n->t('Dot files are not allowed'));
1787
-		}
1788
-
1789
-		// verify database - e.g. mysql only 3-byte chars
1790
-		if (preg_match('%(?:
82
+    /** @var string */
83
+    private $fakeRoot = '';
84
+
85
+    /**
86
+     * @var \OCP\Lock\ILockingProvider
87
+     */
88
+    private $lockingProvider;
89
+
90
+    private $lockingEnabled;
91
+
92
+    private $updaterEnabled = true;
93
+
94
+    private $userManager;
95
+
96
+    /**
97
+     * @param string $root
98
+     * @throws \Exception If $root contains an invalid path
99
+     */
100
+    public function __construct($root = '') {
101
+        if (is_null($root)) {
102
+            throw new \InvalidArgumentException('Root can\'t be null');
103
+        }
104
+        if (!Filesystem::isValidPath($root)) {
105
+            throw new \Exception();
106
+        }
107
+
108
+        $this->fakeRoot = $root;
109
+        $this->lockingProvider = \OC::$server->getLockingProvider();
110
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
111
+        $this->userManager = \OC::$server->getUserManager();
112
+    }
113
+
114
+    public function getAbsolutePath($path = '/') {
115
+        if ($path === null) {
116
+            return null;
117
+        }
118
+        $this->assertPathLength($path);
119
+        if ($path === '') {
120
+            $path = '/';
121
+        }
122
+        if ($path[0] !== '/') {
123
+            $path = '/' . $path;
124
+        }
125
+        return $this->fakeRoot . $path;
126
+    }
127
+
128
+    /**
129
+     * change the root to a fake root
130
+     *
131
+     * @param string $fakeRoot
132
+     * @return boolean|null
133
+     */
134
+    public function chroot($fakeRoot) {
135
+        if (!$fakeRoot == '') {
136
+            if ($fakeRoot[0] !== '/') {
137
+                $fakeRoot = '/' . $fakeRoot;
138
+            }
139
+        }
140
+        $this->fakeRoot = $fakeRoot;
141
+    }
142
+
143
+    /**
144
+     * get the fake root
145
+     *
146
+     * @return string
147
+     */
148
+    public function getRoot() {
149
+        return $this->fakeRoot;
150
+    }
151
+
152
+    /**
153
+     * get path relative to the root of the view
154
+     *
155
+     * @param string $path
156
+     * @return string
157
+     */
158
+    public function getRelativePath($path) {
159
+        $this->assertPathLength($path);
160
+        if ($this->fakeRoot == '') {
161
+            return $path;
162
+        }
163
+
164
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
165
+            return '/';
166
+        }
167
+
168
+        // missing slashes can cause wrong matches!
169
+        $root = rtrim($this->fakeRoot, '/') . '/';
170
+
171
+        if (strpos($path, $root) !== 0) {
172
+            return null;
173
+        } else {
174
+            $path = substr($path, strlen($this->fakeRoot));
175
+            if (strlen($path) === 0) {
176
+                return '/';
177
+            } else {
178
+                return $path;
179
+            }
180
+        }
181
+    }
182
+
183
+    /**
184
+     * get the mountpoint of the storage object for a path
185
+     * ( note: because a storage is not always mounted inside the fakeroot, the
186
+     * returned mountpoint is relative to the absolute root of the filesystem
187
+     * and does not take the chroot into account )
188
+     *
189
+     * @param string $path
190
+     * @return string
191
+     */
192
+    public function getMountPoint($path) {
193
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
194
+    }
195
+
196
+    /**
197
+     * get the mountpoint of the storage object for a path
198
+     * ( note: because a storage is not always mounted inside the fakeroot, the
199
+     * returned mountpoint is relative to the absolute root of the filesystem
200
+     * and does not take the chroot into account )
201
+     *
202
+     * @param string $path
203
+     * @return \OCP\Files\Mount\IMountPoint
204
+     */
205
+    public function getMount($path) {
206
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
207
+    }
208
+
209
+    /**
210
+     * resolve a path to a storage and internal path
211
+     *
212
+     * @param string $path
213
+     * @return array an array consisting of the storage and the internal path
214
+     */
215
+    public function resolvePath($path) {
216
+        $a = $this->getAbsolutePath($path);
217
+        $p = Filesystem::normalizePath($a);
218
+        return Filesystem::resolvePath($p);
219
+    }
220
+
221
+    /**
222
+     * return the path to a local version of the file
223
+     * we need this because we can't know if a file is stored local or not from
224
+     * outside the filestorage and for some purposes a local file is needed
225
+     *
226
+     * @param string $path
227
+     * @return string
228
+     */
229
+    public function getLocalFile($path) {
230
+        $parent = substr($path, 0, strrpos($path, '/'));
231
+        $path = $this->getAbsolutePath($path);
232
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
233
+        if (Filesystem::isValidPath($parent) and $storage) {
234
+            return $storage->getLocalFile($internalPath);
235
+        } else {
236
+            return null;
237
+        }
238
+    }
239
+
240
+    /**
241
+     * @param string $path
242
+     * @return string
243
+     */
244
+    public function getLocalFolder($path) {
245
+        $parent = substr($path, 0, strrpos($path, '/'));
246
+        $path = $this->getAbsolutePath($path);
247
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
248
+        if (Filesystem::isValidPath($parent) and $storage) {
249
+            return $storage->getLocalFolder($internalPath);
250
+        } else {
251
+            return null;
252
+        }
253
+    }
254
+
255
+    /**
256
+     * the following functions operate with arguments and return values identical
257
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
258
+     * for \OC\Files\Storage\Storage via basicOperation().
259
+     */
260
+    public function mkdir($path) {
261
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
262
+    }
263
+
264
+    /**
265
+     * remove mount point
266
+     *
267
+     * @param \OC\Files\Mount\MoveableMount $mount
268
+     * @param string $path relative to data/
269
+     * @return boolean
270
+     */
271
+    protected function removeMount($mount, $path) {
272
+        if ($mount instanceof MoveableMount) {
273
+            // cut of /user/files to get the relative path to data/user/files
274
+            $pathParts = explode('/', $path, 4);
275
+            $relPath = '/' . $pathParts[3];
276
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
277
+            \OC_Hook::emit(
278
+                Filesystem::CLASSNAME, "umount",
279
+                array(Filesystem::signal_param_path => $relPath)
280
+            );
281
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
282
+            $result = $mount->removeMount();
283
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
284
+            if ($result) {
285
+                \OC_Hook::emit(
286
+                    Filesystem::CLASSNAME, "post_umount",
287
+                    array(Filesystem::signal_param_path => $relPath)
288
+                );
289
+            }
290
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
291
+            return $result;
292
+        } else {
293
+            // do not allow deleting the storage's root / the mount point
294
+            // because for some storages it might delete the whole contents
295
+            // but isn't supposed to work that way
296
+            return false;
297
+        }
298
+    }
299
+
300
+    public function disableCacheUpdate() {
301
+        $this->updaterEnabled = false;
302
+    }
303
+
304
+    public function enableCacheUpdate() {
305
+        $this->updaterEnabled = true;
306
+    }
307
+
308
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
309
+        if ($this->updaterEnabled) {
310
+            if (is_null($time)) {
311
+                $time = time();
312
+            }
313
+            $storage->getUpdater()->update($internalPath, $time);
314
+        }
315
+    }
316
+
317
+    protected function removeUpdate(Storage $storage, $internalPath) {
318
+        if ($this->updaterEnabled) {
319
+            $storage->getUpdater()->remove($internalPath);
320
+        }
321
+    }
322
+
323
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
324
+        if ($this->updaterEnabled) {
325
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
326
+        }
327
+    }
328
+
329
+    /**
330
+     * @param string $path
331
+     * @return bool|mixed
332
+     */
333
+    public function rmdir($path) {
334
+        $absolutePath = $this->getAbsolutePath($path);
335
+        $mount = Filesystem::getMountManager()->find($absolutePath);
336
+        if ($mount->getInternalPath($absolutePath) === '') {
337
+            return $this->removeMount($mount, $absolutePath);
338
+        }
339
+        if ($this->is_dir($path)) {
340
+            return $this->basicOperation('rmdir', $path, array('delete'));
341
+        } else {
342
+            return false;
343
+        }
344
+    }
345
+
346
+    /**
347
+     * @param string $path
348
+     * @return resource
349
+     */
350
+    public function opendir($path) {
351
+        return $this->basicOperation('opendir', $path, array('read'));
352
+    }
353
+
354
+    /**
355
+     * @param $handle
356
+     * @return mixed
357
+     */
358
+    public function readdir($handle) {
359
+        $fsLocal = new Storage\Local(array('datadir' => '/'));
360
+        return $fsLocal->readdir($handle);
361
+    }
362
+
363
+    /**
364
+     * @param string $path
365
+     * @return bool|mixed
366
+     */
367
+    public function is_dir($path) {
368
+        if ($path == '/') {
369
+            return true;
370
+        }
371
+        return $this->basicOperation('is_dir', $path);
372
+    }
373
+
374
+    /**
375
+     * @param string $path
376
+     * @return bool|mixed
377
+     */
378
+    public function is_file($path) {
379
+        if ($path == '/') {
380
+            return false;
381
+        }
382
+        return $this->basicOperation('is_file', $path);
383
+    }
384
+
385
+    /**
386
+     * @param string $path
387
+     * @return mixed
388
+     */
389
+    public function stat($path) {
390
+        return $this->basicOperation('stat', $path);
391
+    }
392
+
393
+    /**
394
+     * @param string $path
395
+     * @return mixed
396
+     */
397
+    public function filetype($path) {
398
+        return $this->basicOperation('filetype', $path);
399
+    }
400
+
401
+    /**
402
+     * @param string $path
403
+     * @return mixed
404
+     */
405
+    public function filesize($path) {
406
+        return $this->basicOperation('filesize', $path);
407
+    }
408
+
409
+    /**
410
+     * @param string $path
411
+     * @return bool|mixed
412
+     * @throws \OCP\Files\InvalidPathException
413
+     */
414
+    public function readfile($path) {
415
+        $this->assertPathLength($path);
416
+        @ob_end_clean();
417
+        $handle = $this->fopen($path, 'rb');
418
+        if ($handle) {
419
+            $chunkSize = 8192; // 8 kB chunks
420
+            while (!feof($handle)) {
421
+                echo fread($handle, $chunkSize);
422
+                flush();
423
+            }
424
+            $size = $this->filesize($path);
425
+            return $size;
426
+        }
427
+        return false;
428
+    }
429
+
430
+    /**
431
+     * @param string $path
432
+     * @param int $from 
433
+     * @param int $to
434
+     * @return bool|mixed
435
+     * @throws \OCP\Files\InvalidPathException
436
+     * @throws \OCP\Files\NotPermittedException
437
+     */
438
+    public function readfilePart($path, $from, $to) {
439
+        $this->assertPathLength($path);
440
+        @ob_end_clean();
441
+        $handle = $this->fopen($path, 'rb');
442
+        if ($handle) {
443
+            if (fseek($handle, $from) === 0) {
444
+                $chunkSize = 8192; // 8 kB chunks
445
+                $end = $to + 1;
446
+                while (!feof($handle) && ftell($handle) < $end) {
447
+                $len = $end-ftell($handle);
448
+                if ($len > $chunkSize) { 
449
+                    $len = $chunkSize; 
450
+                }
451
+                echo fread($handle, $len);
452
+                flush();
453
+                }
454
+                $size = ftell($handle) - $from;
455
+                return $size;
456
+            }
457
+
458
+            throw new \OCP\Files\NotPermittedException('fseek error');
459
+        }
460
+        return false;
461
+    }
462
+
463
+    /**
464
+     * @param string $path
465
+     * @return mixed
466
+     */
467
+    public function isCreatable($path) {
468
+        return $this->basicOperation('isCreatable', $path);
469
+    }
470
+
471
+    /**
472
+     * @param string $path
473
+     * @return mixed
474
+     */
475
+    public function isReadable($path) {
476
+        return $this->basicOperation('isReadable', $path);
477
+    }
478
+
479
+    /**
480
+     * @param string $path
481
+     * @return mixed
482
+     */
483
+    public function isUpdatable($path) {
484
+        return $this->basicOperation('isUpdatable', $path);
485
+    }
486
+
487
+    /**
488
+     * @param string $path
489
+     * @return bool|mixed
490
+     */
491
+    public function isDeletable($path) {
492
+        $absolutePath = $this->getAbsolutePath($path);
493
+        $mount = Filesystem::getMountManager()->find($absolutePath);
494
+        if ($mount->getInternalPath($absolutePath) === '') {
495
+            return $mount instanceof MoveableMount;
496
+        }
497
+        return $this->basicOperation('isDeletable', $path);
498
+    }
499
+
500
+    /**
501
+     * @param string $path
502
+     * @return mixed
503
+     */
504
+    public function isSharable($path) {
505
+        return $this->basicOperation('isSharable', $path);
506
+    }
507
+
508
+    /**
509
+     * @param string $path
510
+     * @return bool|mixed
511
+     */
512
+    public function file_exists($path) {
513
+        if ($path == '/') {
514
+            return true;
515
+        }
516
+        return $this->basicOperation('file_exists', $path);
517
+    }
518
+
519
+    /**
520
+     * @param string $path
521
+     * @return mixed
522
+     */
523
+    public function filemtime($path) {
524
+        return $this->basicOperation('filemtime', $path);
525
+    }
526
+
527
+    /**
528
+     * @param string $path
529
+     * @param int|string $mtime
530
+     * @return bool
531
+     */
532
+    public function touch($path, $mtime = null) {
533
+        if (!is_null($mtime) and !is_numeric($mtime)) {
534
+            $mtime = strtotime($mtime);
535
+        }
536
+
537
+        $hooks = array('touch');
538
+
539
+        if (!$this->file_exists($path)) {
540
+            $hooks[] = 'create';
541
+            $hooks[] = 'write';
542
+        }
543
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
544
+        if (!$result) {
545
+            // If create file fails because of permissions on external storage like SMB folders,
546
+            // check file exists and return false if not.
547
+            if (!$this->file_exists($path)) {
548
+                return false;
549
+            }
550
+            if (is_null($mtime)) {
551
+                $mtime = time();
552
+            }
553
+            //if native touch fails, we emulate it by changing the mtime in the cache
554
+            $this->putFileInfo($path, array('mtime' => $mtime));
555
+        }
556
+        return true;
557
+    }
558
+
559
+    /**
560
+     * @param string $path
561
+     * @return mixed
562
+     */
563
+    public function file_get_contents($path) {
564
+        return $this->basicOperation('file_get_contents', $path, array('read'));
565
+    }
566
+
567
+    /**
568
+     * @param bool $exists
569
+     * @param string $path
570
+     * @param bool $run
571
+     */
572
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
573
+        if (!$exists) {
574
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
575
+                Filesystem::signal_param_path => $this->getHookPath($path),
576
+                Filesystem::signal_param_run => &$run,
577
+            ));
578
+        } else {
579
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
580
+                Filesystem::signal_param_path => $this->getHookPath($path),
581
+                Filesystem::signal_param_run => &$run,
582
+            ));
583
+        }
584
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
585
+            Filesystem::signal_param_path => $this->getHookPath($path),
586
+            Filesystem::signal_param_run => &$run,
587
+        ));
588
+    }
589
+
590
+    /**
591
+     * @param bool $exists
592
+     * @param string $path
593
+     */
594
+    protected function emit_file_hooks_post($exists, $path) {
595
+        if (!$exists) {
596
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
597
+                Filesystem::signal_param_path => $this->getHookPath($path),
598
+            ));
599
+        } else {
600
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
601
+                Filesystem::signal_param_path => $this->getHookPath($path),
602
+            ));
603
+        }
604
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
605
+            Filesystem::signal_param_path => $this->getHookPath($path),
606
+        ));
607
+    }
608
+
609
+    /**
610
+     * @param string $path
611
+     * @param mixed $data
612
+     * @return bool|mixed
613
+     * @throws \Exception
614
+     */
615
+    public function file_put_contents($path, $data) {
616
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
617
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
618
+            if (Filesystem::isValidPath($path)
619
+                and !Filesystem::isFileBlacklisted($path)
620
+            ) {
621
+                $path = $this->getRelativePath($absolutePath);
622
+
623
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
624
+
625
+                $exists = $this->file_exists($path);
626
+                $run = true;
627
+                if ($this->shouldEmitHooks($path)) {
628
+                    $this->emit_file_hooks_pre($exists, $path, $run);
629
+                }
630
+                if (!$run) {
631
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
632
+                    return false;
633
+                }
634
+
635
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
636
+
637
+                /** @var \OC\Files\Storage\Storage $storage */
638
+                list($storage, $internalPath) = $this->resolvePath($path);
639
+                $target = $storage->fopen($internalPath, 'w');
640
+                if ($target) {
641
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
642
+                    fclose($target);
643
+                    fclose($data);
644
+
645
+                    $this->writeUpdate($storage, $internalPath);
646
+
647
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
648
+
649
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
650
+                        $this->emit_file_hooks_post($exists, $path);
651
+                    }
652
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
653
+                    return $result;
654
+                } else {
655
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
656
+                    return false;
657
+                }
658
+            } else {
659
+                return false;
660
+            }
661
+        } else {
662
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
663
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
664
+        }
665
+    }
666
+
667
+    /**
668
+     * @param string $path
669
+     * @return bool|mixed
670
+     */
671
+    public function unlink($path) {
672
+        if ($path === '' || $path === '/') {
673
+            // do not allow deleting the root
674
+            return false;
675
+        }
676
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
677
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
678
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
679
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
680
+            return $this->removeMount($mount, $absolutePath);
681
+        }
682
+        return $this->basicOperation('unlink', $path, array('delete'));
683
+    }
684
+
685
+    /**
686
+     * @param string $directory
687
+     * @return bool|mixed
688
+     */
689
+    public function deleteAll($directory) {
690
+        return $this->rmdir($directory);
691
+    }
692
+
693
+    /**
694
+     * Rename/move a file or folder from the source path to target path.
695
+     *
696
+     * @param string $path1 source path
697
+     * @param string $path2 target path
698
+     *
699
+     * @return bool|mixed
700
+     */
701
+    public function rename($path1, $path2) {
702
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
703
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
704
+        $result = false;
705
+        if (
706
+            Filesystem::isValidPath($path2)
707
+            and Filesystem::isValidPath($path1)
708
+            and !Filesystem::isFileBlacklisted($path2)
709
+        ) {
710
+            $path1 = $this->getRelativePath($absolutePath1);
711
+            $path2 = $this->getRelativePath($absolutePath2);
712
+            $exists = $this->file_exists($path2);
713
+
714
+            if ($path1 == null or $path2 == null) {
715
+                return false;
716
+            }
717
+
718
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
719
+            try {
720
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
721
+            } catch (LockedException $e) {
722
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
723
+                throw $e;
724
+            }
725
+
726
+            $run = true;
727
+            if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
728
+                // if it was a rename from a part file to a regular file it was a write and not a rename operation
729
+                $this->emit_file_hooks_pre($exists, $path2, $run);
730
+            } elseif ($this->shouldEmitHooks($path1)) {
731
+                \OC_Hook::emit(
732
+                    Filesystem::CLASSNAME, Filesystem::signal_rename,
733
+                    array(
734
+                        Filesystem::signal_param_oldpath => $this->getHookPath($path1),
735
+                        Filesystem::signal_param_newpath => $this->getHookPath($path2),
736
+                        Filesystem::signal_param_run => &$run
737
+                    )
738
+                );
739
+            }
740
+            if ($run) {
741
+                $this->verifyPath(dirname($path2), basename($path2));
742
+
743
+                $manager = Filesystem::getMountManager();
744
+                $mount1 = $this->getMount($path1);
745
+                $mount2 = $this->getMount($path2);
746
+                $storage1 = $mount1->getStorage();
747
+                $storage2 = $mount2->getStorage();
748
+                $internalPath1 = $mount1->getInternalPath($absolutePath1);
749
+                $internalPath2 = $mount2->getInternalPath($absolutePath2);
750
+
751
+                $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
752
+                $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
753
+
754
+                if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
755
+                    if ($this->isTargetAllowed($absolutePath2)) {
756
+                        /**
757
+                         * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
758
+                         */
759
+                        $sourceMountPoint = $mount1->getMountPoint();
760
+                        $result = $mount1->moveMount($absolutePath2);
761
+                        $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
762
+                    } else {
763
+                        $result = false;
764
+                    }
765
+                    // moving a file/folder within the same mount point
766
+                } elseif ($storage1 === $storage2) {
767
+                    if ($storage1) {
768
+                        $result = $storage1->rename($internalPath1, $internalPath2);
769
+                    } else {
770
+                        $result = false;
771
+                    }
772
+                    // moving a file/folder between storages (from $storage1 to $storage2)
773
+                } else {
774
+                    $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
775
+                }
776
+
777
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
778
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
779
+
780
+                    $this->writeUpdate($storage2, $internalPath2);
781
+                } else if ($result) {
782
+                    if ($internalPath1 !== '') { // dont do a cache update for moved mounts
783
+                        $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
784
+                    }
785
+                }
786
+
787
+                $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
788
+                $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
789
+
790
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
791
+                    if ($this->shouldEmitHooks()) {
792
+                        $this->emit_file_hooks_post($exists, $path2);
793
+                    }
794
+                } elseif ($result) {
795
+                    if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
796
+                        \OC_Hook::emit(
797
+                            Filesystem::CLASSNAME,
798
+                            Filesystem::signal_post_rename,
799
+                            array(
800
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
801
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
802
+                            )
803
+                        );
804
+                    }
805
+                }
806
+            }
807
+            $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
808
+            $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
809
+        }
810
+        return $result;
811
+    }
812
+
813
+    /**
814
+     * Copy a file/folder from the source path to target path
815
+     *
816
+     * @param string $path1 source path
817
+     * @param string $path2 target path
818
+     * @param bool $preserveMtime whether to preserve mtime on the copy
819
+     *
820
+     * @return bool|mixed
821
+     */
822
+    public function copy($path1, $path2, $preserveMtime = false) {
823
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
824
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
825
+        $result = false;
826
+        if (
827
+            Filesystem::isValidPath($path2)
828
+            and Filesystem::isValidPath($path1)
829
+            and !Filesystem::isFileBlacklisted($path2)
830
+        ) {
831
+            $path1 = $this->getRelativePath($absolutePath1);
832
+            $path2 = $this->getRelativePath($absolutePath2);
833
+
834
+            if ($path1 == null or $path2 == null) {
835
+                return false;
836
+            }
837
+            $run = true;
838
+
839
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
840
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
841
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
842
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
843
+
844
+            try {
845
+
846
+                $exists = $this->file_exists($path2);
847
+                if ($this->shouldEmitHooks()) {
848
+                    \OC_Hook::emit(
849
+                        Filesystem::CLASSNAME,
850
+                        Filesystem::signal_copy,
851
+                        array(
852
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
853
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
854
+                            Filesystem::signal_param_run => &$run
855
+                        )
856
+                    );
857
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
858
+                }
859
+                if ($run) {
860
+                    $mount1 = $this->getMount($path1);
861
+                    $mount2 = $this->getMount($path2);
862
+                    $storage1 = $mount1->getStorage();
863
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
864
+                    $storage2 = $mount2->getStorage();
865
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
866
+
867
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
868
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
869
+
870
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
871
+                        if ($storage1) {
872
+                            $result = $storage1->copy($internalPath1, $internalPath2);
873
+                        } else {
874
+                            $result = false;
875
+                        }
876
+                    } else {
877
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
878
+                    }
879
+
880
+                    $this->writeUpdate($storage2, $internalPath2);
881
+
882
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
883
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
884
+
885
+                    if ($this->shouldEmitHooks() && $result !== false) {
886
+                        \OC_Hook::emit(
887
+                            Filesystem::CLASSNAME,
888
+                            Filesystem::signal_post_copy,
889
+                            array(
890
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
891
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
892
+                            )
893
+                        );
894
+                        $this->emit_file_hooks_post($exists, $path2);
895
+                    }
896
+
897
+                }
898
+            } catch (\Exception $e) {
899
+                $this->unlockFile($path2, $lockTypePath2);
900
+                $this->unlockFile($path1, $lockTypePath1);
901
+                throw $e;
902
+            }
903
+
904
+            $this->unlockFile($path2, $lockTypePath2);
905
+            $this->unlockFile($path1, $lockTypePath1);
906
+
907
+        }
908
+        return $result;
909
+    }
910
+
911
+    /**
912
+     * @param string $path
913
+     * @param string $mode
914
+     * @return resource
915
+     */
916
+    public function fopen($path, $mode) {
917
+        $hooks = array();
918
+        switch ($mode) {
919
+            case 'r':
920
+            case 'rb':
921
+                $hooks[] = 'read';
922
+                break;
923
+            case 'r+':
924
+            case 'rb+':
925
+            case 'w+':
926
+            case 'wb+':
927
+            case 'x+':
928
+            case 'xb+':
929
+            case 'a+':
930
+            case 'ab+':
931
+                $hooks[] = 'read';
932
+                $hooks[] = 'write';
933
+                break;
934
+            case 'w':
935
+            case 'wb':
936
+            case 'x':
937
+            case 'xb':
938
+            case 'a':
939
+            case 'ab':
940
+                $hooks[] = 'write';
941
+                break;
942
+            default:
943
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
944
+        }
945
+
946
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
947
+    }
948
+
949
+    /**
950
+     * @param string $path
951
+     * @return bool|string
952
+     * @throws \OCP\Files\InvalidPathException
953
+     */
954
+    public function toTmpFile($path) {
955
+        $this->assertPathLength($path);
956
+        if (Filesystem::isValidPath($path)) {
957
+            $source = $this->fopen($path, 'r');
958
+            if ($source) {
959
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
960
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
961
+                file_put_contents($tmpFile, $source);
962
+                return $tmpFile;
963
+            } else {
964
+                return false;
965
+            }
966
+        } else {
967
+            return false;
968
+        }
969
+    }
970
+
971
+    /**
972
+     * @param string $tmpFile
973
+     * @param string $path
974
+     * @return bool|mixed
975
+     * @throws \OCP\Files\InvalidPathException
976
+     */
977
+    public function fromTmpFile($tmpFile, $path) {
978
+        $this->assertPathLength($path);
979
+        if (Filesystem::isValidPath($path)) {
980
+
981
+            // Get directory that the file is going into
982
+            $filePath = dirname($path);
983
+
984
+            // Create the directories if any
985
+            if (!$this->file_exists($filePath)) {
986
+                $this->mkdir($filePath);
987
+            }
988
+
989
+            $source = fopen($tmpFile, 'r');
990
+            if ($source) {
991
+                $result = $this->file_put_contents($path, $source);
992
+                // $this->file_put_contents() might have already closed
993
+                // the resource, so we check it, before trying to close it
994
+                // to avoid messages in the error log.
995
+                if (is_resource($source)) {
996
+                    fclose($source);
997
+                }
998
+                unlink($tmpFile);
999
+                return $result;
1000
+            } else {
1001
+                return false;
1002
+            }
1003
+        } else {
1004
+            return false;
1005
+        }
1006
+    }
1007
+
1008
+
1009
+    /**
1010
+     * @param string $path
1011
+     * @return mixed
1012
+     * @throws \OCP\Files\InvalidPathException
1013
+     */
1014
+    public function getMimeType($path) {
1015
+        $this->assertPathLength($path);
1016
+        return $this->basicOperation('getMimeType', $path);
1017
+    }
1018
+
1019
+    /**
1020
+     * @param string $type
1021
+     * @param string $path
1022
+     * @param bool $raw
1023
+     * @return bool|null|string
1024
+     */
1025
+    public function hash($type, $path, $raw = false) {
1026
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1027
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1028
+        if (Filesystem::isValidPath($path)) {
1029
+            $path = $this->getRelativePath($absolutePath);
1030
+            if ($path == null) {
1031
+                return false;
1032
+            }
1033
+            if ($this->shouldEmitHooks($path)) {
1034
+                \OC_Hook::emit(
1035
+                    Filesystem::CLASSNAME,
1036
+                    Filesystem::signal_read,
1037
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1038
+                );
1039
+            }
1040
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1041
+            if ($storage) {
1042
+                $result = $storage->hash($type, $internalPath, $raw);
1043
+                return $result;
1044
+            }
1045
+        }
1046
+        return null;
1047
+    }
1048
+
1049
+    /**
1050
+     * @param string $path
1051
+     * @return mixed
1052
+     * @throws \OCP\Files\InvalidPathException
1053
+     */
1054
+    public function free_space($path = '/') {
1055
+        $this->assertPathLength($path);
1056
+        return $this->basicOperation('free_space', $path);
1057
+    }
1058
+
1059
+    /**
1060
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1061
+     *
1062
+     * @param string $operation
1063
+     * @param string $path
1064
+     * @param array $hooks (optional)
1065
+     * @param mixed $extraParam (optional)
1066
+     * @return mixed
1067
+     * @throws \Exception
1068
+     *
1069
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1070
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1071
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1072
+     */
1073
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1074
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1075
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1076
+        if (Filesystem::isValidPath($path)
1077
+            and !Filesystem::isFileBlacklisted($path)
1078
+        ) {
1079
+            $path = $this->getRelativePath($absolutePath);
1080
+            if ($path == null) {
1081
+                return false;
1082
+            }
1083
+
1084
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1085
+                // always a shared lock during pre-hooks so the hook can read the file
1086
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1087
+            }
1088
+
1089
+            $run = $this->runHooks($hooks, $path);
1090
+            /** @var \OC\Files\Storage\Storage $storage */
1091
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1092
+            if ($run and $storage) {
1093
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1094
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1095
+                }
1096
+                try {
1097
+                    if (!is_null($extraParam)) {
1098
+                        $result = $storage->$operation($internalPath, $extraParam);
1099
+                    } else {
1100
+                        $result = $storage->$operation($internalPath);
1101
+                    }
1102
+                } catch (\Exception $e) {
1103
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1104
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1105
+                    } else if (in_array('read', $hooks)) {
1106
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1107
+                    }
1108
+                    throw $e;
1109
+                }
1110
+
1111
+                if ($result && in_array('delete', $hooks) and $result) {
1112
+                    $this->removeUpdate($storage, $internalPath);
1113
+                }
1114
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1115
+                    $this->writeUpdate($storage, $internalPath);
1116
+                }
1117
+                if ($result && in_array('touch', $hooks)) {
1118
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1119
+                }
1120
+
1121
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1122
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1123
+                }
1124
+
1125
+                $unlockLater = false;
1126
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1127
+                    $unlockLater = true;
1128
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1129
+                        if (in_array('write', $hooks)) {
1130
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1131
+                        } else if (in_array('read', $hooks)) {
1132
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1133
+                        }
1134
+                    });
1135
+                }
1136
+
1137
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1138
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1139
+                        $this->runHooks($hooks, $path, true);
1140
+                    }
1141
+                }
1142
+
1143
+                if (!$unlockLater
1144
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1145
+                ) {
1146
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1147
+                }
1148
+                return $result;
1149
+            } else {
1150
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1151
+            }
1152
+        }
1153
+        return null;
1154
+    }
1155
+
1156
+    /**
1157
+     * get the path relative to the default root for hook usage
1158
+     *
1159
+     * @param string $path
1160
+     * @return string
1161
+     */
1162
+    private function getHookPath($path) {
1163
+        if (!Filesystem::getView()) {
1164
+            return $path;
1165
+        }
1166
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1167
+    }
1168
+
1169
+    private function shouldEmitHooks($path = '') {
1170
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1171
+            return false;
1172
+        }
1173
+        if (!Filesystem::$loaded) {
1174
+            return false;
1175
+        }
1176
+        $defaultRoot = Filesystem::getRoot();
1177
+        if ($defaultRoot === null) {
1178
+            return false;
1179
+        }
1180
+        if ($this->fakeRoot === $defaultRoot) {
1181
+            return true;
1182
+        }
1183
+        $fullPath = $this->getAbsolutePath($path);
1184
+
1185
+        if ($fullPath === $defaultRoot) {
1186
+            return true;
1187
+        }
1188
+
1189
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1190
+    }
1191
+
1192
+    /**
1193
+     * @param string[] $hooks
1194
+     * @param string $path
1195
+     * @param bool $post
1196
+     * @return bool
1197
+     */
1198
+    private function runHooks($hooks, $path, $post = false) {
1199
+        $relativePath = $path;
1200
+        $path = $this->getHookPath($path);
1201
+        $prefix = ($post) ? 'post_' : '';
1202
+        $run = true;
1203
+        if ($this->shouldEmitHooks($relativePath)) {
1204
+            foreach ($hooks as $hook) {
1205
+                if ($hook != 'read') {
1206
+                    \OC_Hook::emit(
1207
+                        Filesystem::CLASSNAME,
1208
+                        $prefix . $hook,
1209
+                        array(
1210
+                            Filesystem::signal_param_run => &$run,
1211
+                            Filesystem::signal_param_path => $path
1212
+                        )
1213
+                    );
1214
+                } elseif (!$post) {
1215
+                    \OC_Hook::emit(
1216
+                        Filesystem::CLASSNAME,
1217
+                        $prefix . $hook,
1218
+                        array(
1219
+                            Filesystem::signal_param_path => $path
1220
+                        )
1221
+                    );
1222
+                }
1223
+            }
1224
+        }
1225
+        return $run;
1226
+    }
1227
+
1228
+    /**
1229
+     * check if a file or folder has been updated since $time
1230
+     *
1231
+     * @param string $path
1232
+     * @param int $time
1233
+     * @return bool
1234
+     */
1235
+    public function hasUpdated($path, $time) {
1236
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1237
+    }
1238
+
1239
+    /**
1240
+     * @param string $ownerId
1241
+     * @return \OC\User\User
1242
+     */
1243
+    private function getUserObjectForOwner($ownerId) {
1244
+        $owner = $this->userManager->get($ownerId);
1245
+        if ($owner instanceof IUser) {
1246
+            return $owner;
1247
+        } else {
1248
+            return new User($ownerId, null);
1249
+        }
1250
+    }
1251
+
1252
+    /**
1253
+     * Get file info from cache
1254
+     *
1255
+     * If the file is not in cached it will be scanned
1256
+     * If the file has changed on storage the cache will be updated
1257
+     *
1258
+     * @param \OC\Files\Storage\Storage $storage
1259
+     * @param string $internalPath
1260
+     * @param string $relativePath
1261
+     * @return array|bool
1262
+     */
1263
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1264
+        $cache = $storage->getCache($internalPath);
1265
+        $data = $cache->get($internalPath);
1266
+        $watcher = $storage->getWatcher($internalPath);
1267
+
1268
+        try {
1269
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1270
+            if (!$data || $data['size'] === -1) {
1271
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1272
+                if (!$storage->file_exists($internalPath)) {
1273
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1274
+                    return false;
1275
+                }
1276
+                $scanner = $storage->getScanner($internalPath);
1277
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1278
+                $data = $cache->get($internalPath);
1279
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1280
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1281
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1282
+                $watcher->update($internalPath, $data);
1283
+                $storage->getPropagator()->propagateChange($internalPath, time());
1284
+                $data = $cache->get($internalPath);
1285
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1286
+            }
1287
+        } catch (LockedException $e) {
1288
+            // if the file is locked we just use the old cache info
1289
+        }
1290
+
1291
+        return $data;
1292
+    }
1293
+
1294
+    /**
1295
+     * get the filesystem info
1296
+     *
1297
+     * @param string $path
1298
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1299
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1300
+     * defaults to true
1301
+     * @return \OC\Files\FileInfo|false False if file does not exist
1302
+     */
1303
+    public function getFileInfo($path, $includeMountPoints = true) {
1304
+        $this->assertPathLength($path);
1305
+        if (!Filesystem::isValidPath($path)) {
1306
+            return false;
1307
+        }
1308
+        if (Cache\Scanner::isPartialFile($path)) {
1309
+            return $this->getPartFileInfo($path);
1310
+        }
1311
+        $relativePath = $path;
1312
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1313
+
1314
+        $mount = Filesystem::getMountManager()->find($path);
1315
+        $storage = $mount->getStorage();
1316
+        $internalPath = $mount->getInternalPath($path);
1317
+        if ($storage) {
1318
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1319
+
1320
+            if (!$data instanceof ICacheEntry) {
1321
+                return false;
1322
+            }
1323
+
1324
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1325
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1326
+            }
1327
+
1328
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1329
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1330
+
1331
+            if ($data and isset($data['fileid'])) {
1332
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1333
+                    //add the sizes of other mount points to the folder
1334
+                    $extOnly = ($includeMountPoints === 'ext');
1335
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1336
+                    foreach ($mounts as $mount) {
1337
+                        $subStorage = $mount->getStorage();
1338
+                        if ($subStorage) {
1339
+                            // exclude shared storage ?
1340
+                            if ($extOnly && $subStorage instanceof \OC\Files\Storage\Shared) {
1341
+                                continue;
1342
+                            }
1343
+                            $subCache = $subStorage->getCache('');
1344
+                            $rootEntry = $subCache->get('');
1345
+                            $info->addSubEntry($rootEntry, $mount->getMountPoint());
1346
+                        }
1347
+                    }
1348
+                }
1349
+            }
1350
+
1351
+            return $info;
1352
+        }
1353
+
1354
+        return false;
1355
+    }
1356
+
1357
+    /**
1358
+     * get the content of a directory
1359
+     *
1360
+     * @param string $directory path under datadirectory
1361
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1362
+     * @return FileInfo[]
1363
+     */
1364
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1365
+        $this->assertPathLength($directory);
1366
+        if (!Filesystem::isValidPath($directory)) {
1367
+            return [];
1368
+        }
1369
+        $path = $this->getAbsolutePath($directory);
1370
+        $path = Filesystem::normalizePath($path);
1371
+        $mount = $this->getMount($directory);
1372
+        $storage = $mount->getStorage();
1373
+        $internalPath = $mount->getInternalPath($path);
1374
+        if ($storage) {
1375
+            $cache = $storage->getCache($internalPath);
1376
+            $user = \OC_User::getUser();
1377
+
1378
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1379
+
1380
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1381
+                return [];
1382
+            }
1383
+
1384
+            $folderId = $data['fileid'];
1385
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1386
+
1387
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1388
+            /**
1389
+             * @var \OC\Files\FileInfo[] $files
1390
+             */
1391
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1392
+                if ($sharingDisabled) {
1393
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1394
+                }
1395
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1396
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1397
+            }, $contents);
1398
+
1399
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1400
+            $mounts = Filesystem::getMountManager()->findIn($path);
1401
+            $dirLength = strlen($path);
1402
+            foreach ($mounts as $mount) {
1403
+                $mountPoint = $mount->getMountPoint();
1404
+                $subStorage = $mount->getStorage();
1405
+                if ($subStorage) {
1406
+                    $subCache = $subStorage->getCache('');
1407
+
1408
+                    $rootEntry = $subCache->get('');
1409
+                    if (!$rootEntry) {
1410
+                        $subScanner = $subStorage->getScanner('');
1411
+                        try {
1412
+                            $subScanner->scanFile('');
1413
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1414
+                            continue;
1415
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1416
+                            continue;
1417
+                        } catch (\Exception $e) {
1418
+                            // sometimes when the storage is not available it can be any exception
1419
+                            \OCP\Util::writeLog(
1420
+                                'core',
1421
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1422
+                                get_class($e) . ': ' . $e->getMessage(),
1423
+                                \OCP\Util::ERROR
1424
+                            );
1425
+                            continue;
1426
+                        }
1427
+                        $rootEntry = $subCache->get('');
1428
+                    }
1429
+
1430
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1431
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1432
+                        if ($pos = strpos($relativePath, '/')) {
1433
+                            //mountpoint inside subfolder add size to the correct folder
1434
+                            $entryName = substr($relativePath, 0, $pos);
1435
+                            foreach ($files as &$entry) {
1436
+                                if ($entry->getName() === $entryName) {
1437
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1438
+                                }
1439
+                            }
1440
+                        } else { //mountpoint in this folder, add an entry for it
1441
+                            $rootEntry['name'] = $relativePath;
1442
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1443
+                            $permissions = $rootEntry['permissions'];
1444
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1445
+                            // for shared files/folders we use the permissions given by the owner
1446
+                            if ($mount instanceof MoveableMount) {
1447
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1448
+                            } else {
1449
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1450
+                            }
1451
+
1452
+                            //remove any existing entry with the same name
1453
+                            foreach ($files as $i => $file) {
1454
+                                if ($file['name'] === $rootEntry['name']) {
1455
+                                    unset($files[$i]);
1456
+                                    break;
1457
+                                }
1458
+                            }
1459
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1460
+
1461
+                            // if sharing was disabled for the user we remove the share permissions
1462
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1463
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1464
+                            }
1465
+
1466
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1467
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1468
+                        }
1469
+                    }
1470
+                }
1471
+            }
1472
+
1473
+            if ($mimetype_filter) {
1474
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1475
+                    if (strpos($mimetype_filter, '/')) {
1476
+                        return $file->getMimetype() === $mimetype_filter;
1477
+                    } else {
1478
+                        return $file->getMimePart() === $mimetype_filter;
1479
+                    }
1480
+                });
1481
+            }
1482
+
1483
+            return $files;
1484
+        } else {
1485
+            return [];
1486
+        }
1487
+    }
1488
+
1489
+    /**
1490
+     * change file metadata
1491
+     *
1492
+     * @param string $path
1493
+     * @param array|\OCP\Files\FileInfo $data
1494
+     * @return int
1495
+     *
1496
+     * returns the fileid of the updated file
1497
+     */
1498
+    public function putFileInfo($path, $data) {
1499
+        $this->assertPathLength($path);
1500
+        if ($data instanceof FileInfo) {
1501
+            $data = $data->getData();
1502
+        }
1503
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1504
+        /**
1505
+         * @var \OC\Files\Storage\Storage $storage
1506
+         * @var string $internalPath
1507
+         */
1508
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1509
+        if ($storage) {
1510
+            $cache = $storage->getCache($path);
1511
+
1512
+            if (!$cache->inCache($internalPath)) {
1513
+                $scanner = $storage->getScanner($internalPath);
1514
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1515
+            }
1516
+
1517
+            return $cache->put($internalPath, $data);
1518
+        } else {
1519
+            return -1;
1520
+        }
1521
+    }
1522
+
1523
+    /**
1524
+     * search for files with the name matching $query
1525
+     *
1526
+     * @param string $query
1527
+     * @return FileInfo[]
1528
+     */
1529
+    public function search($query) {
1530
+        return $this->searchCommon('search', array('%' . $query . '%'));
1531
+    }
1532
+
1533
+    /**
1534
+     * search for files with the name matching $query
1535
+     *
1536
+     * @param string $query
1537
+     * @return FileInfo[]
1538
+     */
1539
+    public function searchRaw($query) {
1540
+        return $this->searchCommon('search', array($query));
1541
+    }
1542
+
1543
+    /**
1544
+     * search for files by mimetype
1545
+     *
1546
+     * @param string $mimetype
1547
+     * @return FileInfo[]
1548
+     */
1549
+    public function searchByMime($mimetype) {
1550
+        return $this->searchCommon('searchByMime', array($mimetype));
1551
+    }
1552
+
1553
+    /**
1554
+     * search for files by tag
1555
+     *
1556
+     * @param string|int $tag name or tag id
1557
+     * @param string $userId owner of the tags
1558
+     * @return FileInfo[]
1559
+     */
1560
+    public function searchByTag($tag, $userId) {
1561
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1562
+    }
1563
+
1564
+    /**
1565
+     * @param string $method cache method
1566
+     * @param array $args
1567
+     * @return FileInfo[]
1568
+     */
1569
+    private function searchCommon($method, $args) {
1570
+        $files = array();
1571
+        $rootLength = strlen($this->fakeRoot);
1572
+
1573
+        $mount = $this->getMount('');
1574
+        $mountPoint = $mount->getMountPoint();
1575
+        $storage = $mount->getStorage();
1576
+        if ($storage) {
1577
+            $cache = $storage->getCache('');
1578
+
1579
+            $results = call_user_func_array(array($cache, $method), $args);
1580
+            foreach ($results as $result) {
1581
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1582
+                    $internalPath = $result['path'];
1583
+                    $path = $mountPoint . $result['path'];
1584
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1585
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1586
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1587
+                }
1588
+            }
1589
+
1590
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1591
+            foreach ($mounts as $mount) {
1592
+                $mountPoint = $mount->getMountPoint();
1593
+                $storage = $mount->getStorage();
1594
+                if ($storage) {
1595
+                    $cache = $storage->getCache('');
1596
+
1597
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1598
+                    $results = call_user_func_array(array($cache, $method), $args);
1599
+                    if ($results) {
1600
+                        foreach ($results as $result) {
1601
+                            $internalPath = $result['path'];
1602
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1603
+                            $path = rtrim($mountPoint . $internalPath, '/');
1604
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1605
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1606
+                        }
1607
+                    }
1608
+                }
1609
+            }
1610
+        }
1611
+        return $files;
1612
+    }
1613
+
1614
+    /**
1615
+     * Get the owner for a file or folder
1616
+     *
1617
+     * @param string $path
1618
+     * @return string the user id of the owner
1619
+     * @throws NotFoundException
1620
+     */
1621
+    public function getOwner($path) {
1622
+        $info = $this->getFileInfo($path);
1623
+        if (!$info) {
1624
+            throw new NotFoundException($path . ' not found while trying to get owner');
1625
+        }
1626
+        return $info->getOwner()->getUID();
1627
+    }
1628
+
1629
+    /**
1630
+     * get the ETag for a file or folder
1631
+     *
1632
+     * @param string $path
1633
+     * @return string
1634
+     */
1635
+    public function getETag($path) {
1636
+        /**
1637
+         * @var Storage\Storage $storage
1638
+         * @var string $internalPath
1639
+         */
1640
+        list($storage, $internalPath) = $this->resolvePath($path);
1641
+        if ($storage) {
1642
+            return $storage->getETag($internalPath);
1643
+        } else {
1644
+            return null;
1645
+        }
1646
+    }
1647
+
1648
+    /**
1649
+     * Get the path of a file by id, relative to the view
1650
+     *
1651
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1652
+     *
1653
+     * @param int $id
1654
+     * @throws NotFoundException
1655
+     * @return string
1656
+     */
1657
+    public function getPath($id) {
1658
+        $id = (int)$id;
1659
+        $manager = Filesystem::getMountManager();
1660
+        $mounts = $manager->findIn($this->fakeRoot);
1661
+        $mounts[] = $manager->find($this->fakeRoot);
1662
+        // reverse the array so we start with the storage this view is in
1663
+        // which is the most likely to contain the file we're looking for
1664
+        $mounts = array_reverse($mounts);
1665
+        foreach ($mounts as $mount) {
1666
+            /**
1667
+             * @var \OC\Files\Mount\MountPoint $mount
1668
+             */
1669
+            if ($mount->getStorage()) {
1670
+                $cache = $mount->getStorage()->getCache();
1671
+                $internalPath = $cache->getPathById($id);
1672
+                if (is_string($internalPath)) {
1673
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1674
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1675
+                        return $path;
1676
+                    }
1677
+                }
1678
+            }
1679
+        }
1680
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1681
+    }
1682
+
1683
+    /**
1684
+     * @param string $path
1685
+     * @throws InvalidPathException
1686
+     */
1687
+    private function assertPathLength($path) {
1688
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1689
+        // Check for the string length - performed using isset() instead of strlen()
1690
+        // because isset() is about 5x-40x faster.
1691
+        if (isset($path[$maxLen])) {
1692
+            $pathLen = strlen($path);
1693
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1694
+        }
1695
+    }
1696
+
1697
+    /**
1698
+     * check if it is allowed to move a mount point to a given target.
1699
+     * It is not allowed to move a mount point into a different mount point or
1700
+     * into an already shared folder
1701
+     *
1702
+     * @param string $target path
1703
+     * @return boolean
1704
+     */
1705
+    private function isTargetAllowed($target) {
1706
+
1707
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1708
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1709
+            \OCP\Util::writeLog('files',
1710
+                'It is not allowed to move one mount point into another one',
1711
+                \OCP\Util::DEBUG);
1712
+            return false;
1713
+        }
1714
+
1715
+        // note: cannot use the view because the target is already locked
1716
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1717
+        if ($fileId === -1) {
1718
+            // target might not exist, need to check parent instead
1719
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1720
+        }
1721
+
1722
+        // check if any of the parents were shared by the current owner (include collections)
1723
+        $shares = \OCP\Share::getItemShared(
1724
+            'folder',
1725
+            $fileId,
1726
+            \OCP\Share::FORMAT_NONE,
1727
+            null,
1728
+            true
1729
+        );
1730
+
1731
+        if (count($shares) > 0) {
1732
+            \OCP\Util::writeLog('files',
1733
+                'It is not allowed to move one mount point into a shared folder',
1734
+                \OCP\Util::DEBUG);
1735
+            return false;
1736
+        }
1737
+
1738
+        return true;
1739
+    }
1740
+
1741
+    /**
1742
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1743
+     *
1744
+     * @param string $path
1745
+     * @return \OCP\Files\FileInfo
1746
+     */
1747
+    private function getPartFileInfo($path) {
1748
+        $mount = $this->getMount($path);
1749
+        $storage = $mount->getStorage();
1750
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1751
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1752
+        return new FileInfo(
1753
+            $this->getAbsolutePath($path),
1754
+            $storage,
1755
+            $internalPath,
1756
+            [
1757
+                'fileid' => null,
1758
+                'mimetype' => $storage->getMimeType($internalPath),
1759
+                'name' => basename($path),
1760
+                'etag' => null,
1761
+                'size' => $storage->filesize($internalPath),
1762
+                'mtime' => $storage->filemtime($internalPath),
1763
+                'encrypted' => false,
1764
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1765
+            ],
1766
+            $mount,
1767
+            $owner
1768
+        );
1769
+    }
1770
+
1771
+    /**
1772
+     * @param string $path
1773
+     * @param string $fileName
1774
+     * @throws InvalidPathException
1775
+     */
1776
+    public function verifyPath($path, $fileName) {
1777
+
1778
+        $l10n = \OC::$server->getL10N('lib');
1779
+
1780
+        // verify empty and dot files
1781
+        $trimmed = trim($fileName);
1782
+        if ($trimmed === '') {
1783
+            throw new InvalidPathException($l10n->t('Empty filename is not allowed'));
1784
+        }
1785
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1786
+            throw new InvalidPathException($l10n->t('Dot files are not allowed'));
1787
+        }
1788
+
1789
+        // verify database - e.g. mysql only 3-byte chars
1790
+        if (preg_match('%(?:
1791 1791
       \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
1792 1792
     | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
1793 1793
     | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
1794 1794
 )%xs', $fileName)) {
1795
-			throw new InvalidPathException($l10n->t('4-byte characters are not supported in file names'));
1796
-		}
1797
-
1798
-		try {
1799
-			/** @type \OCP\Files\Storage $storage */
1800
-			list($storage, $internalPath) = $this->resolvePath($path);
1801
-			$storage->verifyPath($internalPath, $fileName);
1802
-		} catch (ReservedWordException $ex) {
1803
-			throw new InvalidPathException($l10n->t('File name is a reserved word'));
1804
-		} catch (InvalidCharacterInPathException $ex) {
1805
-			throw new InvalidPathException($l10n->t('File name contains at least one invalid character'));
1806
-		} catch (FileNameTooLongException $ex) {
1807
-			throw new InvalidPathException($l10n->t('File name is too long'));
1808
-		}
1809
-	}
1810
-
1811
-	/**
1812
-	 * get all parent folders of $path
1813
-	 *
1814
-	 * @param string $path
1815
-	 * @return string[]
1816
-	 */
1817
-	private function getParents($path) {
1818
-		$path = trim($path, '/');
1819
-		if (!$path) {
1820
-			return [];
1821
-		}
1822
-
1823
-		$parts = explode('/', $path);
1824
-
1825
-		// remove the single file
1826
-		array_pop($parts);
1827
-		$result = array('/');
1828
-		$resultPath = '';
1829
-		foreach ($parts as $part) {
1830
-			if ($part) {
1831
-				$resultPath .= '/' . $part;
1832
-				$result[] = $resultPath;
1833
-			}
1834
-		}
1835
-		return $result;
1836
-	}
1837
-
1838
-	/**
1839
-	 * Returns the mount point for which to lock
1840
-	 *
1841
-	 * @param string $absolutePath absolute path
1842
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1843
-	 * is mounted directly on the given path, false otherwise
1844
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1845
-	 */
1846
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1847
-		$results = [];
1848
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1849
-		if (!$mount) {
1850
-			return $results;
1851
-		}
1852
-
1853
-		if ($useParentMount) {
1854
-			// find out if something is mounted directly on the path
1855
-			$internalPath = $mount->getInternalPath($absolutePath);
1856
-			if ($internalPath === '') {
1857
-				// resolve the parent mount instead
1858
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1859
-			}
1860
-		}
1861
-
1862
-		return $mount;
1863
-	}
1864
-
1865
-	/**
1866
-	 * Lock the given path
1867
-	 *
1868
-	 * @param string $path the path of the file to lock, relative to the view
1869
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1870
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1871
-	 *
1872
-	 * @return bool False if the path is excluded from locking, true otherwise
1873
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1874
-	 */
1875
-	private function lockPath($path, $type, $lockMountPoint = false) {
1876
-		$absolutePath = $this->getAbsolutePath($path);
1877
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1878
-		if (!$this->shouldLockFile($absolutePath)) {
1879
-			return false;
1880
-		}
1881
-
1882
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1883
-		if ($mount) {
1884
-			try {
1885
-				$storage = $mount->getStorage();
1886
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1887
-					$storage->acquireLock(
1888
-						$mount->getInternalPath($absolutePath),
1889
-						$type,
1890
-						$this->lockingProvider
1891
-					);
1892
-				}
1893
-			} catch (\OCP\Lock\LockedException $e) {
1894
-				// rethrow with the a human-readable path
1895
-				throw new \OCP\Lock\LockedException(
1896
-					$this->getPathRelativeToFiles($absolutePath),
1897
-					$e
1898
-				);
1899
-			}
1900
-		}
1901
-
1902
-		return true;
1903
-	}
1904
-
1905
-	/**
1906
-	 * Change the lock type
1907
-	 *
1908
-	 * @param string $path the path of the file to lock, relative to the view
1909
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1910
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1911
-	 *
1912
-	 * @return bool False if the path is excluded from locking, true otherwise
1913
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1914
-	 */
1915
-	public function changeLock($path, $type, $lockMountPoint = false) {
1916
-		$path = Filesystem::normalizePath($path);
1917
-		$absolutePath = $this->getAbsolutePath($path);
1918
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1919
-		if (!$this->shouldLockFile($absolutePath)) {
1920
-			return false;
1921
-		}
1922
-
1923
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1924
-		if ($mount) {
1925
-			try {
1926
-				$storage = $mount->getStorage();
1927
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1928
-					$storage->changeLock(
1929
-						$mount->getInternalPath($absolutePath),
1930
-						$type,
1931
-						$this->lockingProvider
1932
-					);
1933
-				}
1934
-			} catch (\OCP\Lock\LockedException $e) {
1935
-				// rethrow with the a human-readable path
1936
-				throw new \OCP\Lock\LockedException(
1937
-					$this->getPathRelativeToFiles($absolutePath),
1938
-					$e
1939
-				);
1940
-			}
1941
-		}
1942
-
1943
-		return true;
1944
-	}
1945
-
1946
-	/**
1947
-	 * Unlock the given path
1948
-	 *
1949
-	 * @param string $path the path of the file to unlock, relative to the view
1950
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1951
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1952
-	 *
1953
-	 * @return bool False if the path is excluded from locking, true otherwise
1954
-	 */
1955
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1956
-		$absolutePath = $this->getAbsolutePath($path);
1957
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1958
-		if (!$this->shouldLockFile($absolutePath)) {
1959
-			return false;
1960
-		}
1961
-
1962
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1963
-		if ($mount) {
1964
-			$storage = $mount->getStorage();
1965
-			if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1966
-				$storage->releaseLock(
1967
-					$mount->getInternalPath($absolutePath),
1968
-					$type,
1969
-					$this->lockingProvider
1970
-				);
1971
-			}
1972
-		}
1973
-
1974
-		return true;
1975
-	}
1976
-
1977
-	/**
1978
-	 * Lock a path and all its parents up to the root of the view
1979
-	 *
1980
-	 * @param string $path the path of the file to lock relative to the view
1981
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1982
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1983
-	 *
1984
-	 * @return bool False if the path is excluded from locking, true otherwise
1985
-	 */
1986
-	public function lockFile($path, $type, $lockMountPoint = false) {
1987
-		$absolutePath = $this->getAbsolutePath($path);
1988
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1989
-		if (!$this->shouldLockFile($absolutePath)) {
1990
-			return false;
1991
-		}
1992
-
1993
-		$this->lockPath($path, $type, $lockMountPoint);
1994
-
1995
-		$parents = $this->getParents($path);
1996
-		foreach ($parents as $parent) {
1997
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
1998
-		}
1999
-
2000
-		return true;
2001
-	}
2002
-
2003
-	/**
2004
-	 * Unlock a path and all its parents up to the root of the view
2005
-	 *
2006
-	 * @param string $path the path of the file to lock relative to the view
2007
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2008
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2009
-	 *
2010
-	 * @return bool False if the path is excluded from locking, true otherwise
2011
-	 */
2012
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2013
-		$absolutePath = $this->getAbsolutePath($path);
2014
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2015
-		if (!$this->shouldLockFile($absolutePath)) {
2016
-			return false;
2017
-		}
2018
-
2019
-		$this->unlockPath($path, $type, $lockMountPoint);
2020
-
2021
-		$parents = $this->getParents($path);
2022
-		foreach ($parents as $parent) {
2023
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2024
-		}
2025
-
2026
-		return true;
2027
-	}
2028
-
2029
-	/**
2030
-	 * Only lock files in data/user/files/
2031
-	 *
2032
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2033
-	 * @return bool
2034
-	 */
2035
-	protected function shouldLockFile($path) {
2036
-		$path = Filesystem::normalizePath($path);
2037
-
2038
-		$pathSegments = explode('/', $path);
2039
-		if (isset($pathSegments[2])) {
2040
-			// E.g.: /username/files/path-to-file
2041
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2042
-		}
2043
-
2044
-		return true;
2045
-	}
2046
-
2047
-	/**
2048
-	 * Shortens the given absolute path to be relative to
2049
-	 * "$user/files".
2050
-	 *
2051
-	 * @param string $absolutePath absolute path which is under "files"
2052
-	 *
2053
-	 * @return string path relative to "files" with trimmed slashes or null
2054
-	 * if the path was NOT relative to files
2055
-	 *
2056
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2057
-	 * @since 8.1.0
2058
-	 */
2059
-	public function getPathRelativeToFiles($absolutePath) {
2060
-		$path = Filesystem::normalizePath($absolutePath);
2061
-		$parts = explode('/', trim($path, '/'), 3);
2062
-		// "$user", "files", "path/to/dir"
2063
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2064
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2065
-		}
2066
-		if (isset($parts[2])) {
2067
-			return $parts[2];
2068
-		}
2069
-		return '';
2070
-	}
2071
-
2072
-	/**
2073
-	 * @param string $filename
2074
-	 * @return array
2075
-	 * @throws \OC\User\NoUserException
2076
-	 * @throws NotFoundException
2077
-	 */
2078
-	public function getUidAndFilename($filename) {
2079
-		$info = $this->getFileInfo($filename);
2080
-		if (!$info instanceof \OCP\Files\FileInfo) {
2081
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2082
-		}
2083
-		$uid = $info->getOwner()->getUID();
2084
-		if ($uid != \OCP\User::getUser()) {
2085
-			Filesystem::initMountPoints($uid);
2086
-			$ownerView = new View('/' . $uid . '/files');
2087
-			try {
2088
-				$filename = $ownerView->getPath($info['fileid']);
2089
-			} catch (NotFoundException $e) {
2090
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2091
-			}
2092
-		}
2093
-		return [$uid, $filename];
2094
-	}
1795
+            throw new InvalidPathException($l10n->t('4-byte characters are not supported in file names'));
1796
+        }
1797
+
1798
+        try {
1799
+            /** @type \OCP\Files\Storage $storage */
1800
+            list($storage, $internalPath) = $this->resolvePath($path);
1801
+            $storage->verifyPath($internalPath, $fileName);
1802
+        } catch (ReservedWordException $ex) {
1803
+            throw new InvalidPathException($l10n->t('File name is a reserved word'));
1804
+        } catch (InvalidCharacterInPathException $ex) {
1805
+            throw new InvalidPathException($l10n->t('File name contains at least one invalid character'));
1806
+        } catch (FileNameTooLongException $ex) {
1807
+            throw new InvalidPathException($l10n->t('File name is too long'));
1808
+        }
1809
+    }
1810
+
1811
+    /**
1812
+     * get all parent folders of $path
1813
+     *
1814
+     * @param string $path
1815
+     * @return string[]
1816
+     */
1817
+    private function getParents($path) {
1818
+        $path = trim($path, '/');
1819
+        if (!$path) {
1820
+            return [];
1821
+        }
1822
+
1823
+        $parts = explode('/', $path);
1824
+
1825
+        // remove the single file
1826
+        array_pop($parts);
1827
+        $result = array('/');
1828
+        $resultPath = '';
1829
+        foreach ($parts as $part) {
1830
+            if ($part) {
1831
+                $resultPath .= '/' . $part;
1832
+                $result[] = $resultPath;
1833
+            }
1834
+        }
1835
+        return $result;
1836
+    }
1837
+
1838
+    /**
1839
+     * Returns the mount point for which to lock
1840
+     *
1841
+     * @param string $absolutePath absolute path
1842
+     * @param bool $useParentMount true to return parent mount instead of whatever
1843
+     * is mounted directly on the given path, false otherwise
1844
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1845
+     */
1846
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1847
+        $results = [];
1848
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1849
+        if (!$mount) {
1850
+            return $results;
1851
+        }
1852
+
1853
+        if ($useParentMount) {
1854
+            // find out if something is mounted directly on the path
1855
+            $internalPath = $mount->getInternalPath($absolutePath);
1856
+            if ($internalPath === '') {
1857
+                // resolve the parent mount instead
1858
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1859
+            }
1860
+        }
1861
+
1862
+        return $mount;
1863
+    }
1864
+
1865
+    /**
1866
+     * Lock the given path
1867
+     *
1868
+     * @param string $path the path of the file to lock, relative to the view
1869
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1870
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1871
+     *
1872
+     * @return bool False if the path is excluded from locking, true otherwise
1873
+     * @throws \OCP\Lock\LockedException if the path is already locked
1874
+     */
1875
+    private function lockPath($path, $type, $lockMountPoint = false) {
1876
+        $absolutePath = $this->getAbsolutePath($path);
1877
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1878
+        if (!$this->shouldLockFile($absolutePath)) {
1879
+            return false;
1880
+        }
1881
+
1882
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1883
+        if ($mount) {
1884
+            try {
1885
+                $storage = $mount->getStorage();
1886
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1887
+                    $storage->acquireLock(
1888
+                        $mount->getInternalPath($absolutePath),
1889
+                        $type,
1890
+                        $this->lockingProvider
1891
+                    );
1892
+                }
1893
+            } catch (\OCP\Lock\LockedException $e) {
1894
+                // rethrow with the a human-readable path
1895
+                throw new \OCP\Lock\LockedException(
1896
+                    $this->getPathRelativeToFiles($absolutePath),
1897
+                    $e
1898
+                );
1899
+            }
1900
+        }
1901
+
1902
+        return true;
1903
+    }
1904
+
1905
+    /**
1906
+     * Change the lock type
1907
+     *
1908
+     * @param string $path the path of the file to lock, relative to the view
1909
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1910
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1911
+     *
1912
+     * @return bool False if the path is excluded from locking, true otherwise
1913
+     * @throws \OCP\Lock\LockedException if the path is already locked
1914
+     */
1915
+    public function changeLock($path, $type, $lockMountPoint = false) {
1916
+        $path = Filesystem::normalizePath($path);
1917
+        $absolutePath = $this->getAbsolutePath($path);
1918
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1919
+        if (!$this->shouldLockFile($absolutePath)) {
1920
+            return false;
1921
+        }
1922
+
1923
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1924
+        if ($mount) {
1925
+            try {
1926
+                $storage = $mount->getStorage();
1927
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1928
+                    $storage->changeLock(
1929
+                        $mount->getInternalPath($absolutePath),
1930
+                        $type,
1931
+                        $this->lockingProvider
1932
+                    );
1933
+                }
1934
+            } catch (\OCP\Lock\LockedException $e) {
1935
+                // rethrow with the a human-readable path
1936
+                throw new \OCP\Lock\LockedException(
1937
+                    $this->getPathRelativeToFiles($absolutePath),
1938
+                    $e
1939
+                );
1940
+            }
1941
+        }
1942
+
1943
+        return true;
1944
+    }
1945
+
1946
+    /**
1947
+     * Unlock the given path
1948
+     *
1949
+     * @param string $path the path of the file to unlock, relative to the view
1950
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1951
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1952
+     *
1953
+     * @return bool False if the path is excluded from locking, true otherwise
1954
+     */
1955
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1956
+        $absolutePath = $this->getAbsolutePath($path);
1957
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1958
+        if (!$this->shouldLockFile($absolutePath)) {
1959
+            return false;
1960
+        }
1961
+
1962
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1963
+        if ($mount) {
1964
+            $storage = $mount->getStorage();
1965
+            if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1966
+                $storage->releaseLock(
1967
+                    $mount->getInternalPath($absolutePath),
1968
+                    $type,
1969
+                    $this->lockingProvider
1970
+                );
1971
+            }
1972
+        }
1973
+
1974
+        return true;
1975
+    }
1976
+
1977
+    /**
1978
+     * Lock a path and all its parents up to the root of the view
1979
+     *
1980
+     * @param string $path the path of the file to lock relative to the view
1981
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1982
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1983
+     *
1984
+     * @return bool False if the path is excluded from locking, true otherwise
1985
+     */
1986
+    public function lockFile($path, $type, $lockMountPoint = false) {
1987
+        $absolutePath = $this->getAbsolutePath($path);
1988
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1989
+        if (!$this->shouldLockFile($absolutePath)) {
1990
+            return false;
1991
+        }
1992
+
1993
+        $this->lockPath($path, $type, $lockMountPoint);
1994
+
1995
+        $parents = $this->getParents($path);
1996
+        foreach ($parents as $parent) {
1997
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
1998
+        }
1999
+
2000
+        return true;
2001
+    }
2002
+
2003
+    /**
2004
+     * Unlock a path and all its parents up to the root of the view
2005
+     *
2006
+     * @param string $path the path of the file to lock relative to the view
2007
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2008
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2009
+     *
2010
+     * @return bool False if the path is excluded from locking, true otherwise
2011
+     */
2012
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2013
+        $absolutePath = $this->getAbsolutePath($path);
2014
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2015
+        if (!$this->shouldLockFile($absolutePath)) {
2016
+            return false;
2017
+        }
2018
+
2019
+        $this->unlockPath($path, $type, $lockMountPoint);
2020
+
2021
+        $parents = $this->getParents($path);
2022
+        foreach ($parents as $parent) {
2023
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2024
+        }
2025
+
2026
+        return true;
2027
+    }
2028
+
2029
+    /**
2030
+     * Only lock files in data/user/files/
2031
+     *
2032
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2033
+     * @return bool
2034
+     */
2035
+    protected function shouldLockFile($path) {
2036
+        $path = Filesystem::normalizePath($path);
2037
+
2038
+        $pathSegments = explode('/', $path);
2039
+        if (isset($pathSegments[2])) {
2040
+            // E.g.: /username/files/path-to-file
2041
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2042
+        }
2043
+
2044
+        return true;
2045
+    }
2046
+
2047
+    /**
2048
+     * Shortens the given absolute path to be relative to
2049
+     * "$user/files".
2050
+     *
2051
+     * @param string $absolutePath absolute path which is under "files"
2052
+     *
2053
+     * @return string path relative to "files" with trimmed slashes or null
2054
+     * if the path was NOT relative to files
2055
+     *
2056
+     * @throws \InvalidArgumentException if the given path was not under "files"
2057
+     * @since 8.1.0
2058
+     */
2059
+    public function getPathRelativeToFiles($absolutePath) {
2060
+        $path = Filesystem::normalizePath($absolutePath);
2061
+        $parts = explode('/', trim($path, '/'), 3);
2062
+        // "$user", "files", "path/to/dir"
2063
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2064
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2065
+        }
2066
+        if (isset($parts[2])) {
2067
+            return $parts[2];
2068
+        }
2069
+        return '';
2070
+    }
2071
+
2072
+    /**
2073
+     * @param string $filename
2074
+     * @return array
2075
+     * @throws \OC\User\NoUserException
2076
+     * @throws NotFoundException
2077
+     */
2078
+    public function getUidAndFilename($filename) {
2079
+        $info = $this->getFileInfo($filename);
2080
+        if (!$info instanceof \OCP\Files\FileInfo) {
2081
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2082
+        }
2083
+        $uid = $info->getOwner()->getUID();
2084
+        if ($uid != \OCP\User::getUser()) {
2085
+            Filesystem::initMountPoints($uid);
2086
+            $ownerView = new View('/' . $uid . '/files');
2087
+            try {
2088
+                $filename = $ownerView->getPath($info['fileid']);
2089
+            } catch (NotFoundException $e) {
2090
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2091
+            }
2092
+        }
2093
+        return [$uid, $filename];
2094
+    }
2095 2095
 }
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -120,9 +120,9 @@  discard block
 block discarded – undo
120 120
 			$path = '/';
121 121
 		}
122 122
 		if ($path[0] !== '/') {
123
-			$path = '/' . $path;
123
+			$path = '/'.$path;
124 124
 		}
125
-		return $this->fakeRoot . $path;
125
+		return $this->fakeRoot.$path;
126 126
 	}
127 127
 
128 128
 	/**
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 	public function chroot($fakeRoot) {
135 135
 		if (!$fakeRoot == '') {
136 136
 			if ($fakeRoot[0] !== '/') {
137
-				$fakeRoot = '/' . $fakeRoot;
137
+				$fakeRoot = '/'.$fakeRoot;
138 138
 			}
139 139
 		}
140 140
 		$this->fakeRoot = $fakeRoot;
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 		}
167 167
 
168 168
 		// missing slashes can cause wrong matches!
169
-		$root = rtrim($this->fakeRoot, '/') . '/';
169
+		$root = rtrim($this->fakeRoot, '/').'/';
170 170
 
171 171
 		if (strpos($path, $root) !== 0) {
172 172
 			return null;
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 		if ($mount instanceof MoveableMount) {
273 273
 			// cut of /user/files to get the relative path to data/user/files
274 274
 			$pathParts = explode('/', $path, 4);
275
-			$relPath = '/' . $pathParts[3];
275
+			$relPath = '/'.$pathParts[3];
276 276
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
277 277
 			\OC_Hook::emit(
278 278
 				Filesystem::CLASSNAME, "umount",
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
 			    $chunkSize = 8192; // 8 kB chunks
445 445
 			    $end = $to + 1;
446 446
 			    while (!feof($handle) && ftell($handle) < $end) {
447
-				$len = $end-ftell($handle);
447
+				$len = $end - ftell($handle);
448 448
 				if ($len > $chunkSize) { 
449 449
 				    $len = $chunkSize; 
450 450
 				}
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 		}
676 676
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
677 677
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
678
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
678
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
679 679
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
680 680
 			return $this->removeMount($mount, $absolutePath);
681 681
 		}
@@ -940,7 +940,7 @@  discard block
 block discarded – undo
940 940
 				$hooks[] = 'write';
941 941
 				break;
942 942
 			default:
943
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
943
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
944 944
 		}
945 945
 
946 946
 		return $this->basicOperation('fopen', $path, $hooks, $mode);
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1038 1038
 				);
1039 1039
 			}
1040
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1040
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1041 1041
 			if ($storage) {
1042 1042
 				$result = $storage->hash($type, $internalPath, $raw);
1043 1043
 				return $result;
@@ -1088,7 +1088,7 @@  discard block
 block discarded – undo
1088 1088
 
1089 1089
 			$run = $this->runHooks($hooks, $path);
1090 1090
 			/** @var \OC\Files\Storage\Storage $storage */
1091
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1091
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1092 1092
 			if ($run and $storage) {
1093 1093
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1094 1094
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1125,7 +1125,7 @@  discard block
 block discarded – undo
1125 1125
 				$unlockLater = false;
1126 1126
 				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1127 1127
 					$unlockLater = true;
1128
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1128
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1129 1129
 						if (in_array('write', $hooks)) {
1130 1130
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1131 1131
 						} else if (in_array('read', $hooks)) {
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
 			return true;
1187 1187
 		}
1188 1188
 
1189
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1189
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1190 1190
 	}
1191 1191
 
1192 1192
 	/**
@@ -1205,7 +1205,7 @@  discard block
 block discarded – undo
1205 1205
 				if ($hook != 'read') {
1206 1206
 					\OC_Hook::emit(
1207 1207
 						Filesystem::CLASSNAME,
1208
-						$prefix . $hook,
1208
+						$prefix.$hook,
1209 1209
 						array(
1210 1210
 							Filesystem::signal_param_run => &$run,
1211 1211
 							Filesystem::signal_param_path => $path
@@ -1214,7 +1214,7 @@  discard block
 block discarded – undo
1214 1214
 				} elseif (!$post) {
1215 1215
 					\OC_Hook::emit(
1216 1216
 						Filesystem::CLASSNAME,
1217
-						$prefix . $hook,
1217
+						$prefix.$hook,
1218 1218
 						array(
1219 1219
 							Filesystem::signal_param_path => $path
1220 1220
 						)
@@ -1309,7 +1309,7 @@  discard block
 block discarded – undo
1309 1309
 			return $this->getPartFileInfo($path);
1310 1310
 		}
1311 1311
 		$relativePath = $path;
1312
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1312
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1313 1313
 
1314 1314
 		$mount = Filesystem::getMountManager()->find($path);
1315 1315
 		$storage = $mount->getStorage();
@@ -1388,12 +1388,12 @@  discard block
 block discarded – undo
1388 1388
 			/**
1389 1389
 			 * @var \OC\Files\FileInfo[] $files
1390 1390
 			 */
1391
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1391
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1392 1392
 				if ($sharingDisabled) {
1393 1393
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1394 1394
 				}
1395 1395
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1396
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1396
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1397 1397
 			}, $contents);
1398 1398
 
1399 1399
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1418,8 +1418,8 @@  discard block
 block discarded – undo
1418 1418
 							// sometimes when the storage is not available it can be any exception
1419 1419
 							\OCP\Util::writeLog(
1420 1420
 								'core',
1421
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1422
-								get_class($e) . ': ' . $e->getMessage(),
1421
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1422
+								get_class($e).': '.$e->getMessage(),
1423 1423
 								\OCP\Util::ERROR
1424 1424
 							);
1425 1425
 							continue;
@@ -1456,7 +1456,7 @@  discard block
 block discarded – undo
1456 1456
 									break;
1457 1457
 								}
1458 1458
 							}
1459
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1459
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1460 1460
 
1461 1461
 							// if sharing was disabled for the user we remove the share permissions
1462 1462
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1464,14 +1464,14 @@  discard block
 block discarded – undo
1464 1464
 							}
1465 1465
 
1466 1466
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1467
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1467
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1468 1468
 						}
1469 1469
 					}
1470 1470
 				}
1471 1471
 			}
1472 1472
 
1473 1473
 			if ($mimetype_filter) {
1474
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1474
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1475 1475
 					if (strpos($mimetype_filter, '/')) {
1476 1476
 						return $file->getMimetype() === $mimetype_filter;
1477 1477
 					} else {
@@ -1500,7 +1500,7 @@  discard block
 block discarded – undo
1500 1500
 		if ($data instanceof FileInfo) {
1501 1501
 			$data = $data->getData();
1502 1502
 		}
1503
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1503
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1504 1504
 		/**
1505 1505
 		 * @var \OC\Files\Storage\Storage $storage
1506 1506
 		 * @var string $internalPath
@@ -1527,7 +1527,7 @@  discard block
 block discarded – undo
1527 1527
 	 * @return FileInfo[]
1528 1528
 	 */
1529 1529
 	public function search($query) {
1530
-		return $this->searchCommon('search', array('%' . $query . '%'));
1530
+		return $this->searchCommon('search', array('%'.$query.'%'));
1531 1531
 	}
1532 1532
 
1533 1533
 	/**
@@ -1578,10 +1578,10 @@  discard block
 block discarded – undo
1578 1578
 
1579 1579
 			$results = call_user_func_array(array($cache, $method), $args);
1580 1580
 			foreach ($results as $result) {
1581
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1581
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1582 1582
 					$internalPath = $result['path'];
1583
-					$path = $mountPoint . $result['path'];
1584
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1583
+					$path = $mountPoint.$result['path'];
1584
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1585 1585
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1586 1586
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1587 1587
 				}
@@ -1599,8 +1599,8 @@  discard block
 block discarded – undo
1599 1599
 					if ($results) {
1600 1600
 						foreach ($results as $result) {
1601 1601
 							$internalPath = $result['path'];
1602
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1603
-							$path = rtrim($mountPoint . $internalPath, '/');
1602
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1603
+							$path = rtrim($mountPoint.$internalPath, '/');
1604 1604
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1605 1605
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1606 1606
 						}
@@ -1621,7 +1621,7 @@  discard block
 block discarded – undo
1621 1621
 	public function getOwner($path) {
1622 1622
 		$info = $this->getFileInfo($path);
1623 1623
 		if (!$info) {
1624
-			throw new NotFoundException($path . ' not found while trying to get owner');
1624
+			throw new NotFoundException($path.' not found while trying to get owner');
1625 1625
 		}
1626 1626
 		return $info->getOwner()->getUID();
1627 1627
 	}
@@ -1655,7 +1655,7 @@  discard block
 block discarded – undo
1655 1655
 	 * @return string
1656 1656
 	 */
1657 1657
 	public function getPath($id) {
1658
-		$id = (int)$id;
1658
+		$id = (int) $id;
1659 1659
 		$manager = Filesystem::getMountManager();
1660 1660
 		$mounts = $manager->findIn($this->fakeRoot);
1661 1661
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1670,7 +1670,7 @@  discard block
 block discarded – undo
1670 1670
 				$cache = $mount->getStorage()->getCache();
1671 1671
 				$internalPath = $cache->getPathById($id);
1672 1672
 				if (is_string($internalPath)) {
1673
-					$fullPath = $mount->getMountPoint() . $internalPath;
1673
+					$fullPath = $mount->getMountPoint().$internalPath;
1674 1674
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1675 1675
 						return $path;
1676 1676
 					}
@@ -1713,10 +1713,10 @@  discard block
 block discarded – undo
1713 1713
 		}
1714 1714
 
1715 1715
 		// note: cannot use the view because the target is already locked
1716
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1716
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1717 1717
 		if ($fileId === -1) {
1718 1718
 			// target might not exist, need to check parent instead
1719
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1719
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1720 1720
 		}
1721 1721
 
1722 1722
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
 		$resultPath = '';
1829 1829
 		foreach ($parts as $part) {
1830 1830
 			if ($part) {
1831
-				$resultPath .= '/' . $part;
1831
+				$resultPath .= '/'.$part;
1832 1832
 				$result[] = $resultPath;
1833 1833
 			}
1834 1834
 		}
@@ -2078,16 +2078,16 @@  discard block
 block discarded – undo
2078 2078
 	public function getUidAndFilename($filename) {
2079 2079
 		$info = $this->getFileInfo($filename);
2080 2080
 		if (!$info instanceof \OCP\Files\FileInfo) {
2081
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2081
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2082 2082
 		}
2083 2083
 		$uid = $info->getOwner()->getUID();
2084 2084
 		if ($uid != \OCP\User::getUser()) {
2085 2085
 			Filesystem::initMountPoints($uid);
2086
-			$ownerView = new View('/' . $uid . '/files');
2086
+			$ownerView = new View('/'.$uid.'/files');
2087 2087
 			try {
2088 2088
 				$filename = $ownerView->getPath($info['fileid']);
2089 2089
 			} catch (NotFoundException $e) {
2090
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2090
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2091 2091
 			}
2092 2092
 		}
2093 2093
 		return [$uid, $filename];
Please login to merge, or discard this patch.
lib/private/group/manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -154,7 +154,7 @@
 block discarded – undo
154 154
 
155 155
 	/**
156 156
 	 * @param string $gid
157
-	 * @return \OCP\IGroup
157
+	 * @return null|Group
158 158
 	 */
159 159
 	protected function getGroupObject($gid) {
160 160
 		$backends = array();
Please login to merge, or discard this patch.
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -55,298 +55,298 @@
 block discarded – undo
55 55
  * @package OC\Group
56 56
  */
57 57
 class Manager extends PublicEmitter implements IGroupManager {
58
-	/**
59
-	 * @var GroupInterface[] $backends
60
-	 */
61
-	private $backends = array();
58
+    /**
59
+     * @var GroupInterface[] $backends
60
+     */
61
+    private $backends = array();
62 62
 
63
-	/**
64
-	 * @var \OC\User\Manager $userManager
65
-	 */
66
-	private $userManager;
63
+    /**
64
+     * @var \OC\User\Manager $userManager
65
+     */
66
+    private $userManager;
67 67
 
68
-	/**
69
-	 * @var \OC\Group\Group[]
70
-	 */
71
-	private $cachedGroups = array();
68
+    /**
69
+     * @var \OC\Group\Group[]
70
+     */
71
+    private $cachedGroups = array();
72 72
 
73
-	/**
74
-	 * @var \OC\Group\Group[]
75
-	 */
76
-	private $cachedUserGroups = array();
73
+    /**
74
+     * @var \OC\Group\Group[]
75
+     */
76
+    private $cachedUserGroups = array();
77 77
 
78
-	/** @var \OC\SubAdmin */
79
-	private $subAdmin = null;
78
+    /** @var \OC\SubAdmin */
79
+    private $subAdmin = null;
80 80
 
81
-	/**
82
-	 * @param \OC\User\Manager $userManager
83
-	 */
84
-	public function __construct(\OC\User\Manager $userManager) {
85
-		$this->userManager = $userManager;
86
-		$cachedGroups = & $this->cachedGroups;
87
-		$cachedUserGroups = & $this->cachedUserGroups;
88
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
89
-			/**
90
-			 * @var \OC\Group\Group $group
91
-			 */
92
-			unset($cachedGroups[$group->getGID()]);
93
-			$cachedUserGroups = array();
94
-		});
95
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
96
-			/**
97
-			 * @var \OC\Group\Group $group
98
-			 */
99
-			$cachedUserGroups = array();
100
-		});
101
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
102
-			/**
103
-			 * @var \OC\Group\Group $group
104
-			 */
105
-			$cachedUserGroups = array();
106
-		});
107
-	}
81
+    /**
82
+     * @param \OC\User\Manager $userManager
83
+     */
84
+    public function __construct(\OC\User\Manager $userManager) {
85
+        $this->userManager = $userManager;
86
+        $cachedGroups = & $this->cachedGroups;
87
+        $cachedUserGroups = & $this->cachedUserGroups;
88
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
89
+            /**
90
+             * @var \OC\Group\Group $group
91
+             */
92
+            unset($cachedGroups[$group->getGID()]);
93
+            $cachedUserGroups = array();
94
+        });
95
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
96
+            /**
97
+             * @var \OC\Group\Group $group
98
+             */
99
+            $cachedUserGroups = array();
100
+        });
101
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
102
+            /**
103
+             * @var \OC\Group\Group $group
104
+             */
105
+            $cachedUserGroups = array();
106
+        });
107
+    }
108 108
 
109
-	/**
110
-	 * Checks whether a given backend is used
111
-	 *
112
-	 * @param string $backendClass Full classname including complete namespace
113
-	 * @return bool
114
-	 */
115
-	public function isBackendUsed($backendClass) {
116
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
109
+    /**
110
+     * Checks whether a given backend is used
111
+     *
112
+     * @param string $backendClass Full classname including complete namespace
113
+     * @return bool
114
+     */
115
+    public function isBackendUsed($backendClass) {
116
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
117 117
 
118
-		foreach ($this->backends as $backend) {
119
-			if (strtolower(get_class($backend)) === $backendClass) {
120
-				return true;
121
-			}
122
-		}
118
+        foreach ($this->backends as $backend) {
119
+            if (strtolower(get_class($backend)) === $backendClass) {
120
+                return true;
121
+            }
122
+        }
123 123
 
124
-		return false;
125
-	}
124
+        return false;
125
+    }
126 126
 
127
-	/**
128
-	 * @param \OCP\GroupInterface $backend
129
-	 */
130
-	public function addBackend($backend) {
131
-		$this->backends[] = $backend;
132
-		$this->clearCaches();
133
-	}
127
+    /**
128
+     * @param \OCP\GroupInterface $backend
129
+     */
130
+    public function addBackend($backend) {
131
+        $this->backends[] = $backend;
132
+        $this->clearCaches();
133
+    }
134 134
 
135
-	public function clearBackends() {
136
-		$this->backends = array();
137
-		$this->clearCaches();
138
-	}
135
+    public function clearBackends() {
136
+        $this->backends = array();
137
+        $this->clearCaches();
138
+    }
139 139
 	
140
-	protected function clearCaches() {
141
-		$this->cachedGroups = array();
142
-		$this->cachedUserGroups = array();
143
-	}
140
+    protected function clearCaches() {
141
+        $this->cachedGroups = array();
142
+        $this->cachedUserGroups = array();
143
+    }
144 144
 
145
-	/**
146
-	 * @param string $gid
147
-	 * @return \OC\Group\Group
148
-	 */
149
-	public function get($gid) {
150
-		if (isset($this->cachedGroups[$gid])) {
151
-			return $this->cachedGroups[$gid];
152
-		}
153
-		return $this->getGroupObject($gid);
154
-	}
145
+    /**
146
+     * @param string $gid
147
+     * @return \OC\Group\Group
148
+     */
149
+    public function get($gid) {
150
+        if (isset($this->cachedGroups[$gid])) {
151
+            return $this->cachedGroups[$gid];
152
+        }
153
+        return $this->getGroupObject($gid);
154
+    }
155 155
 
156
-	/**
157
-	 * @param string $gid
158
-	 * @return \OCP\IGroup
159
-	 */
160
-	protected function getGroupObject($gid) {
161
-		$backends = array();
162
-		foreach ($this->backends as $backend) {
163
-			if ($backend->groupExists($gid)) {
164
-				$backends[] = $backend;
165
-			}
166
-		}
167
-		if (count($backends) === 0) {
168
-			return null;
169
-		}
170
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this);
171
-		return $this->cachedGroups[$gid];
172
-	}
156
+    /**
157
+     * @param string $gid
158
+     * @return \OCP\IGroup
159
+     */
160
+    protected function getGroupObject($gid) {
161
+        $backends = array();
162
+        foreach ($this->backends as $backend) {
163
+            if ($backend->groupExists($gid)) {
164
+                $backends[] = $backend;
165
+            }
166
+        }
167
+        if (count($backends) === 0) {
168
+            return null;
169
+        }
170
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this);
171
+        return $this->cachedGroups[$gid];
172
+    }
173 173
 
174
-	/**
175
-	 * @param string $gid
176
-	 * @return bool
177
-	 */
178
-	public function groupExists($gid) {
179
-		return !is_null($this->get($gid));
180
-	}
174
+    /**
175
+     * @param string $gid
176
+     * @return bool
177
+     */
178
+    public function groupExists($gid) {
179
+        return !is_null($this->get($gid));
180
+    }
181 181
 
182
-	/**
183
-	 * @param string $gid
184
-	 * @return \OC\Group\Group
185
-	 */
186
-	public function createGroup($gid) {
187
-		if ($gid === '' || is_null($gid)) {
188
-			return false;
189
-		} else if ($group = $this->get($gid)) {
190
-			return $group;
191
-		} else {
192
-			$this->emit('\OC\Group', 'preCreate', array($gid));
193
-			foreach ($this->backends as $backend) {
194
-				if ($backend->implementsActions(\OC_Group_Backend::CREATE_GROUP)) {
195
-					$backend->createGroup($gid);
196
-					$group = $this->getGroupObject($gid);
197
-					$this->emit('\OC\Group', 'postCreate', array($group));
198
-					return $group;
199
-				}
200
-			}
201
-			return null;
202
-		}
203
-	}
182
+    /**
183
+     * @param string $gid
184
+     * @return \OC\Group\Group
185
+     */
186
+    public function createGroup($gid) {
187
+        if ($gid === '' || is_null($gid)) {
188
+            return false;
189
+        } else if ($group = $this->get($gid)) {
190
+            return $group;
191
+        } else {
192
+            $this->emit('\OC\Group', 'preCreate', array($gid));
193
+            foreach ($this->backends as $backend) {
194
+                if ($backend->implementsActions(\OC_Group_Backend::CREATE_GROUP)) {
195
+                    $backend->createGroup($gid);
196
+                    $group = $this->getGroupObject($gid);
197
+                    $this->emit('\OC\Group', 'postCreate', array($group));
198
+                    return $group;
199
+                }
200
+            }
201
+            return null;
202
+        }
203
+    }
204 204
 
205
-	/**
206
-	 * @param string $search
207
-	 * @param int $limit
208
-	 * @param int $offset
209
-	 * @return \OC\Group\Group[]
210
-	 */
211
-	public function search($search, $limit = null, $offset = null) {
212
-		$groups = array();
213
-		foreach ($this->backends as $backend) {
214
-			$groupIds = $backend->getGroups($search, $limit, $offset);
215
-			foreach ($groupIds as $groupId) {
216
-				$groups[$groupId] = $this->get($groupId);
217
-			}
218
-			if (!is_null($limit) and $limit <= 0) {
219
-				return array_values($groups);
220
-			}
221
-		}
222
-		return array_values($groups);
223
-	}
205
+    /**
206
+     * @param string $search
207
+     * @param int $limit
208
+     * @param int $offset
209
+     * @return \OC\Group\Group[]
210
+     */
211
+    public function search($search, $limit = null, $offset = null) {
212
+        $groups = array();
213
+        foreach ($this->backends as $backend) {
214
+            $groupIds = $backend->getGroups($search, $limit, $offset);
215
+            foreach ($groupIds as $groupId) {
216
+                $groups[$groupId] = $this->get($groupId);
217
+            }
218
+            if (!is_null($limit) and $limit <= 0) {
219
+                return array_values($groups);
220
+            }
221
+        }
222
+        return array_values($groups);
223
+    }
224 224
 
225
-	/**
226
-	 * @param \OC\User\User|null $user
227
-	 * @return \OC\Group\Group[]
228
-	 */
229
-	public function getUserGroups($user) {
230
-		if (is_null($user)) {
231
-			return [];
232
-		}
233
-		return $this->getUserIdGroups($user->getUID());
234
-	}
225
+    /**
226
+     * @param \OC\User\User|null $user
227
+     * @return \OC\Group\Group[]
228
+     */
229
+    public function getUserGroups($user) {
230
+        if (is_null($user)) {
231
+            return [];
232
+        }
233
+        return $this->getUserIdGroups($user->getUID());
234
+    }
235 235
 
236
-	/**
237
-	 * @param string $uid the user id
238
-	 * @return \OC\Group\Group[]
239
-	 */
240
-	public function getUserIdGroups($uid) {
241
-		if (isset($this->cachedUserGroups[$uid])) {
242
-			return $this->cachedUserGroups[$uid];
243
-		}
244
-		$groups = array();
245
-		foreach ($this->backends as $backend) {
246
-			$groupIds = $backend->getUserGroups($uid);
247
-			if (is_array($groupIds)) {
248
-				foreach ($groupIds as $groupId) {
249
-					$groups[$groupId] = $this->get($groupId);
250
-				}
251
-			}
252
-		}
253
-		$this->cachedUserGroups[$uid] = $groups;
254
-		return $this->cachedUserGroups[$uid];
255
-	}
236
+    /**
237
+     * @param string $uid the user id
238
+     * @return \OC\Group\Group[]
239
+     */
240
+    public function getUserIdGroups($uid) {
241
+        if (isset($this->cachedUserGroups[$uid])) {
242
+            return $this->cachedUserGroups[$uid];
243
+        }
244
+        $groups = array();
245
+        foreach ($this->backends as $backend) {
246
+            $groupIds = $backend->getUserGroups($uid);
247
+            if (is_array($groupIds)) {
248
+                foreach ($groupIds as $groupId) {
249
+                    $groups[$groupId] = $this->get($groupId);
250
+                }
251
+            }
252
+        }
253
+        $this->cachedUserGroups[$uid] = $groups;
254
+        return $this->cachedUserGroups[$uid];
255
+    }
256 256
 
257
-	/**
258
-	 * Checks if a userId is in the admin group
259
-	 * @param string $userId
260
-	 * @return bool if admin
261
-	 */
262
-	public function isAdmin($userId) {
263
-		return $this->isInGroup($userId, 'admin');
264
-	}
257
+    /**
258
+     * Checks if a userId is in the admin group
259
+     * @param string $userId
260
+     * @return bool if admin
261
+     */
262
+    public function isAdmin($userId) {
263
+        return $this->isInGroup($userId, 'admin');
264
+    }
265 265
 
266
-	/**
267
-	 * Checks if a userId is in a group
268
-	 * @param string $userId
269
-	 * @param string $group
270
-	 * @return bool if in group
271
-	 */
272
-	public function isInGroup($userId, $group) {
273
-		return array_key_exists($group, $this->getUserIdGroups($userId));
274
-	}
266
+    /**
267
+     * Checks if a userId is in a group
268
+     * @param string $userId
269
+     * @param string $group
270
+     * @return bool if in group
271
+     */
272
+    public function isInGroup($userId, $group) {
273
+        return array_key_exists($group, $this->getUserIdGroups($userId));
274
+    }
275 275
 
276
-	/**
277
-	 * get a list of group ids for a user
278
-	 * @param \OC\User\User $user
279
-	 * @return array with group ids
280
-	 */
281
-	public function getUserGroupIds($user) {
282
-		return array_map(function($value) {
283
-			return (string) $value;
284
-		}, array_keys($this->getUserGroups($user)));
285
-	}
276
+    /**
277
+     * get a list of group ids for a user
278
+     * @param \OC\User\User $user
279
+     * @return array with group ids
280
+     */
281
+    public function getUserGroupIds($user) {
282
+        return array_map(function($value) {
283
+            return (string) $value;
284
+        }, array_keys($this->getUserGroups($user)));
285
+    }
286 286
 
287
-	/**
288
-	 * get a list of all display names in a group
289
-	 * @param string $gid
290
-	 * @param string $search
291
-	 * @param int $limit
292
-	 * @param int $offset
293
-	 * @return array an array of display names (value) and user ids (key)
294
-	 */
295
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
296
-		$group = $this->get($gid);
297
-		if(is_null($group)) {
298
-			return array();
299
-		}
287
+    /**
288
+     * get a list of all display names in a group
289
+     * @param string $gid
290
+     * @param string $search
291
+     * @param int $limit
292
+     * @param int $offset
293
+     * @return array an array of display names (value) and user ids (key)
294
+     */
295
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
296
+        $group = $this->get($gid);
297
+        if(is_null($group)) {
298
+            return array();
299
+        }
300 300
 
301
-		$search = trim($search);
302
-		$groupUsers = array();
301
+        $search = trim($search);
302
+        $groupUsers = array();
303 303
 
304
-		if(!empty($search)) {
305
-			// only user backends have the capability to do a complex search for users
306
-			$searchOffset = 0;
307
-			$searchLimit = $limit * 100;
308
-			if($limit === -1) {
309
-				$searchLimit = 500;
310
-			}
304
+        if(!empty($search)) {
305
+            // only user backends have the capability to do a complex search for users
306
+            $searchOffset = 0;
307
+            $searchLimit = $limit * 100;
308
+            if($limit === -1) {
309
+                $searchLimit = 500;
310
+            }
311 311
 
312
-			do {
313
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
314
-				foreach($filteredUsers as $filteredUser) {
315
-					if($group->inGroup($filteredUser)) {
316
-						$groupUsers[]= $filteredUser;
317
-					}
318
-				}
319
-				$searchOffset += $searchLimit;
320
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
312
+            do {
313
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
314
+                foreach($filteredUsers as $filteredUser) {
315
+                    if($group->inGroup($filteredUser)) {
316
+                        $groupUsers[]= $filteredUser;
317
+                    }
318
+                }
319
+                $searchOffset += $searchLimit;
320
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
321 321
 
322
-			if($limit === -1) {
323
-				$groupUsers = array_slice($groupUsers, $offset);
324
-			} else {
325
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
326
-			}
327
-		} else {
328
-			$groupUsers = $group->searchUsers('', $limit, $offset);
329
-		}
322
+            if($limit === -1) {
323
+                $groupUsers = array_slice($groupUsers, $offset);
324
+            } else {
325
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
326
+            }
327
+        } else {
328
+            $groupUsers = $group->searchUsers('', $limit, $offset);
329
+        }
330 330
 
331
-		$matchingUsers = array();
332
-		foreach($groupUsers as $groupUser) {
333
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
334
-		}
335
-		return $matchingUsers;
336
-	}
331
+        $matchingUsers = array();
332
+        foreach($groupUsers as $groupUser) {
333
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
334
+        }
335
+        return $matchingUsers;
336
+    }
337 337
 
338
-	/**
339
-	 * @return \OC\SubAdmin
340
-	 */
341
-	public function getSubAdmin() {
342
-		if (!$this->subAdmin) {
343
-			$this->subAdmin = new \OC\SubAdmin(
344
-				$this->userManager,
345
-				$this,
346
-				\OC::$server->getDatabaseConnection()
347
-			);
348
-		}
338
+    /**
339
+     * @return \OC\SubAdmin
340
+     */
341
+    public function getSubAdmin() {
342
+        if (!$this->subAdmin) {
343
+            $this->subAdmin = new \OC\SubAdmin(
344
+                $this->userManager,
345
+                $this,
346
+                \OC::$server->getDatabaseConnection()
347
+            );
348
+        }
349 349
 
350
-		return $this->subAdmin;
351
-	}
350
+        return $this->subAdmin;
351
+    }
352 352
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -85,20 +85,20 @@  discard block
 block discarded – undo
85 85
 		$this->userManager = $userManager;
86 86
 		$cachedGroups = & $this->cachedGroups;
87 87
 		$cachedUserGroups = & $this->cachedUserGroups;
88
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
88
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
89 89
 			/**
90 90
 			 * @var \OC\Group\Group $group
91 91
 			 */
92 92
 			unset($cachedGroups[$group->getGID()]);
93 93
 			$cachedUserGroups = array();
94 94
 		});
95
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
95
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
96 96
 			/**
97 97
 			 * @var \OC\Group\Group $group
98 98
 			 */
99 99
 			$cachedUserGroups = array();
100 100
 		});
101
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
101
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
102 102
 			/**
103 103
 			 * @var \OC\Group\Group $group
104 104
 			 */
@@ -304,32 +304,32 @@  discard block
 block discarded – undo
304 304
 	 */
305 305
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
306 306
 		$group = $this->get($gid);
307
-		if(is_null($group)) {
307
+		if (is_null($group)) {
308 308
 			return array();
309 309
 		}
310 310
 
311 311
 		$search = trim($search);
312 312
 		$groupUsers = array();
313 313
 
314
-		if(!empty($search)) {
314
+		if (!empty($search)) {
315 315
 			// only user backends have the capability to do a complex search for users
316 316
 			$searchOffset = 0;
317 317
 			$searchLimit = $limit * 100;
318
-			if($limit === -1) {
318
+			if ($limit === -1) {
319 319
 				$searchLimit = 500;
320 320
 			}
321 321
 
322 322
 			do {
323 323
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
324
-				foreach($filteredUsers as $filteredUser) {
325
-					if($group->inGroup($filteredUser)) {
326
-						$groupUsers[]= $filteredUser;
324
+				foreach ($filteredUsers as $filteredUser) {
325
+					if ($group->inGroup($filteredUser)) {
326
+						$groupUsers[] = $filteredUser;
327 327
 					}
328 328
 				}
329 329
 				$searchOffset += $searchLimit;
330
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
330
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
331 331
 
332
-			if($limit === -1) {
332
+			if ($limit === -1) {
333 333
 				$groupUsers = array_slice($groupUsers, $offset);
334 334
 			} else {
335 335
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		}
340 340
 
341 341
 		$matchingUsers = array();
342
-		foreach($groupUsers as $groupUser) {
342
+		foreach ($groupUsers as $groupUser) {
343 343
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
344 344
 		}
345 345
 		return $matchingUsers;
Please login to merge, or discard this patch.
lib/private/helper.php 4 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -77,6 +77,9 @@  discard block
 block discarded – undo
77 77
 		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
78 78
 	}
79 79
 
80
+	/**
81
+	 * @param string $path
82
+	 */
80 83
 	public static function publicPreviewIcon( $path, $token ) {
81 84
 		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_public_preview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
82 85
 	}
@@ -591,7 +594,7 @@  discard block
 block discarded – undo
591 594
 	 *
592 595
 	 * @param string $path
593 596
 	 * @param \OCP\Files\FileInfo $rootInfo (optional)
594
-	 * @return array
597
+	 * @return string
595 598
 	 * @throws \OCP\Files\NotFoundException
596 599
 	 */
597 600
 	public static function getStorageInfo($path, $rootInfo = null) {
Please login to merge, or discard this patch.
Indentation   +655 added lines, -655 removed lines patch added patch discarded remove patch
@@ -49,659 +49,659 @@
 block discarded – undo
49 49
  * Collection of useful functions
50 50
  */
51 51
 class OC_Helper {
52
-	private static $templateManager;
53
-
54
-	/**
55
-	 * Creates an absolute url for public use
56
-	 * @param string $service id
57
-	 * @param bool $add_slash
58
-	 * @return string the url
59
-	 *
60
-	 * Returns a absolute url to the given service.
61
-	 */
62
-	public static function linkToPublic($service, $add_slash = false) {
63
-		if ($service === 'files') {
64
-			$url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
65
-		} else {
66
-			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
67
-		}
68
-		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
69
-	}
70
-
71
-	/**
72
-	 * get path to preview of file
73
-	 * @param string $path path
74
-	 * @return string the url
75
-	 *
76
-	 * Returns the path to the preview of the file.
77
-	 */
78
-	public static function previewIcon($path) {
79
-		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
80
-	}
81
-
82
-	public static function publicPreviewIcon( $path, $token ) {
83
-		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_public_preview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
84
-	}
85
-
86
-	/**
87
-	 * Make a human file size
88
-	 * @param int $bytes file size in bytes
89
-	 * @return string a human readable file size
90
-	 *
91
-	 * Makes 2048 to 2 kB.
92
-	 */
93
-	public static function humanFileSize($bytes) {
94
-		if ($bytes < 0) {
95
-			return "?";
96
-		}
97
-		if ($bytes < 1024) {
98
-			return "$bytes B";
99
-		}
100
-		$bytes = round($bytes / 1024, 0);
101
-		if ($bytes < 1024) {
102
-			return "$bytes KB";
103
-		}
104
-		$bytes = round($bytes / 1024, 1);
105
-		if ($bytes < 1024) {
106
-			return "$bytes MB";
107
-		}
108
-		$bytes = round($bytes / 1024, 1);
109
-		if ($bytes < 1024) {
110
-			return "$bytes GB";
111
-		}
112
-		$bytes = round($bytes / 1024, 1);
113
-		if ($bytes < 1024) {
114
-			return "$bytes TB";
115
-		}
116
-
117
-		$bytes = round($bytes / 1024, 1);
118
-		return "$bytes PB";
119
-	}
120
-
121
-	/**
122
-	 * Make a php file size
123
-	 * @param int $bytes file size in bytes
124
-	 * @return string a php parseable file size
125
-	 *
126
-	 * Makes 2048 to 2k and 2^41 to 2048G
127
-	 */
128
-	public static function phpFileSize($bytes) {
129
-		if ($bytes < 0) {
130
-			return "?";
131
-		}
132
-		if ($bytes < 1024) {
133
-			return $bytes . "B";
134
-		}
135
-		$bytes = round($bytes / 1024, 1);
136
-		if ($bytes < 1024) {
137
-			return $bytes . "K";
138
-		}
139
-		$bytes = round($bytes / 1024, 1);
140
-		if ($bytes < 1024) {
141
-			return $bytes . "M";
142
-		}
143
-		$bytes = round($bytes / 1024, 1);
144
-		return $bytes . "G";
145
-	}
146
-
147
-	/**
148
-	 * Make a computer file size
149
-	 * @param string $str file size in human readable format
150
-	 * @return float a file size in bytes
151
-	 *
152
-	 * Makes 2kB to 2048.
153
-	 *
154
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
155
-	 */
156
-	public static function computerFileSize($str) {
157
-		$str = strtolower($str);
158
-		if (is_numeric($str)) {
159
-			return floatval($str);
160
-		}
161
-
162
-		$bytes_array = array(
163
-			'b' => 1,
164
-			'k' => 1024,
165
-			'kb' => 1024,
166
-			'mb' => 1024 * 1024,
167
-			'm' => 1024 * 1024,
168
-			'gb' => 1024 * 1024 * 1024,
169
-			'g' => 1024 * 1024 * 1024,
170
-			'tb' => 1024 * 1024 * 1024 * 1024,
171
-			't' => 1024 * 1024 * 1024 * 1024,
172
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
173
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
174
-		);
175
-
176
-		$bytes = floatval($str);
177
-
178
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
179
-			$bytes *= $bytes_array[$matches[1]];
180
-		} else {
181
-			return false;
182
-		}
183
-
184
-		$bytes = round($bytes);
185
-
186
-		return $bytes;
187
-	}
188
-
189
-	/**
190
-	 * Recursive copying of folders
191
-	 * @param string $src source folder
192
-	 * @param string $dest target folder
193
-	 *
194
-	 */
195
-	static function copyr($src, $dest) {
196
-		if (is_dir($src)) {
197
-			if (!is_dir($dest)) {
198
-				mkdir($dest);
199
-			}
200
-			$files = scandir($src);
201
-			foreach ($files as $file) {
202
-				if ($file != "." && $file != "..") {
203
-					self::copyr("$src/$file", "$dest/$file");
204
-				}
205
-			}
206
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
207
-			copy($src, $dest);
208
-		}
209
-	}
210
-
211
-	/**
212
-	 * Recursive deletion of folders
213
-	 * @param string $dir path to the folder
214
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
215
-	 * @return bool
216
-	 */
217
-	static function rmdirr($dir, $deleteSelf = true) {
218
-		if (is_dir($dir)) {
219
-			$files = new RecursiveIteratorIterator(
220
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
221
-				RecursiveIteratorIterator::CHILD_FIRST
222
-			);
223
-
224
-			foreach ($files as $fileInfo) {
225
-				/** @var SplFileInfo $fileInfo */
226
-				if ($fileInfo->isLink()) {
227
-					unlink($fileInfo->getPathname());
228
-				} else if ($fileInfo->isDir()) {
229
-					rmdir($fileInfo->getRealPath());
230
-				} else {
231
-					unlink($fileInfo->getRealPath());
232
-				}
233
-			}
234
-			if ($deleteSelf) {
235
-				rmdir($dir);
236
-			}
237
-		} elseif (file_exists($dir)) {
238
-			if ($deleteSelf) {
239
-				unlink($dir);
240
-			}
241
-		}
242
-		if (!$deleteSelf) {
243
-			return true;
244
-		}
245
-
246
-		return !file_exists($dir);
247
-	}
248
-
249
-	/**
250
-	 * @return \OC\Files\Type\TemplateManager
251
-	 */
252
-	static public function getFileTemplateManager() {
253
-		if (!self::$templateManager) {
254
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
255
-		}
256
-		return self::$templateManager;
257
-	}
258
-
259
-	/**
260
-	 * detect if a given program is found in the search PATH
261
-	 *
262
-	 * @param string $name
263
-	 * @param bool $path
264
-	 * @internal param string $program name
265
-	 * @internal param string $optional search path, defaults to $PATH
266
-	 * @return bool    true if executable program found in path
267
-	 */
268
-	public static function canExecute($name, $path = false) {
269
-		// path defaults to PATH from environment if not set
270
-		if ($path === false) {
271
-			$path = getenv("PATH");
272
-		}
273
-		// check method depends on operating system
274
-		if (!strncmp(PHP_OS, "WIN", 3)) {
275
-			// on Windows an appropriate COM or EXE file needs to exist
276
-			$exts = array(".exe", ".com");
277
-			$check_fn = "file_exists";
278
-		} else {
279
-			// anywhere else we look for an executable file of that name
280
-			$exts = array("");
281
-			$check_fn = "is_executable";
282
-		}
283
-		// Default check will be done with $path directories :
284
-		$dirs = explode(PATH_SEPARATOR, $path);
285
-		// WARNING : We have to check if open_basedir is enabled :
286
-		$obd = OC::$server->getIniWrapper()->getString('open_basedir');
287
-		if ($obd != "none") {
288
-			$obd_values = explode(PATH_SEPARATOR, $obd);
289
-			if (count($obd_values) > 0 and $obd_values[0]) {
290
-				// open_basedir is in effect !
291
-				// We need to check if the program is in one of these dirs :
292
-				$dirs = $obd_values;
293
-			}
294
-		}
295
-		foreach ($dirs as $dir) {
296
-			foreach ($exts as $ext) {
297
-				if ($check_fn("$dir/$name" . $ext))
298
-					return true;
299
-			}
300
-		}
301
-		return false;
302
-	}
303
-
304
-	/**
305
-	 * copy the contents of one stream to another
306
-	 *
307
-	 * @param resource $source
308
-	 * @param resource $target
309
-	 * @return array the number of bytes copied and result
310
-	 */
311
-	public static function streamCopy($source, $target) {
312
-		if (!$source or !$target) {
313
-			return array(0, false);
314
-		}
315
-		$bufSize = 8192;
316
-		$result = true;
317
-		$count = 0;
318
-		while (!feof($source)) {
319
-			$buf = fread($source, $bufSize);
320
-			$bytesWritten = fwrite($target, $buf);
321
-			if ($bytesWritten !== false) {
322
-				$count += $bytesWritten;
323
-			}
324
-			// note: strlen is expensive so only use it when necessary,
325
-			// on the last block
326
-			if ($bytesWritten === false
327
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
328
-			) {
329
-				// write error, could be disk full ?
330
-				$result = false;
331
-				break;
332
-			}
333
-		}
334
-		return array($count, $result);
335
-	}
336
-
337
-	/**
338
-	 * Adds a suffix to the name in case the file exists
339
-	 *
340
-	 * @param string $path
341
-	 * @param string $filename
342
-	 * @return string
343
-	 */
344
-	public static function buildNotExistingFileName($path, $filename) {
345
-		$view = \OC\Files\Filesystem::getView();
346
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
347
-	}
348
-
349
-	/**
350
-	 * Adds a suffix to the name in case the file exists
351
-	 *
352
-	 * @param string $path
353
-	 * @param string $filename
354
-	 * @return string
355
-	 */
356
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
357
-		if ($path === '/') {
358
-			$path = '';
359
-		}
360
-		if ($pos = strrpos($filename, '.')) {
361
-			$name = substr($filename, 0, $pos);
362
-			$ext = substr($filename, $pos);
363
-		} else {
364
-			$name = $filename;
365
-			$ext = '';
366
-		}
367
-
368
-		$newpath = $path . '/' . $filename;
369
-		if ($view->file_exists($newpath)) {
370
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
371
-				//Replace the last "(number)" with "(number+1)"
372
-				$last_match = count($matches[0]) - 1;
373
-				$counter = $matches[1][$last_match][0] + 1;
374
-				$offset = $matches[0][$last_match][1];
375
-				$match_length = strlen($matches[0][$last_match][0]);
376
-			} else {
377
-				$counter = 2;
378
-				$match_length = 0;
379
-				$offset = false;
380
-			}
381
-			do {
382
-				if ($offset) {
383
-					//Replace the last "(number)" with "(number+1)"
384
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
385
-				} else {
386
-					$newname = $name . ' (' . $counter . ')';
387
-				}
388
-				$newpath = $path . '/' . $newname . $ext;
389
-				$counter++;
390
-			} while ($view->file_exists($newpath));
391
-		}
392
-
393
-		return $newpath;
394
-	}
395
-
396
-	/**
397
-	 * Checks if $sub is a subdirectory of $parent
398
-	 *
399
-	 * @param string $sub
400
-	 * @param string $parent
401
-	 * @return bool
402
-	 */
403
-	public static function isSubDirectory($sub, $parent) {
404
-		$realpathSub = realpath($sub);
405
-		$realpathParent = realpath($parent);
406
-
407
-		// realpath() may return false in case the directory does not exist
408
-		// since we can not be sure how different PHP versions may behave here
409
-		// we do an additional check whether realpath returned false
410
-		if($realpathSub === false ||  $realpathParent === false) {
411
-			return false;
412
-		}
413
-
414
-		// Check whether $sub is a subdirectory of $parent
415
-		if (strpos($realpathSub, $realpathParent) === 0) {
416
-			return true;
417
-		}
418
-
419
-		return false;
420
-	}
421
-
422
-	/**
423
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
424
-	 *
425
-	 * @param array $input The array to work on
426
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
427
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
428
-	 * @return array
429
-	 *
430
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
431
-	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
432
-	 *
433
-	 */
434
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
435
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
436
-		$ret = array();
437
-		foreach ($input as $k => $v) {
438
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
439
-		}
440
-		return $ret;
441
-	}
442
-
443
-	/**
444
-	 * performs a search in a nested array
445
-	 * @param array $haystack the array to be searched
446
-	 * @param string $needle the search string
447
-	 * @param string $index optional, only search this key name
448
-	 * @return mixed the key of the matching field, otherwise false
449
-	 *
450
-	 * performs a search in a nested array
451
-	 *
452
-	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
453
-	 */
454
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
455
-		$aIt = new RecursiveArrayIterator($haystack);
456
-		$it = new RecursiveIteratorIterator($aIt);
457
-
458
-		while ($it->valid()) {
459
-			if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
460
-				return $aIt->key();
461
-			}
462
-
463
-			$it->next();
464
-		}
465
-
466
-		return false;
467
-	}
468
-
469
-	/**
470
-	 * Shortens str to maxlen by replacing characters in the middle with '...', eg.
471
-	 * ellipsis('a very long string with lots of useless info to make a better example', 14) becomes 'a very ...example'
472
-	 *
473
-	 * @param string $str the string
474
-	 * @param string $maxlen the maximum length of the result
475
-	 * @return string with at most maxlen characters
476
-	 */
477
-	public static function ellipsis($str, $maxlen) {
478
-		if (strlen($str) > $maxlen) {
479
-			$characters = floor($maxlen / 2);
480
-			return substr($str, 0, $characters) . '...' . substr($str, -1 * $characters);
481
-		}
482
-		return $str;
483
-	}
484
-
485
-	/**
486
-	 * calculates the maximum upload size respecting system settings, free space and user quota
487
-	 *
488
-	 * @param string $dir the current folder where the user currently operates
489
-	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
490
-	 * @return int number of bytes representing
491
-	 */
492
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
493
-		if (is_null($freeSpace) || $freeSpace < 0){
494
-			$freeSpace = self::freeSpace($dir);
495
-		}
496
-		return min($freeSpace, self::uploadLimit());
497
-	}
498
-
499
-	/**
500
-	 * Calculate free space left within user quota
501
-	 *
502
-	 * @param string $dir the current folder where the user currently operates
503
-	 * @return int number of bytes representing
504
-	 */
505
-	public static function freeSpace($dir) {
506
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
507
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
508
-			$freeSpace = max($freeSpace, 0);
509
-			return $freeSpace;
510
-		} else {
511
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
512
-		}
513
-	}
514
-
515
-	/**
516
-	 * Calculate PHP upload limit
517
-	 *
518
-	 * @return int PHP upload file size limit
519
-	 */
520
-	public static function uploadLimit() {
521
-		$ini = \OC::$server->getIniWrapper();
522
-		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
523
-		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
524
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
525
-			return INF;
526
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
527
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
528
-		} else {
529
-			return min($upload_max_filesize, $post_max_size);
530
-		}
531
-	}
532
-
533
-	/**
534
-	 * Checks if a function is available
535
-	 *
536
-	 * @param string $function_name
537
-	 * @return bool
538
-	 */
539
-	public static function is_function_enabled($function_name) {
540
-		if (!function_exists($function_name)) {
541
-			return false;
542
-		}
543
-		$ini = \OC::$server->getIniWrapper();
544
-		$disabled = explode(',', $ini->get('disable_functions'));
545
-		$disabled = array_map('trim', $disabled);
546
-		if (in_array($function_name, $disabled)) {
547
-			return false;
548
-		}
549
-		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
550
-		$disabled = array_map('trim', $disabled);
551
-		if (in_array($function_name, $disabled)) {
552
-			return false;
553
-		}
554
-		return true;
555
-	}
556
-
557
-	/**
558
-	 * Try to find a program
559
-	 * Note: currently windows is not supported
560
-	 *
561
-	 * @param string $program
562
-	 * @return null|string
563
-	 */
564
-	public static function findBinaryPath($program) {
565
-		$memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
566
-		if ($memcache->hasKey($program)) {
567
-			return $memcache->get($program);
568
-		}
569
-		$result = null;
570
-		if (!\OC_Util::runningOnWindows() && self::is_function_enabled('exec')) {
571
-			$exeSniffer = new ExecutableFinder();
572
-			// Returns null if nothing is found
573
-			$result = $exeSniffer->find($program);
574
-			if (empty($result)) {
575
-				$paths = getenv('PATH');
576
-				if (empty($paths)) {
577
-					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
578
-				} else {
579
-					$paths = str_replace(':',' ',getenv('PATH'));
580
-				}
581
-				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
582
-				exec($command, $output, $returnCode);
583
-				if (count($output) > 0) {
584
-					$result = escapeshellcmd($output[0]);
585
-				}
586
-			}
587
-		}
588
-		// store the value for 5 minutes
589
-		$memcache->set($program, $result, 300);
590
-		return $result;
591
-	}
592
-
593
-	/**
594
-	 * Calculate the disc space for the given path
595
-	 *
596
-	 * @param string $path
597
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
598
-	 * @return array
599
-	 * @throws \OCP\Files\NotFoundException
600
-	 */
601
-	public static function getStorageInfo($path, $rootInfo = null) {
602
-		// return storage info without adding mount points
603
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
604
-
605
-		if (!$rootInfo) {
606
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
607
-		}
608
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
609
-			throw new \OCP\Files\NotFoundException();
610
-		}
611
-		$used = $rootInfo->getSize();
612
-		if ($used < 0) {
613
-			$used = 0;
614
-		}
615
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
616
-		$storage = $rootInfo->getStorage();
617
-		$sourceStorage = $storage;
618
-		if ($storage->instanceOfStorage('\OC\Files\Storage\Shared')) {
619
-			$includeExtStorage = false;
620
-			$sourceStorage = $storage->getSourceStorage();
621
-		}
622
-		if ($includeExtStorage) {
623
-			$quota = OC_Util::getUserQuota(\OCP\User::getUser());
624
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
625
-				// always get free space / total space from root + mount points
626
-				return self::getGlobalStorageInfo();
627
-			}
628
-		}
629
-
630
-		// TODO: need a better way to get total space from storage
631
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
632
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
633
-			$quota = $sourceStorage->getQuota();
634
-		}
635
-		$free = $storage->free_space('');
636
-		if ($free >= 0) {
637
-			$total = $free + $used;
638
-		} else {
639
-			$total = $free; //either unknown or unlimited
640
-		}
641
-		if ($total > 0) {
642
-			if ($quota > 0 && $total > $quota) {
643
-				$total = $quota;
644
-			}
645
-			// prevent division by zero or error codes (negative values)
646
-			$relative = round(($used / $total) * 10000) / 100;
647
-		} else {
648
-			$relative = 0;
649
-		}
650
-
651
-		$ownerId = $storage->getOwner($path);
652
-		$ownerDisplayName = '';
653
-		$owner = \OC::$server->getUserManager()->get($ownerId);
654
-		if($owner) {
655
-			$ownerDisplayName = $owner->getDisplayName();
656
-		}
657
-
658
-		return [
659
-			'free' => $free,
660
-			'used' => $used,
661
-			'quota' => $quota,
662
-			'total' => $total,
663
-			'relative' => $relative,
664
-			'owner' => $ownerId,
665
-			'ownerDisplayName' => $ownerDisplayName,
666
-		];
667
-	}
668
-
669
-	/**
670
-	 * Get storage info including all mount points and quota
671
-	 *
672
-	 * @return array
673
-	 */
674
-	private static function getGlobalStorageInfo() {
675
-		$quota = OC_Util::getUserQuota(\OCP\User::getUser());
676
-
677
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
678
-		$used = $rootInfo['size'];
679
-		if ($used < 0) {
680
-			$used = 0;
681
-		}
682
-
683
-		$total = $quota;
684
-		$free = $quota - $used;
685
-
686
-		if ($total > 0) {
687
-			if ($quota > 0 && $total > $quota) {
688
-				$total = $quota;
689
-			}
690
-			// prevent division by zero or error codes (negative values)
691
-			$relative = round(($used / $total) * 10000) / 100;
692
-		} else {
693
-			$relative = 0;
694
-		}
695
-
696
-		return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
697
-
698
-	}
699
-
700
-	/**
701
-	 * Returns whether the config file is set manually to read-only
702
-	 * @return bool
703
-	 */
704
-	public static function isReadOnlyConfigEnabled() {
705
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
706
-	}
52
+    private static $templateManager;
53
+
54
+    /**
55
+     * Creates an absolute url for public use
56
+     * @param string $service id
57
+     * @param bool $add_slash
58
+     * @return string the url
59
+     *
60
+     * Returns a absolute url to the given service.
61
+     */
62
+    public static function linkToPublic($service, $add_slash = false) {
63
+        if ($service === 'files') {
64
+            $url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
65
+        } else {
66
+            $url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
67
+        }
68
+        return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
69
+    }
70
+
71
+    /**
72
+     * get path to preview of file
73
+     * @param string $path path
74
+     * @return string the url
75
+     *
76
+     * Returns the path to the preview of the file.
77
+     */
78
+    public static function previewIcon($path) {
79
+        return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
80
+    }
81
+
82
+    public static function publicPreviewIcon( $path, $token ) {
83
+        return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_public_preview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
84
+    }
85
+
86
+    /**
87
+     * Make a human file size
88
+     * @param int $bytes file size in bytes
89
+     * @return string a human readable file size
90
+     *
91
+     * Makes 2048 to 2 kB.
92
+     */
93
+    public static function humanFileSize($bytes) {
94
+        if ($bytes < 0) {
95
+            return "?";
96
+        }
97
+        if ($bytes < 1024) {
98
+            return "$bytes B";
99
+        }
100
+        $bytes = round($bytes / 1024, 0);
101
+        if ($bytes < 1024) {
102
+            return "$bytes KB";
103
+        }
104
+        $bytes = round($bytes / 1024, 1);
105
+        if ($bytes < 1024) {
106
+            return "$bytes MB";
107
+        }
108
+        $bytes = round($bytes / 1024, 1);
109
+        if ($bytes < 1024) {
110
+            return "$bytes GB";
111
+        }
112
+        $bytes = round($bytes / 1024, 1);
113
+        if ($bytes < 1024) {
114
+            return "$bytes TB";
115
+        }
116
+
117
+        $bytes = round($bytes / 1024, 1);
118
+        return "$bytes PB";
119
+    }
120
+
121
+    /**
122
+     * Make a php file size
123
+     * @param int $bytes file size in bytes
124
+     * @return string a php parseable file size
125
+     *
126
+     * Makes 2048 to 2k and 2^41 to 2048G
127
+     */
128
+    public static function phpFileSize($bytes) {
129
+        if ($bytes < 0) {
130
+            return "?";
131
+        }
132
+        if ($bytes < 1024) {
133
+            return $bytes . "B";
134
+        }
135
+        $bytes = round($bytes / 1024, 1);
136
+        if ($bytes < 1024) {
137
+            return $bytes . "K";
138
+        }
139
+        $bytes = round($bytes / 1024, 1);
140
+        if ($bytes < 1024) {
141
+            return $bytes . "M";
142
+        }
143
+        $bytes = round($bytes / 1024, 1);
144
+        return $bytes . "G";
145
+    }
146
+
147
+    /**
148
+     * Make a computer file size
149
+     * @param string $str file size in human readable format
150
+     * @return float a file size in bytes
151
+     *
152
+     * Makes 2kB to 2048.
153
+     *
154
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
155
+     */
156
+    public static function computerFileSize($str) {
157
+        $str = strtolower($str);
158
+        if (is_numeric($str)) {
159
+            return floatval($str);
160
+        }
161
+
162
+        $bytes_array = array(
163
+            'b' => 1,
164
+            'k' => 1024,
165
+            'kb' => 1024,
166
+            'mb' => 1024 * 1024,
167
+            'm' => 1024 * 1024,
168
+            'gb' => 1024 * 1024 * 1024,
169
+            'g' => 1024 * 1024 * 1024,
170
+            'tb' => 1024 * 1024 * 1024 * 1024,
171
+            't' => 1024 * 1024 * 1024 * 1024,
172
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
173
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
174
+        );
175
+
176
+        $bytes = floatval($str);
177
+
178
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
179
+            $bytes *= $bytes_array[$matches[1]];
180
+        } else {
181
+            return false;
182
+        }
183
+
184
+        $bytes = round($bytes);
185
+
186
+        return $bytes;
187
+    }
188
+
189
+    /**
190
+     * Recursive copying of folders
191
+     * @param string $src source folder
192
+     * @param string $dest target folder
193
+     *
194
+     */
195
+    static function copyr($src, $dest) {
196
+        if (is_dir($src)) {
197
+            if (!is_dir($dest)) {
198
+                mkdir($dest);
199
+            }
200
+            $files = scandir($src);
201
+            foreach ($files as $file) {
202
+                if ($file != "." && $file != "..") {
203
+                    self::copyr("$src/$file", "$dest/$file");
204
+                }
205
+            }
206
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
207
+            copy($src, $dest);
208
+        }
209
+    }
210
+
211
+    /**
212
+     * Recursive deletion of folders
213
+     * @param string $dir path to the folder
214
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
215
+     * @return bool
216
+     */
217
+    static function rmdirr($dir, $deleteSelf = true) {
218
+        if (is_dir($dir)) {
219
+            $files = new RecursiveIteratorIterator(
220
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
221
+                RecursiveIteratorIterator::CHILD_FIRST
222
+            );
223
+
224
+            foreach ($files as $fileInfo) {
225
+                /** @var SplFileInfo $fileInfo */
226
+                if ($fileInfo->isLink()) {
227
+                    unlink($fileInfo->getPathname());
228
+                } else if ($fileInfo->isDir()) {
229
+                    rmdir($fileInfo->getRealPath());
230
+                } else {
231
+                    unlink($fileInfo->getRealPath());
232
+                }
233
+            }
234
+            if ($deleteSelf) {
235
+                rmdir($dir);
236
+            }
237
+        } elseif (file_exists($dir)) {
238
+            if ($deleteSelf) {
239
+                unlink($dir);
240
+            }
241
+        }
242
+        if (!$deleteSelf) {
243
+            return true;
244
+        }
245
+
246
+        return !file_exists($dir);
247
+    }
248
+
249
+    /**
250
+     * @return \OC\Files\Type\TemplateManager
251
+     */
252
+    static public function getFileTemplateManager() {
253
+        if (!self::$templateManager) {
254
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
255
+        }
256
+        return self::$templateManager;
257
+    }
258
+
259
+    /**
260
+     * detect if a given program is found in the search PATH
261
+     *
262
+     * @param string $name
263
+     * @param bool $path
264
+     * @internal param string $program name
265
+     * @internal param string $optional search path, defaults to $PATH
266
+     * @return bool    true if executable program found in path
267
+     */
268
+    public static function canExecute($name, $path = false) {
269
+        // path defaults to PATH from environment if not set
270
+        if ($path === false) {
271
+            $path = getenv("PATH");
272
+        }
273
+        // check method depends on operating system
274
+        if (!strncmp(PHP_OS, "WIN", 3)) {
275
+            // on Windows an appropriate COM or EXE file needs to exist
276
+            $exts = array(".exe", ".com");
277
+            $check_fn = "file_exists";
278
+        } else {
279
+            // anywhere else we look for an executable file of that name
280
+            $exts = array("");
281
+            $check_fn = "is_executable";
282
+        }
283
+        // Default check will be done with $path directories :
284
+        $dirs = explode(PATH_SEPARATOR, $path);
285
+        // WARNING : We have to check if open_basedir is enabled :
286
+        $obd = OC::$server->getIniWrapper()->getString('open_basedir');
287
+        if ($obd != "none") {
288
+            $obd_values = explode(PATH_SEPARATOR, $obd);
289
+            if (count($obd_values) > 0 and $obd_values[0]) {
290
+                // open_basedir is in effect !
291
+                // We need to check if the program is in one of these dirs :
292
+                $dirs = $obd_values;
293
+            }
294
+        }
295
+        foreach ($dirs as $dir) {
296
+            foreach ($exts as $ext) {
297
+                if ($check_fn("$dir/$name" . $ext))
298
+                    return true;
299
+            }
300
+        }
301
+        return false;
302
+    }
303
+
304
+    /**
305
+     * copy the contents of one stream to another
306
+     *
307
+     * @param resource $source
308
+     * @param resource $target
309
+     * @return array the number of bytes copied and result
310
+     */
311
+    public static function streamCopy($source, $target) {
312
+        if (!$source or !$target) {
313
+            return array(0, false);
314
+        }
315
+        $bufSize = 8192;
316
+        $result = true;
317
+        $count = 0;
318
+        while (!feof($source)) {
319
+            $buf = fread($source, $bufSize);
320
+            $bytesWritten = fwrite($target, $buf);
321
+            if ($bytesWritten !== false) {
322
+                $count += $bytesWritten;
323
+            }
324
+            // note: strlen is expensive so only use it when necessary,
325
+            // on the last block
326
+            if ($bytesWritten === false
327
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
328
+            ) {
329
+                // write error, could be disk full ?
330
+                $result = false;
331
+                break;
332
+            }
333
+        }
334
+        return array($count, $result);
335
+    }
336
+
337
+    /**
338
+     * Adds a suffix to the name in case the file exists
339
+     *
340
+     * @param string $path
341
+     * @param string $filename
342
+     * @return string
343
+     */
344
+    public static function buildNotExistingFileName($path, $filename) {
345
+        $view = \OC\Files\Filesystem::getView();
346
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
347
+    }
348
+
349
+    /**
350
+     * Adds a suffix to the name in case the file exists
351
+     *
352
+     * @param string $path
353
+     * @param string $filename
354
+     * @return string
355
+     */
356
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
357
+        if ($path === '/') {
358
+            $path = '';
359
+        }
360
+        if ($pos = strrpos($filename, '.')) {
361
+            $name = substr($filename, 0, $pos);
362
+            $ext = substr($filename, $pos);
363
+        } else {
364
+            $name = $filename;
365
+            $ext = '';
366
+        }
367
+
368
+        $newpath = $path . '/' . $filename;
369
+        if ($view->file_exists($newpath)) {
370
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
371
+                //Replace the last "(number)" with "(number+1)"
372
+                $last_match = count($matches[0]) - 1;
373
+                $counter = $matches[1][$last_match][0] + 1;
374
+                $offset = $matches[0][$last_match][1];
375
+                $match_length = strlen($matches[0][$last_match][0]);
376
+            } else {
377
+                $counter = 2;
378
+                $match_length = 0;
379
+                $offset = false;
380
+            }
381
+            do {
382
+                if ($offset) {
383
+                    //Replace the last "(number)" with "(number+1)"
384
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
385
+                } else {
386
+                    $newname = $name . ' (' . $counter . ')';
387
+                }
388
+                $newpath = $path . '/' . $newname . $ext;
389
+                $counter++;
390
+            } while ($view->file_exists($newpath));
391
+        }
392
+
393
+        return $newpath;
394
+    }
395
+
396
+    /**
397
+     * Checks if $sub is a subdirectory of $parent
398
+     *
399
+     * @param string $sub
400
+     * @param string $parent
401
+     * @return bool
402
+     */
403
+    public static function isSubDirectory($sub, $parent) {
404
+        $realpathSub = realpath($sub);
405
+        $realpathParent = realpath($parent);
406
+
407
+        // realpath() may return false in case the directory does not exist
408
+        // since we can not be sure how different PHP versions may behave here
409
+        // we do an additional check whether realpath returned false
410
+        if($realpathSub === false ||  $realpathParent === false) {
411
+            return false;
412
+        }
413
+
414
+        // Check whether $sub is a subdirectory of $parent
415
+        if (strpos($realpathSub, $realpathParent) === 0) {
416
+            return true;
417
+        }
418
+
419
+        return false;
420
+    }
421
+
422
+    /**
423
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
424
+     *
425
+     * @param array $input The array to work on
426
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
427
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
428
+     * @return array
429
+     *
430
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
431
+     * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
432
+     *
433
+     */
434
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
435
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
436
+        $ret = array();
437
+        foreach ($input as $k => $v) {
438
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
439
+        }
440
+        return $ret;
441
+    }
442
+
443
+    /**
444
+     * performs a search in a nested array
445
+     * @param array $haystack the array to be searched
446
+     * @param string $needle the search string
447
+     * @param string $index optional, only search this key name
448
+     * @return mixed the key of the matching field, otherwise false
449
+     *
450
+     * performs a search in a nested array
451
+     *
452
+     * taken from http://www.php.net/manual/en/function.array-search.php#97645
453
+     */
454
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
455
+        $aIt = new RecursiveArrayIterator($haystack);
456
+        $it = new RecursiveIteratorIterator($aIt);
457
+
458
+        while ($it->valid()) {
459
+            if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
460
+                return $aIt->key();
461
+            }
462
+
463
+            $it->next();
464
+        }
465
+
466
+        return false;
467
+    }
468
+
469
+    /**
470
+     * Shortens str to maxlen by replacing characters in the middle with '...', eg.
471
+     * ellipsis('a very long string with lots of useless info to make a better example', 14) becomes 'a very ...example'
472
+     *
473
+     * @param string $str the string
474
+     * @param string $maxlen the maximum length of the result
475
+     * @return string with at most maxlen characters
476
+     */
477
+    public static function ellipsis($str, $maxlen) {
478
+        if (strlen($str) > $maxlen) {
479
+            $characters = floor($maxlen / 2);
480
+            return substr($str, 0, $characters) . '...' . substr($str, -1 * $characters);
481
+        }
482
+        return $str;
483
+    }
484
+
485
+    /**
486
+     * calculates the maximum upload size respecting system settings, free space and user quota
487
+     *
488
+     * @param string $dir the current folder where the user currently operates
489
+     * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
490
+     * @return int number of bytes representing
491
+     */
492
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
493
+        if (is_null($freeSpace) || $freeSpace < 0){
494
+            $freeSpace = self::freeSpace($dir);
495
+        }
496
+        return min($freeSpace, self::uploadLimit());
497
+    }
498
+
499
+    /**
500
+     * Calculate free space left within user quota
501
+     *
502
+     * @param string $dir the current folder where the user currently operates
503
+     * @return int number of bytes representing
504
+     */
505
+    public static function freeSpace($dir) {
506
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
507
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
508
+            $freeSpace = max($freeSpace, 0);
509
+            return $freeSpace;
510
+        } else {
511
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
512
+        }
513
+    }
514
+
515
+    /**
516
+     * Calculate PHP upload limit
517
+     *
518
+     * @return int PHP upload file size limit
519
+     */
520
+    public static function uploadLimit() {
521
+        $ini = \OC::$server->getIniWrapper();
522
+        $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
523
+        $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
524
+        if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
525
+            return INF;
526
+        } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
527
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
528
+        } else {
529
+            return min($upload_max_filesize, $post_max_size);
530
+        }
531
+    }
532
+
533
+    /**
534
+     * Checks if a function is available
535
+     *
536
+     * @param string $function_name
537
+     * @return bool
538
+     */
539
+    public static function is_function_enabled($function_name) {
540
+        if (!function_exists($function_name)) {
541
+            return false;
542
+        }
543
+        $ini = \OC::$server->getIniWrapper();
544
+        $disabled = explode(',', $ini->get('disable_functions'));
545
+        $disabled = array_map('trim', $disabled);
546
+        if (in_array($function_name, $disabled)) {
547
+            return false;
548
+        }
549
+        $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
550
+        $disabled = array_map('trim', $disabled);
551
+        if (in_array($function_name, $disabled)) {
552
+            return false;
553
+        }
554
+        return true;
555
+    }
556
+
557
+    /**
558
+     * Try to find a program
559
+     * Note: currently windows is not supported
560
+     *
561
+     * @param string $program
562
+     * @return null|string
563
+     */
564
+    public static function findBinaryPath($program) {
565
+        $memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
566
+        if ($memcache->hasKey($program)) {
567
+            return $memcache->get($program);
568
+        }
569
+        $result = null;
570
+        if (!\OC_Util::runningOnWindows() && self::is_function_enabled('exec')) {
571
+            $exeSniffer = new ExecutableFinder();
572
+            // Returns null if nothing is found
573
+            $result = $exeSniffer->find($program);
574
+            if (empty($result)) {
575
+                $paths = getenv('PATH');
576
+                if (empty($paths)) {
577
+                    $paths = '/usr/local/bin /usr/bin /opt/bin /bin';
578
+                } else {
579
+                    $paths = str_replace(':',' ',getenv('PATH'));
580
+                }
581
+                $command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
582
+                exec($command, $output, $returnCode);
583
+                if (count($output) > 0) {
584
+                    $result = escapeshellcmd($output[0]);
585
+                }
586
+            }
587
+        }
588
+        // store the value for 5 minutes
589
+        $memcache->set($program, $result, 300);
590
+        return $result;
591
+    }
592
+
593
+    /**
594
+     * Calculate the disc space for the given path
595
+     *
596
+     * @param string $path
597
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
598
+     * @return array
599
+     * @throws \OCP\Files\NotFoundException
600
+     */
601
+    public static function getStorageInfo($path, $rootInfo = null) {
602
+        // return storage info without adding mount points
603
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
604
+
605
+        if (!$rootInfo) {
606
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, false);
607
+        }
608
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
609
+            throw new \OCP\Files\NotFoundException();
610
+        }
611
+        $used = $rootInfo->getSize();
612
+        if ($used < 0) {
613
+            $used = 0;
614
+        }
615
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
616
+        $storage = $rootInfo->getStorage();
617
+        $sourceStorage = $storage;
618
+        if ($storage->instanceOfStorage('\OC\Files\Storage\Shared')) {
619
+            $includeExtStorage = false;
620
+            $sourceStorage = $storage->getSourceStorage();
621
+        }
622
+        if ($includeExtStorage) {
623
+            $quota = OC_Util::getUserQuota(\OCP\User::getUser());
624
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
625
+                // always get free space / total space from root + mount points
626
+                return self::getGlobalStorageInfo();
627
+            }
628
+        }
629
+
630
+        // TODO: need a better way to get total space from storage
631
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
632
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
633
+            $quota = $sourceStorage->getQuota();
634
+        }
635
+        $free = $storage->free_space('');
636
+        if ($free >= 0) {
637
+            $total = $free + $used;
638
+        } else {
639
+            $total = $free; //either unknown or unlimited
640
+        }
641
+        if ($total > 0) {
642
+            if ($quota > 0 && $total > $quota) {
643
+                $total = $quota;
644
+            }
645
+            // prevent division by zero or error codes (negative values)
646
+            $relative = round(($used / $total) * 10000) / 100;
647
+        } else {
648
+            $relative = 0;
649
+        }
650
+
651
+        $ownerId = $storage->getOwner($path);
652
+        $ownerDisplayName = '';
653
+        $owner = \OC::$server->getUserManager()->get($ownerId);
654
+        if($owner) {
655
+            $ownerDisplayName = $owner->getDisplayName();
656
+        }
657
+
658
+        return [
659
+            'free' => $free,
660
+            'used' => $used,
661
+            'quota' => $quota,
662
+            'total' => $total,
663
+            'relative' => $relative,
664
+            'owner' => $ownerId,
665
+            'ownerDisplayName' => $ownerDisplayName,
666
+        ];
667
+    }
668
+
669
+    /**
670
+     * Get storage info including all mount points and quota
671
+     *
672
+     * @return array
673
+     */
674
+    private static function getGlobalStorageInfo() {
675
+        $quota = OC_Util::getUserQuota(\OCP\User::getUser());
676
+
677
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
678
+        $used = $rootInfo['size'];
679
+        if ($used < 0) {
680
+            $used = 0;
681
+        }
682
+
683
+        $total = $quota;
684
+        $free = $quota - $used;
685
+
686
+        if ($total > 0) {
687
+            if ($quota > 0 && $total > $quota) {
688
+                $total = $quota;
689
+            }
690
+            // prevent division by zero or error codes (negative values)
691
+            $relative = round(($used / $total) * 10000) / 100;
692
+        } else {
693
+            $relative = 0;
694
+        }
695
+
696
+        return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
697
+
698
+    }
699
+
700
+    /**
701
+     * Returns whether the config file is set manually to read-only
702
+     * @return bool
703
+     */
704
+    public static function isReadOnlyConfigEnabled() {
705
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
706
+    }
707 707
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 		} else {
66 66
 			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
67 67
 		}
68
-		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68
+		return $url.(($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
69 69
 	}
70 70
 
71 71
 	/**
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_preview', ['x' => 32, 'y' => 32, 'file' => $path]);
80 80
 	}
81 81
 
82
-	public static function publicPreviewIcon( $path, $token ) {
82
+	public static function publicPreviewIcon($path, $token) {
83 83
 		return \OC::$server->getURLGenerator()->linkToRoute('core_ajax_public_preview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
84 84
 	}
85 85
 
@@ -130,18 +130,18 @@  discard block
 block discarded – undo
130 130
 			return "?";
131 131
 		}
132 132
 		if ($bytes < 1024) {
133
-			return $bytes . "B";
133
+			return $bytes."B";
134 134
 		}
135 135
 		$bytes = round($bytes / 1024, 1);
136 136
 		if ($bytes < 1024) {
137
-			return $bytes . "K";
137
+			return $bytes."K";
138 138
 		}
139 139
 		$bytes = round($bytes / 1024, 1);
140 140
 		if ($bytes < 1024) {
141
-			return $bytes . "M";
141
+			return $bytes."M";
142 142
 		}
143 143
 		$bytes = round($bytes / 1024, 1);
144
-		return $bytes . "G";
144
+		return $bytes."G";
145 145
 	}
146 146
 
147 147
 	/**
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
 		}
295 295
 		foreach ($dirs as $dir) {
296 296
 			foreach ($exts as $ext) {
297
-				if ($check_fn("$dir/$name" . $ext))
297
+				if ($check_fn("$dir/$name".$ext))
298 298
 					return true;
299 299
 			}
300 300
 		}
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 			$ext = '';
366 366
 		}
367 367
 
368
-		$newpath = $path . '/' . $filename;
368
+		$newpath = $path.'/'.$filename;
369 369
 		if ($view->file_exists($newpath)) {
370 370
 			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
371 371
 				//Replace the last "(number)" with "(number+1)"
@@ -381,11 +381,11 @@  discard block
 block discarded – undo
381 381
 			do {
382 382
 				if ($offset) {
383 383
 					//Replace the last "(number)" with "(number+1)"
384
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
384
+					$newname = substr_replace($name, '('.$counter.')', $offset, $match_length);
385 385
 				} else {
386
-					$newname = $name . ' (' . $counter . ')';
386
+					$newname = $name.' ('.$counter.')';
387 387
 				}
388
-				$newpath = $path . '/' . $newname . $ext;
388
+				$newpath = $path.'/'.$newname.$ext;
389 389
 				$counter++;
390 390
 			} while ($view->file_exists($newpath));
391 391
 		}
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 		// realpath() may return false in case the directory does not exist
408 408
 		// since we can not be sure how different PHP versions may behave here
409 409
 		// we do an additional check whether realpath returned false
410
-		if($realpathSub === false ||  $realpathParent === false) {
410
+		if ($realpathSub === false || $realpathParent === false) {
411 411
 			return false;
412 412
 		}
413 413
 
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
 	public static function ellipsis($str, $maxlen) {
478 478
 		if (strlen($str) > $maxlen) {
479 479
 			$characters = floor($maxlen / 2);
480
-			return substr($str, 0, $characters) . '...' . substr($str, -1 * $characters);
480
+			return substr($str, 0, $characters).'...'.substr($str, -1 * $characters);
481 481
 		}
482 482
 		return $str;
483 483
 	}
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 	 * @return int number of bytes representing
491 491
 	 */
492 492
 	public static function maxUploadFilesize($dir, $freeSpace = null) {
493
-		if (is_null($freeSpace) || $freeSpace < 0){
493
+		if (is_null($freeSpace) || $freeSpace < 0) {
494 494
 			$freeSpace = self::freeSpace($dir);
495 495
 		}
496 496
 		return min($freeSpace, self::uploadLimit());
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 			$freeSpace = max($freeSpace, 0);
509 509
 			return $freeSpace;
510 510
 		} else {
511
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
511
+			return (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
512 512
 		}
513 513
 	}
514 514
 
@@ -521,9 +521,9 @@  discard block
 block discarded – undo
521 521
 		$ini = \OC::$server->getIniWrapper();
522 522
 		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
523 523
 		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
524
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
524
+		if ((int) $upload_max_filesize === 0 and (int) $post_max_size === 0) {
525 525
 			return INF;
526
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
526
+		} elseif ((int) $upload_max_filesize === 0 or (int) $post_max_size === 0) {
527 527
 			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
528 528
 		} else {
529 529
 			return min($upload_max_filesize, $post_max_size);
@@ -576,9 +576,9 @@  discard block
 block discarded – undo
576 576
 				if (empty($paths)) {
577 577
 					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
578 578
 				} else {
579
-					$paths = str_replace(':',' ',getenv('PATH'));
579
+					$paths = str_replace(':', ' ', getenv('PATH'));
580 580
 				}
581
-				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
581
+				$command = 'find '.$paths.' -name '.escapeshellarg($program).' 2> /dev/null';
582 582
 				exec($command, $output, $returnCode);
583 583
 				if (count($output) > 0) {
584 584
 					$result = escapeshellcmd($output[0]);
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
 		$ownerId = $storage->getOwner($path);
652 652
 		$ownerDisplayName = '';
653 653
 		$owner = \OC::$server->getUserManager()->get($ownerId);
654
-		if($owner) {
654
+		if ($owner) {
655 655
 			$ownerDisplayName = $owner->getDisplayName();
656 656
 		}
657 657
 
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -271,8 +271,9 @@
 block discarded – undo
271 271
 		}
272 272
 		foreach ($dirs as $dir) {
273 273
 			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
275
-					return true;
274
+				if ($check_fn("$dir/$name" . $ext)) {
275
+									return true;
276
+				}
276 277
 			}
277 278
 		}
278 279
 		return false;
Please login to merge, or discard this patch.
lib/private/l10n/factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -278,6 +278,11 @@
 block discarded – undo
278 278
 	 */
279 279
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
280 280
 	// FIXME This is also the reason, why it is not in the public interface
281
+
282
+	/**
283
+	 * @param string|boolean $app
284
+	 * @param string|null $lang
285
+	 */
281 286
 	public function getL10nFilesForApp($app, $lang) {
282 287
 		$languageFiles = [];
283 288
 
Please login to merge, or discard this patch.
Indentation   +351 added lines, -351 removed lines patch added patch discarded remove patch
@@ -37,355 +37,355 @@
 block discarded – undo
37 37
  */
38 38
 class Factory implements IFactory {
39 39
 
40
-	/** @var string */
41
-	protected $requestLanguage = '';
42
-
43
-	/**
44
-	 * cached instances
45
-	 * @var array Structure: Lang => App => \OCP\IL10N
46
-	 */
47
-	protected $instances = [];
48
-
49
-	/**
50
-	 * @var array Structure: App => string[]
51
-	 */
52
-	protected $availableLanguages = [];
53
-
54
-	/**
55
-	 * @var array Structure: string => callable
56
-	 */
57
-	protected $pluralFunctions = [];
58
-
59
-	/** @var IConfig */
60
-	protected $config;
61
-
62
-	/** @var IRequest */
63
-	protected $request;
64
-
65
-	/** @var IUserSession */
66
-	protected $userSession;
67
-
68
-	/** @var string */
69
-	protected $serverRoot;
70
-
71
-	/**
72
-	 * @param IConfig $config
73
-	 * @param IRequest $request
74
-	 * @param IUserSession $userSession
75
-	 * @param string $serverRoot
76
-	 */
77
-	public function __construct(IConfig $config,
78
-								IRequest $request,
79
-								IUserSession $userSession,
80
-								$serverRoot) {
81
-		$this->config = $config;
82
-		$this->request = $request;
83
-		$this->userSession = $userSession;
84
-		$this->serverRoot = $serverRoot;
85
-	}
86
-
87
-	/**
88
-	 * Get a language instance
89
-	 *
90
-	 * @param string $app
91
-	 * @param string|null $lang
92
-	 * @return \OCP\IL10N
93
-	 */
94
-	public function get($app, $lang = null) {
95
-		$app = \OC_App::cleanAppId($app);
96
-		if ($lang !== null) {
97
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
98
-		}
99
-		if ($lang === null || !$this->languageExists($app, $lang)) {
100
-			$lang = $this->findLanguage($app);
101
-		}
102
-
103
-		if (!isset($this->instances[$lang][$app])) {
104
-			$this->instances[$lang][$app] = new L10N(
105
-				$this, $app, $lang,
106
-				$this->getL10nFilesForApp($app, $lang)
107
-			);
108
-		}
109
-
110
-		return $this->instances[$lang][$app];
111
-	}
112
-
113
-	/**
114
-	 * Find the best language
115
-	 *
116
-	 * @param string|null $app App id or null for core
117
-	 * @return string language If nothing works it returns 'en'
118
-	 */
119
-	public function findLanguage($app = null) {
120
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
121
-			return $this->requestLanguage;
122
-		}
123
-
124
-		/**
125
-		 * At this point ownCloud might not yet be installed and thus the lookup
126
-		 * in the preferences table might fail. For this reason we need to check
127
-		 * whether the instance has already been installed
128
-		 *
129
-		 * @link https://github.com/owncloud/core/issues/21955
130
-		 */
131
-		if($this->config->getSystemValue('installed', false)) {
132
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
133
-			if(!is_null($userId)) {
134
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
135
-			} else {
136
-				$userLang = null;
137
-			}
138
-		} else {
139
-			$userId = null;
140
-			$userLang = null;
141
-		}
142
-
143
-		if ($userLang) {
144
-			$this->requestLanguage = $userLang;
145
-			if ($this->languageExists($app, $userLang)) {
146
-				return $userLang;
147
-			}
148
-		}
149
-
150
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
151
-
152
-		if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
153
-			return $defaultLanguage;
154
-		}
155
-
156
-		$lang = $this->setLanguageFromRequest($app);
157
-		if ($userId !== null && $app === null && !$userLang) {
158
-			$this->config->setUserValue($userId, 'core', 'lang', $lang);
159
-		}
160
-
161
-		return $lang;
162
-	}
163
-
164
-	/**
165
-	 * Find all available languages for an app
166
-	 *
167
-	 * @param string|null $app App id or null for core
168
-	 * @return array an array of available languages
169
-	 */
170
-	public function findAvailableLanguages($app = null) {
171
-		$key = $app;
172
-		if ($key === null) {
173
-			$key = 'null';
174
-		}
175
-
176
-		// also works with null as key
177
-		if (!empty($this->availableLanguages[$key])) {
178
-			return $this->availableLanguages[$key];
179
-		}
180
-
181
-		$available = ['en']; //english is always available
182
-		$dir = $this->findL10nDir($app);
183
-		if (is_dir($dir)) {
184
-			$files = scandir($dir);
185
-			if ($files !== false) {
186
-				foreach ($files as $file) {
187
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
188
-						$available[] = substr($file, 0, -5);
189
-					}
190
-				}
191
-			}
192
-		}
193
-
194
-		// merge with translations from theme
195
-		$theme = $this->config->getSystemValue('theme');
196
-		if (!empty($theme)) {
197
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
198
-
199
-			if (is_dir($themeDir)) {
200
-				$files = scandir($themeDir);
201
-				if ($files !== false) {
202
-					foreach ($files as $file) {
203
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
204
-							$available[] = substr($file, 0, -5);
205
-						}
206
-					}
207
-				}
208
-			}
209
-		}
210
-
211
-		$this->availableLanguages[$key] = $available;
212
-		return $available;
213
-	}
214
-
215
-	/**
216
-	 * @param string|null $app App id or null for core
217
-	 * @param string $lang
218
-	 * @return bool
219
-	 */
220
-	public function languageExists($app, $lang) {
221
-		if ($lang === 'en') {//english is always available
222
-			return true;
223
-		}
224
-
225
-		$languages = $this->findAvailableLanguages($app);
226
-		return array_search($lang, $languages) !== false;
227
-	}
228
-
229
-	/**
230
-	 * @param string|null $app App id or null for core
231
-	 * @return string
232
-	 */
233
-	public function setLanguageFromRequest($app = null) {
234
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
235
-		if ($header) {
236
-			$available = $this->findAvailableLanguages($app);
237
-
238
-			// E.g. make sure that 'de' is before 'de_DE'.
239
-			sort($available);
240
-
241
-			$preferences = preg_split('/,\s*/', strtolower($header));
242
-			foreach ($preferences as $preference) {
243
-				list($preferred_language) = explode(';', $preference);
244
-				$preferred_language = str_replace('-', '_', $preferred_language);
245
-
246
-				foreach ($available as $available_language) {
247
-					if ($preferred_language === strtolower($available_language)) {
248
-						if ($app === null && !$this->requestLanguage) {
249
-							$this->requestLanguage = $available_language;
250
-						}
251
-						return $available_language;
252
-					}
253
-				}
254
-
255
-				// Fallback from de_De to de
256
-				foreach ($available as $available_language) {
257
-					if (substr($preferred_language, 0, 2) === $available_language) {
258
-						if ($app === null && !$this->requestLanguage) {
259
-							$this->requestLanguage = $available_language;
260
-						}
261
-						return $available_language;
262
-					}
263
-				}
264
-			}
265
-		}
266
-
267
-		if ($app === null && !$this->requestLanguage) {
268
-			$this->requestLanguage = 'en';
269
-		}
270
-		return 'en'; // Last try: English
271
-	}
272
-
273
-	/**
274
-	 * Get a list of language files that should be loaded
275
-	 *
276
-	 * @param string $app
277
-	 * @param string $lang
278
-	 * @return string[]
279
-	 */
280
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
281
-	// FIXME This is also the reason, why it is not in the public interface
282
-	public function getL10nFilesForApp($app, $lang) {
283
-		$languageFiles = [];
284
-
285
-		$i18nDir = $this->findL10nDir($app);
286
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
287
-
288
-		if ((\OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
289
-				|| \OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
290
-				|| \OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
291
-				|| \OC_Helper::isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
292
-			)
293
-			&& file_exists($transFile)) {
294
-			// load the translations file
295
-			$languageFiles[] = $transFile;
296
-		}
297
-
298
-		// merge with translations from theme
299
-		$theme = $this->config->getSystemValue('theme');
300
-		if (!empty($theme)) {
301
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
302
-			if (file_exists($transFile)) {
303
-				$languageFiles[] = $transFile;
304
-			}
305
-		}
306
-
307
-		return $languageFiles;
308
-	}
309
-
310
-	/**
311
-	 * find the l10n directory
312
-	 *
313
-	 * @param string $app App id or empty string for core
314
-	 * @return string directory
315
-	 */
316
-	protected function findL10nDir($app = null) {
317
-		if (in_array($app, ['core', 'lib', 'settings'])) {
318
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
319
-				return $this->serverRoot . '/' . $app . '/l10n/';
320
-			}
321
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
322
-			// Check if the app is in the app folder
323
-			return \OC_App::getAppPath($app) . '/l10n/';
324
-		}
325
-		return $this->serverRoot . '/core/l10n/';
326
-	}
327
-
328
-
329
-	/**
330
-	 * Creates a function from the plural string
331
-	 *
332
-	 * Parts of the code is copied from Habari:
333
-	 * https://github.com/habari/system/blob/master/classes/locale.php
334
-	 * @param string $string
335
-	 * @return string
336
-	 */
337
-	public function createPluralFunction($string) {
338
-		if (isset($this->pluralFunctions[$string])) {
339
-			return $this->pluralFunctions[$string];
340
-		}
341
-
342
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
343
-			// sanitize
344
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
345
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
346
-
347
-			$body = str_replace(
348
-				array( 'plural', 'n', '$n$plurals', ),
349
-				array( '$plural', '$n', '$nplurals', ),
350
-				'nplurals='. $nplurals . '; plural=' . $plural
351
-			);
352
-
353
-			// add parents
354
-			// important since PHP's ternary evaluates from left to right
355
-			$body .= ';';
356
-			$res = '';
357
-			$p = 0;
358
-			for($i = 0; $i < strlen($body); $i++) {
359
-				$ch = $body[$i];
360
-				switch ( $ch ) {
361
-					case '?':
362
-						$res .= ' ? (';
363
-						$p++;
364
-						break;
365
-					case ':':
366
-						$res .= ') : (';
367
-						break;
368
-					case ';':
369
-						$res .= str_repeat( ')', $p ) . ';';
370
-						$p = 0;
371
-						break;
372
-					default:
373
-						$res .= $ch;
374
-				}
375
-			}
376
-
377
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
378
-			$function = create_function('$n', $body);
379
-			$this->pluralFunctions[$string] = $function;
380
-			return $function;
381
-		} else {
382
-			// default: one plural form for all cases but n==1 (english)
383
-			$function = create_function(
384
-				'$n',
385
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
386
-			);
387
-			$this->pluralFunctions[$string] = $function;
388
-			return $function;
389
-		}
390
-	}
40
+    /** @var string */
41
+    protected $requestLanguage = '';
42
+
43
+    /**
44
+     * cached instances
45
+     * @var array Structure: Lang => App => \OCP\IL10N
46
+     */
47
+    protected $instances = [];
48
+
49
+    /**
50
+     * @var array Structure: App => string[]
51
+     */
52
+    protected $availableLanguages = [];
53
+
54
+    /**
55
+     * @var array Structure: string => callable
56
+     */
57
+    protected $pluralFunctions = [];
58
+
59
+    /** @var IConfig */
60
+    protected $config;
61
+
62
+    /** @var IRequest */
63
+    protected $request;
64
+
65
+    /** @var IUserSession */
66
+    protected $userSession;
67
+
68
+    /** @var string */
69
+    protected $serverRoot;
70
+
71
+    /**
72
+     * @param IConfig $config
73
+     * @param IRequest $request
74
+     * @param IUserSession $userSession
75
+     * @param string $serverRoot
76
+     */
77
+    public function __construct(IConfig $config,
78
+                                IRequest $request,
79
+                                IUserSession $userSession,
80
+                                $serverRoot) {
81
+        $this->config = $config;
82
+        $this->request = $request;
83
+        $this->userSession = $userSession;
84
+        $this->serverRoot = $serverRoot;
85
+    }
86
+
87
+    /**
88
+     * Get a language instance
89
+     *
90
+     * @param string $app
91
+     * @param string|null $lang
92
+     * @return \OCP\IL10N
93
+     */
94
+    public function get($app, $lang = null) {
95
+        $app = \OC_App::cleanAppId($app);
96
+        if ($lang !== null) {
97
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
98
+        }
99
+        if ($lang === null || !$this->languageExists($app, $lang)) {
100
+            $lang = $this->findLanguage($app);
101
+        }
102
+
103
+        if (!isset($this->instances[$lang][$app])) {
104
+            $this->instances[$lang][$app] = new L10N(
105
+                $this, $app, $lang,
106
+                $this->getL10nFilesForApp($app, $lang)
107
+            );
108
+        }
109
+
110
+        return $this->instances[$lang][$app];
111
+    }
112
+
113
+    /**
114
+     * Find the best language
115
+     *
116
+     * @param string|null $app App id or null for core
117
+     * @return string language If nothing works it returns 'en'
118
+     */
119
+    public function findLanguage($app = null) {
120
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
121
+            return $this->requestLanguage;
122
+        }
123
+
124
+        /**
125
+         * At this point ownCloud might not yet be installed and thus the lookup
126
+         * in the preferences table might fail. For this reason we need to check
127
+         * whether the instance has already been installed
128
+         *
129
+         * @link https://github.com/owncloud/core/issues/21955
130
+         */
131
+        if($this->config->getSystemValue('installed', false)) {
132
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
133
+            if(!is_null($userId)) {
134
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
135
+            } else {
136
+                $userLang = null;
137
+            }
138
+        } else {
139
+            $userId = null;
140
+            $userLang = null;
141
+        }
142
+
143
+        if ($userLang) {
144
+            $this->requestLanguage = $userLang;
145
+            if ($this->languageExists($app, $userLang)) {
146
+                return $userLang;
147
+            }
148
+        }
149
+
150
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
151
+
152
+        if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
153
+            return $defaultLanguage;
154
+        }
155
+
156
+        $lang = $this->setLanguageFromRequest($app);
157
+        if ($userId !== null && $app === null && !$userLang) {
158
+            $this->config->setUserValue($userId, 'core', 'lang', $lang);
159
+        }
160
+
161
+        return $lang;
162
+    }
163
+
164
+    /**
165
+     * Find all available languages for an app
166
+     *
167
+     * @param string|null $app App id or null for core
168
+     * @return array an array of available languages
169
+     */
170
+    public function findAvailableLanguages($app = null) {
171
+        $key = $app;
172
+        if ($key === null) {
173
+            $key = 'null';
174
+        }
175
+
176
+        // also works with null as key
177
+        if (!empty($this->availableLanguages[$key])) {
178
+            return $this->availableLanguages[$key];
179
+        }
180
+
181
+        $available = ['en']; //english is always available
182
+        $dir = $this->findL10nDir($app);
183
+        if (is_dir($dir)) {
184
+            $files = scandir($dir);
185
+            if ($files !== false) {
186
+                foreach ($files as $file) {
187
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
188
+                        $available[] = substr($file, 0, -5);
189
+                    }
190
+                }
191
+            }
192
+        }
193
+
194
+        // merge with translations from theme
195
+        $theme = $this->config->getSystemValue('theme');
196
+        if (!empty($theme)) {
197
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
198
+
199
+            if (is_dir($themeDir)) {
200
+                $files = scandir($themeDir);
201
+                if ($files !== false) {
202
+                    foreach ($files as $file) {
203
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
204
+                            $available[] = substr($file, 0, -5);
205
+                        }
206
+                    }
207
+                }
208
+            }
209
+        }
210
+
211
+        $this->availableLanguages[$key] = $available;
212
+        return $available;
213
+    }
214
+
215
+    /**
216
+     * @param string|null $app App id or null for core
217
+     * @param string $lang
218
+     * @return bool
219
+     */
220
+    public function languageExists($app, $lang) {
221
+        if ($lang === 'en') {//english is always available
222
+            return true;
223
+        }
224
+
225
+        $languages = $this->findAvailableLanguages($app);
226
+        return array_search($lang, $languages) !== false;
227
+    }
228
+
229
+    /**
230
+     * @param string|null $app App id or null for core
231
+     * @return string
232
+     */
233
+    public function setLanguageFromRequest($app = null) {
234
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
235
+        if ($header) {
236
+            $available = $this->findAvailableLanguages($app);
237
+
238
+            // E.g. make sure that 'de' is before 'de_DE'.
239
+            sort($available);
240
+
241
+            $preferences = preg_split('/,\s*/', strtolower($header));
242
+            foreach ($preferences as $preference) {
243
+                list($preferred_language) = explode(';', $preference);
244
+                $preferred_language = str_replace('-', '_', $preferred_language);
245
+
246
+                foreach ($available as $available_language) {
247
+                    if ($preferred_language === strtolower($available_language)) {
248
+                        if ($app === null && !$this->requestLanguage) {
249
+                            $this->requestLanguage = $available_language;
250
+                        }
251
+                        return $available_language;
252
+                    }
253
+                }
254
+
255
+                // Fallback from de_De to de
256
+                foreach ($available as $available_language) {
257
+                    if (substr($preferred_language, 0, 2) === $available_language) {
258
+                        if ($app === null && !$this->requestLanguage) {
259
+                            $this->requestLanguage = $available_language;
260
+                        }
261
+                        return $available_language;
262
+                    }
263
+                }
264
+            }
265
+        }
266
+
267
+        if ($app === null && !$this->requestLanguage) {
268
+            $this->requestLanguage = 'en';
269
+        }
270
+        return 'en'; // Last try: English
271
+    }
272
+
273
+    /**
274
+     * Get a list of language files that should be loaded
275
+     *
276
+     * @param string $app
277
+     * @param string $lang
278
+     * @return string[]
279
+     */
280
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
281
+    // FIXME This is also the reason, why it is not in the public interface
282
+    public function getL10nFilesForApp($app, $lang) {
283
+        $languageFiles = [];
284
+
285
+        $i18nDir = $this->findL10nDir($app);
286
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
287
+
288
+        if ((\OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
289
+                || \OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
290
+                || \OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
291
+                || \OC_Helper::isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
292
+            )
293
+            && file_exists($transFile)) {
294
+            // load the translations file
295
+            $languageFiles[] = $transFile;
296
+        }
297
+
298
+        // merge with translations from theme
299
+        $theme = $this->config->getSystemValue('theme');
300
+        if (!empty($theme)) {
301
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
302
+            if (file_exists($transFile)) {
303
+                $languageFiles[] = $transFile;
304
+            }
305
+        }
306
+
307
+        return $languageFiles;
308
+    }
309
+
310
+    /**
311
+     * find the l10n directory
312
+     *
313
+     * @param string $app App id or empty string for core
314
+     * @return string directory
315
+     */
316
+    protected function findL10nDir($app = null) {
317
+        if (in_array($app, ['core', 'lib', 'settings'])) {
318
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
319
+                return $this->serverRoot . '/' . $app . '/l10n/';
320
+            }
321
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
322
+            // Check if the app is in the app folder
323
+            return \OC_App::getAppPath($app) . '/l10n/';
324
+        }
325
+        return $this->serverRoot . '/core/l10n/';
326
+    }
327
+
328
+
329
+    /**
330
+     * Creates a function from the plural string
331
+     *
332
+     * Parts of the code is copied from Habari:
333
+     * https://github.com/habari/system/blob/master/classes/locale.php
334
+     * @param string $string
335
+     * @return string
336
+     */
337
+    public function createPluralFunction($string) {
338
+        if (isset($this->pluralFunctions[$string])) {
339
+            return $this->pluralFunctions[$string];
340
+        }
341
+
342
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
343
+            // sanitize
344
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
345
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
346
+
347
+            $body = str_replace(
348
+                array( 'plural', 'n', '$n$plurals', ),
349
+                array( '$plural', '$n', '$nplurals', ),
350
+                'nplurals='. $nplurals . '; plural=' . $plural
351
+            );
352
+
353
+            // add parents
354
+            // important since PHP's ternary evaluates from left to right
355
+            $body .= ';';
356
+            $res = '';
357
+            $p = 0;
358
+            for($i = 0; $i < strlen($body); $i++) {
359
+                $ch = $body[$i];
360
+                switch ( $ch ) {
361
+                    case '?':
362
+                        $res .= ' ? (';
363
+                        $p++;
364
+                        break;
365
+                    case ':':
366
+                        $res .= ') : (';
367
+                        break;
368
+                    case ';':
369
+                        $res .= str_repeat( ')', $p ) . ';';
370
+                        $p = 0;
371
+                        break;
372
+                    default:
373
+                        $res .= $ch;
374
+                }
375
+            }
376
+
377
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
378
+            $function = create_function('$n', $body);
379
+            $this->pluralFunctions[$string] = $function;
380
+            return $function;
381
+        } else {
382
+            // default: one plural form for all cases but n==1 (english)
383
+            $function = create_function(
384
+                '$n',
385
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
386
+            );
387
+            $this->pluralFunctions[$string] = $function;
388
+            return $function;
389
+        }
390
+    }
391 391
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -128,9 +128,9 @@  discard block
 block discarded – undo
128 128
 		 *
129 129
 		 * @link https://github.com/owncloud/core/issues/21955
130 130
 		 */
131
-		if($this->config->getSystemValue('installed', false)) {
132
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
133
-			if(!is_null($userId)) {
131
+		if ($this->config->getSystemValue('installed', false)) {
132
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
133
+			if (!is_null($userId)) {
134 134
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
135 135
 			} else {
136 136
 				$userLang = null;
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 		// merge with translations from theme
195 195
 		$theme = $this->config->getSystemValue('theme');
196 196
 		if (!empty($theme)) {
197
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
197
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
198 198
 
199 199
 			if (is_dir($themeDir)) {
200 200
 				$files = scandir($themeDir);
@@ -283,12 +283,12 @@  discard block
 block discarded – undo
283 283
 		$languageFiles = [];
284 284
 
285 285
 		$i18nDir = $this->findL10nDir($app);
286
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
286
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
287 287
 
288
-		if ((\OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
289
-				|| \OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
290
-				|| \OC_Helper::isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
291
-				|| \OC_Helper::isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
288
+		if ((\OC_Helper::isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
289
+				|| \OC_Helper::isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
290
+				|| \OC_Helper::isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
291
+				|| \OC_Helper::isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
292 292
 			)
293 293
 			&& file_exists($transFile)) {
294 294
 			// load the translations file
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 		// merge with translations from theme
299 299
 		$theme = $this->config->getSystemValue('theme');
300 300
 		if (!empty($theme)) {
301
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
301
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
302 302
 			if (file_exists($transFile)) {
303 303
 				$languageFiles[] = $transFile;
304 304
 			}
@@ -315,14 +315,14 @@  discard block
 block discarded – undo
315 315
 	 */
316 316
 	protected function findL10nDir($app = null) {
317 317
 		if (in_array($app, ['core', 'lib', 'settings'])) {
318
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
319
-				return $this->serverRoot . '/' . $app . '/l10n/';
318
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
319
+				return $this->serverRoot.'/'.$app.'/l10n/';
320 320
 			}
321 321
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
322 322
 			// Check if the app is in the app folder
323
-			return \OC_App::getAppPath($app) . '/l10n/';
323
+			return \OC_App::getAppPath($app).'/l10n/';
324 324
 		}
325
-		return $this->serverRoot . '/core/l10n/';
325
+		return $this->serverRoot.'/core/l10n/';
326 326
 	}
327 327
 
328 328
 
@@ -339,15 +339,15 @@  discard block
 block discarded – undo
339 339
 			return $this->pluralFunctions[$string];
340 340
 		}
341 341
 
342
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
342
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
343 343
 			// sanitize
344
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
345
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
344
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
345
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
346 346
 
347 347
 			$body = str_replace(
348
-				array( 'plural', 'n', '$n$plurals', ),
349
-				array( '$plural', '$n', '$nplurals', ),
350
-				'nplurals='. $nplurals . '; plural=' . $plural
348
+				array('plural', 'n', '$n$plurals',),
349
+				array('$plural', '$n', '$nplurals',),
350
+				'nplurals='.$nplurals.'; plural='.$plural
351 351
 			);
352 352
 
353 353
 			// add parents
@@ -355,9 +355,9 @@  discard block
 block discarded – undo
355 355
 			$body .= ';';
356 356
 			$res = '';
357 357
 			$p = 0;
358
-			for($i = 0; $i < strlen($body); $i++) {
358
+			for ($i = 0; $i < strlen($body); $i++) {
359 359
 				$ch = $body[$i];
360
-				switch ( $ch ) {
360
+				switch ($ch) {
361 361
 					case '?':
362 362
 						$res .= ' ? (';
363 363
 						$p++;
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 						$res .= ') : (';
367 367
 						break;
368 368
 					case ';':
369
-						$res .= str_repeat( ')', $p ) . ';';
369
+						$res .= str_repeat(')', $p).';';
370 370
 						$p = 0;
371 371
 						break;
372 372
 					default:
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 				}
375 375
 			}
376 376
 
377
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
377
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
378 378
 			$function = create_function('$n', $body);
379 379
 			$this->pluralFunctions[$string] = $function;
380 380
 			return $function;
Please login to merge, or discard this patch.
lib/private/l10n/l10n.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@
 block discarded – undo
176 176
 	 * Returns an associative array with all translations
177 177
 	 *
178 178
 	 * Called by \OC_L10N_String
179
-	 * @return array
179
+	 * @return string[]
180 180
 	 */
181 181
 	public function getTranslations() {
182 182
 		return $this->translations;
Please login to merge, or discard this patch.
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -28,190 +28,190 @@
 block discarded – undo
28 28
 
29 29
 class L10N implements IL10N {
30 30
 
31
-	/** @var IFactory */
32
-	protected $factory;
33
-
34
-	/** @var string App of this object */
35
-	protected $app;
36
-
37
-	/** @var string Language of this object */
38
-	protected $lang;
39
-
40
-	/** @var string Plural forms (string) */
41
-	private $pluralFormString = 'nplurals=2; plural=(n != 1);';
42
-
43
-	/** @var string Plural forms (function) */
44
-	private $pluralFormFunction = null;
45
-
46
-	/** @var string[] */
47
-	private $translations = [];
48
-
49
-	/**
50
-	 * @param IFactory $factory
51
-	 * @param string $app
52
-	 * @param string $lang
53
-	 * @param array $files
54
-	 */
55
-	public function __construct(IFactory $factory, $app, $lang, array $files) {
56
-		$this->factory = $factory;
57
-		$this->app = $app;
58
-		$this->lang = $lang;
59
-
60
-		$this->translations = [];
61
-		foreach ($files as $languageFile) {
62
-			$this->load($languageFile);
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * The code (en, de, ...) of the language that is used for this instance
68
-	 *
69
-	 * @return string language
70
-	 */
71
-	public function getLanguageCode() {
72
-		return $this->lang;
73
-	}
74
-
75
-	/**
76
-	 * Translating
77
-	 * @param string $text The text we need a translation for
78
-	 * @param array $parameters default:array() Parameters for sprintf
79
-	 * @return string Translation or the same text
80
-	 *
81
-	 * Returns the translation. If no translation is found, $text will be
82
-	 * returned.
83
-	 */
84
-	public function t($text, $parameters = array()) {
85
-		return (string) new \OC_L10N_String($this, $text, $parameters);
86
-	}
87
-
88
-	/**
89
-	 * Translating
90
-	 * @param string $text_singular the string to translate for exactly one object
91
-	 * @param string $text_plural the string to translate for n objects
92
-	 * @param integer $count Number of objects
93
-	 * @param array $parameters default:array() Parameters for sprintf
94
-	 * @return string Translation or the same text
95
-	 *
96
-	 * Returns the translation. If no translation is found, $text will be
97
-	 * returned. %n will be replaced with the number of objects.
98
-	 *
99
-	 * The correct plural is determined by the plural_forms-function
100
-	 * provided by the po file.
101
-	 *
102
-	 */
103
-	public function n($text_singular, $text_plural, $count, $parameters = array()) {
104
-		$identifier = "_${text_singular}_::_${text_plural}_";
105
-		if (isset($this->translations[$identifier])) {
106
-			return (string) new \OC_L10N_String($this, $identifier, $parameters, $count);
107
-		} else {
108
-			if ($count === 1) {
109
-				return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count);
110
-			} else {
111
-				return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count);
112
-			}
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * Localization
118
-	 * @param string $type Type of localization
119
-	 * @param \DateTime|int|string $data parameters for this localization
120
-	 * @param array $options
121
-	 * @return string|int|false
122
-	 *
123
-	 * Returns the localized data.
124
-	 *
125
-	 * Implemented types:
126
-	 *  - date
127
-	 *    - Creates a date
128
-	 *    - params: timestamp (int/string)
129
-	 *  - datetime
130
-	 *    - Creates date and time
131
-	 *    - params: timestamp (int/string)
132
-	 *  - time
133
-	 *    - Creates a time
134
-	 *    - params: timestamp (int/string)
135
-	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
136
-	 *  - jsdate: Returns the short JS date format
137
-	 */
138
-	public function l($type, $data = null, $options = array()) {
139
-		// Use the language of the instance
140
-		$locale = $this->getLanguageCode();
141
-		if ($locale === 'sr@latin') {
142
-			$locale = 'sr_latn';
143
-		}
144
-
145
-		if ($type === 'firstday') {
146
-			return (int) Calendar::getFirstWeekday($locale);
147
-		}
148
-		if ($type === 'jsdate') {
149
-			return (string) Calendar::getDateFormat('short', $locale);
150
-		}
151
-
152
-		$value = new \DateTime();
153
-		if ($data instanceof \DateTime) {
154
-			$value = $data;
155
-		} else if (is_string($data) && !is_numeric($data)) {
156
-			$data = strtotime($data);
157
-			$value->setTimestamp($data);
158
-		} else if ($data !== null) {
159
-			$value->setTimestamp($data);
160
-		}
161
-
162
-		$options = array_merge(array('width' => 'long'), $options);
163
-		$width = $options['width'];
164
-		switch ($type) {
165
-			case 'date':
166
-				return (string) Calendar::formatDate($value, $width, $locale);
167
-			case 'datetime':
168
-				return (string) Calendar::formatDatetime($value, $width, $locale);
169
-			case 'time':
170
-				return (string) Calendar::formatTime($value, $width, $locale);
171
-			default:
172
-				return false;
173
-		}
174
-	}
175
-
176
-	/**
177
-	 * Returns an associative array with all translations
178
-	 *
179
-	 * Called by \OC_L10N_String
180
-	 * @return array
181
-	 */
182
-	public function getTranslations() {
183
-		return $this->translations;
184
-	}
185
-
186
-	/**
187
-	 * Returnsed function accepts the argument $n
188
-	 *
189
-	 * Called by \OC_L10N_String
190
-	 * @return string the plural form function
191
-	 */
192
-	public function getPluralFormFunction() {
193
-		if (is_null($this->pluralFormFunction)) {
194
-			$this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString);
195
-		}
196
-		return $this->pluralFormFunction;
197
-	}
198
-
199
-	/**
200
-	 * @param $translationFile
201
-	 * @return bool
202
-	 */
203
-	protected function load($translationFile) {
204
-		$json = json_decode(file_get_contents($translationFile), true);
205
-		if (!is_array($json)) {
206
-			$jsonError = json_last_error();
207
-			\OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
208
-			return false;
209
-		}
210
-
211
-		if (!empty($json['pluralForm'])) {
212
-			$this->pluralFormString = $json['pluralForm'];
213
-		}
214
-		$this->translations = array_merge($this->translations, $json['translations']);
215
-		return true;
216
-	}
31
+    /** @var IFactory */
32
+    protected $factory;
33
+
34
+    /** @var string App of this object */
35
+    protected $app;
36
+
37
+    /** @var string Language of this object */
38
+    protected $lang;
39
+
40
+    /** @var string Plural forms (string) */
41
+    private $pluralFormString = 'nplurals=2; plural=(n != 1);';
42
+
43
+    /** @var string Plural forms (function) */
44
+    private $pluralFormFunction = null;
45
+
46
+    /** @var string[] */
47
+    private $translations = [];
48
+
49
+    /**
50
+     * @param IFactory $factory
51
+     * @param string $app
52
+     * @param string $lang
53
+     * @param array $files
54
+     */
55
+    public function __construct(IFactory $factory, $app, $lang, array $files) {
56
+        $this->factory = $factory;
57
+        $this->app = $app;
58
+        $this->lang = $lang;
59
+
60
+        $this->translations = [];
61
+        foreach ($files as $languageFile) {
62
+            $this->load($languageFile);
63
+        }
64
+    }
65
+
66
+    /**
67
+     * The code (en, de, ...) of the language that is used for this instance
68
+     *
69
+     * @return string language
70
+     */
71
+    public function getLanguageCode() {
72
+        return $this->lang;
73
+    }
74
+
75
+    /**
76
+     * Translating
77
+     * @param string $text The text we need a translation for
78
+     * @param array $parameters default:array() Parameters for sprintf
79
+     * @return string Translation or the same text
80
+     *
81
+     * Returns the translation. If no translation is found, $text will be
82
+     * returned.
83
+     */
84
+    public function t($text, $parameters = array()) {
85
+        return (string) new \OC_L10N_String($this, $text, $parameters);
86
+    }
87
+
88
+    /**
89
+     * Translating
90
+     * @param string $text_singular the string to translate for exactly one object
91
+     * @param string $text_plural the string to translate for n objects
92
+     * @param integer $count Number of objects
93
+     * @param array $parameters default:array() Parameters for sprintf
94
+     * @return string Translation or the same text
95
+     *
96
+     * Returns the translation. If no translation is found, $text will be
97
+     * returned. %n will be replaced with the number of objects.
98
+     *
99
+     * The correct plural is determined by the plural_forms-function
100
+     * provided by the po file.
101
+     *
102
+     */
103
+    public function n($text_singular, $text_plural, $count, $parameters = array()) {
104
+        $identifier = "_${text_singular}_::_${text_plural}_";
105
+        if (isset($this->translations[$identifier])) {
106
+            return (string) new \OC_L10N_String($this, $identifier, $parameters, $count);
107
+        } else {
108
+            if ($count === 1) {
109
+                return (string) new \OC_L10N_String($this, $text_singular, $parameters, $count);
110
+            } else {
111
+                return (string) new \OC_L10N_String($this, $text_plural, $parameters, $count);
112
+            }
113
+        }
114
+    }
115
+
116
+    /**
117
+     * Localization
118
+     * @param string $type Type of localization
119
+     * @param \DateTime|int|string $data parameters for this localization
120
+     * @param array $options
121
+     * @return string|int|false
122
+     *
123
+     * Returns the localized data.
124
+     *
125
+     * Implemented types:
126
+     *  - date
127
+     *    - Creates a date
128
+     *    - params: timestamp (int/string)
129
+     *  - datetime
130
+     *    - Creates date and time
131
+     *    - params: timestamp (int/string)
132
+     *  - time
133
+     *    - Creates a time
134
+     *    - params: timestamp (int/string)
135
+     *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
136
+     *  - jsdate: Returns the short JS date format
137
+     */
138
+    public function l($type, $data = null, $options = array()) {
139
+        // Use the language of the instance
140
+        $locale = $this->getLanguageCode();
141
+        if ($locale === 'sr@latin') {
142
+            $locale = 'sr_latn';
143
+        }
144
+
145
+        if ($type === 'firstday') {
146
+            return (int) Calendar::getFirstWeekday($locale);
147
+        }
148
+        if ($type === 'jsdate') {
149
+            return (string) Calendar::getDateFormat('short', $locale);
150
+        }
151
+
152
+        $value = new \DateTime();
153
+        if ($data instanceof \DateTime) {
154
+            $value = $data;
155
+        } else if (is_string($data) && !is_numeric($data)) {
156
+            $data = strtotime($data);
157
+            $value->setTimestamp($data);
158
+        } else if ($data !== null) {
159
+            $value->setTimestamp($data);
160
+        }
161
+
162
+        $options = array_merge(array('width' => 'long'), $options);
163
+        $width = $options['width'];
164
+        switch ($type) {
165
+            case 'date':
166
+                return (string) Calendar::formatDate($value, $width, $locale);
167
+            case 'datetime':
168
+                return (string) Calendar::formatDatetime($value, $width, $locale);
169
+            case 'time':
170
+                return (string) Calendar::formatTime($value, $width, $locale);
171
+            default:
172
+                return false;
173
+        }
174
+    }
175
+
176
+    /**
177
+     * Returns an associative array with all translations
178
+     *
179
+     * Called by \OC_L10N_String
180
+     * @return array
181
+     */
182
+    public function getTranslations() {
183
+        return $this->translations;
184
+    }
185
+
186
+    /**
187
+     * Returnsed function accepts the argument $n
188
+     *
189
+     * Called by \OC_L10N_String
190
+     * @return string the plural form function
191
+     */
192
+    public function getPluralFormFunction() {
193
+        if (is_null($this->pluralFormFunction)) {
194
+            $this->pluralFormFunction = $this->factory->createPluralFunction($this->pluralFormString);
195
+        }
196
+        return $this->pluralFormFunction;
197
+    }
198
+
199
+    /**
200
+     * @param $translationFile
201
+     * @return bool
202
+     */
203
+    protected function load($translationFile) {
204
+        $json = json_decode(file_get_contents($translationFile), true);
205
+        if (!is_array($json)) {
206
+            $jsonError = json_last_error();
207
+            \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
208
+            return false;
209
+        }
210
+
211
+        if (!empty($json['pluralForm'])) {
212
+            $this->pluralFormString = $json['pluralForm'];
213
+        }
214
+        $this->translations = array_merge($this->translations, $json['translations']);
215
+        return true;
216
+    }
217 217
 }
Please login to merge, or discard this patch.