Completed
Pull Request — master (#4212)
by Individual IT
13:52
created
lib/private/Files/Storage/Wrapper/Encryption.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	/**
985 985
 	 * check if path points to a files version
986 986
 	 *
987
-	 * @param $path
987
+	 * @param string $path
988 988
 	 * @return bool
989 989
 	 */
990 990
 	protected function isVersion($path) {
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 	/**
996 996
 	 * check if the given storage should be encrypted or not
997 997
 	 *
998
-	 * @param $path
998
+	 * @param string $path
999 999
 	 * @return bool
1000 1000
 	 */
1001 1001
 	protected function shouldEncrypt($path) {
Please login to merge, or discard this patch.
Indentation   +972 added lines, -972 removed lines patch added patch discarded remove patch
@@ -46,977 +46,977 @@
 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->shouldEncrypt($path)) {
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->shouldEncrypt($targetInternalPath) ? 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 = $this->util->getHeaderSize();
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
-
958
-		return $encryptionModule;
959
-	}
960
-
961
-	/**
962
-	 * @param string $path
963
-	 * @param int $unencryptedSize
964
-	 */
965
-	public function updateUnencryptedSize($path, $unencryptedSize) {
966
-		$this->unencryptedSize[$path] = $unencryptedSize;
967
-	}
968
-
969
-	/**
970
-	 * copy keys to new location
971
-	 *
972
-	 * @param string $source path relative to data/
973
-	 * @param string $target path relative to data/
974
-	 * @return bool
975
-	 */
976
-	protected function copyKeys($source, $target) {
977
-		if (!$this->util->isExcluded($source)) {
978
-			return $this->keyStorage->copyKeys($source, $target);
979
-		}
980
-
981
-		return false;
982
-	}
983
-
984
-	/**
985
-	 * check if path points to a files version
986
-	 *
987
-	 * @param $path
988
-	 * @return bool
989
-	 */
990
-	protected function isVersion($path) {
991
-		$normalized = Filesystem::normalizePath($path);
992
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
-	}
994
-
995
-	/**
996
-	 * check if the given storage should be encrypted or not
997
-	 *
998
-	 * @param $path
999
-	 * @return bool
1000
-	 */
1001
-	protected function shouldEncrypt($path) {
1002
-		$fullPath = $this->getFullPath($path);
1003
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1004
-		if ($mountPointConfig === false) {
1005
-			return false;
1006
-		}
1007
-
1008
-		try {
1009
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1010
-		} catch (ModuleDoesNotExistsException $e) {
1011
-			return false;
1012
-		}
1013
-
1014
-		if ($encryptionModule === null) {
1015
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
-		}
1017
-
1018
-		return $encryptionModule->shouldEncrypt($fullPath);
1019
-
1020
-	}
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->shouldEncrypt($path)) {
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->shouldEncrypt($targetInternalPath) ? 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 = $this->util->getHeaderSize();
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
+
958
+        return $encryptionModule;
959
+    }
960
+
961
+    /**
962
+     * @param string $path
963
+     * @param int $unencryptedSize
964
+     */
965
+    public function updateUnencryptedSize($path, $unencryptedSize) {
966
+        $this->unencryptedSize[$path] = $unencryptedSize;
967
+    }
968
+
969
+    /**
970
+     * copy keys to new location
971
+     *
972
+     * @param string $source path relative to data/
973
+     * @param string $target path relative to data/
974
+     * @return bool
975
+     */
976
+    protected function copyKeys($source, $target) {
977
+        if (!$this->util->isExcluded($source)) {
978
+            return $this->keyStorage->copyKeys($source, $target);
979
+        }
980
+
981
+        return false;
982
+    }
983
+
984
+    /**
985
+     * check if path points to a files version
986
+     *
987
+     * @param $path
988
+     * @return bool
989
+     */
990
+    protected function isVersion($path) {
991
+        $normalized = Filesystem::normalizePath($path);
992
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
993
+    }
994
+
995
+    /**
996
+     * check if the given storage should be encrypted or not
997
+     *
998
+     * @param $path
999
+     * @return bool
1000
+     */
1001
+    protected function shouldEncrypt($path) {
1002
+        $fullPath = $this->getFullPath($path);
1003
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1004
+        if ($mountPointConfig === false) {
1005
+            return false;
1006
+        }
1007
+
1008
+        try {
1009
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1010
+        } catch (ModuleDoesNotExistsException $e) {
1011
+            return false;
1012
+        }
1013
+
1014
+        if ($encryptionModule === null) {
1015
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1016
+        }
1017
+
1018
+        return $encryptionModule->shouldEncrypt($fullPath);
1019
+
1020
+    }
1021 1021
 
1022 1022
 }
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->shouldEncrypt($targetInternalPath) ? 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.
apps/dav/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,6 @@
 block discarded – undo
25 25
 namespace OCA\DAV\AppInfo;
26 26
 
27 27
 use OCA\DAV\CalDAV\Activity\Backend;
28
-use OCA\DAV\CalDAV\Activity\Extension;
29 28
 use OCA\DAV\CalDAV\Activity\Provider\Event;
30 29
 use OCA\DAV\CalDAV\BirthdayService;
31 30
 use OCA\DAV\Capabilities;
Please login to merge, or discard this patch.
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -39,134 +39,134 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/**
43
-	 * Application constructor.
44
-	 */
45
-	public function __construct() {
46
-		parent::__construct('dav');
42
+    /**
43
+     * Application constructor.
44
+     */
45
+    public function __construct() {
46
+        parent::__construct('dav');
47 47
 
48
-		/*
48
+        /*
49 49
 		 * Register capabilities
50 50
 		 */
51
-		$this->getContainer()->registerCapability(Capabilities::class);
52
-	}
53
-
54
-	/**
55
-	 * @param IManager $contactsManager
56
-	 * @param string $userID
57
-	 */
58
-	public function setupContactsProvider(IManager $contactsManager, $userID) {
59
-		/** @var ContactsManager $cm */
60
-		$cm = $this->getContainer()->query(ContactsManager::class);
61
-		$urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
62
-		$cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
63
-	}
64
-
65
-	public function registerHooks() {
66
-		/** @var HookManager $hm */
67
-		$hm = $this->getContainer()->query(HookManager::class);
68
-		$hm->setup();
69
-
70
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71
-
72
-		// first time login event setup
73
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
74
-			if ($event instanceof GenericEvent) {
75
-				$hm->firstLogin($event->getSubject());
76
-			}
77
-		});
78
-
79
-		// carddav/caldav sync event setup
80
-		$listener = function($event) {
81
-			if ($event instanceof GenericEvent) {
82
-				/** @var BirthdayService $b */
83
-				$b = $this->getContainer()->query(BirthdayService::class);
84
-				$b->onCardChanged(
85
-					$event->getArgument('addressBookId'),
86
-					$event->getArgument('cardUri'),
87
-					$event->getArgument('cardData')
88
-				);
89
-			}
90
-		};
91
-
92
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
93
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
94
-		$dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
95
-			if ($event instanceof GenericEvent) {
96
-				/** @var BirthdayService $b */
97
-				$b = $this->getContainer()->query(BirthdayService::class);
98
-				$b->onCardDeleted(
99
-					$event->getArgument('addressBookId'),
100
-					$event->getArgument('cardUri')
101
-				);
102
-			}
103
-		});
104
-
105
-		$dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
106
-			$user = $event->getSubject();
107
-			$syncService = $this->getContainer()->query(SyncService::class);
108
-			$syncService->updateUser($user);
109
-		});
110
-
111
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
112
-			/** @var Backend $backend */
113
-			$backend = $this->getContainer()->query(Backend::class);
114
-			$backend->onCalendarAdd(
115
-				$event->getArgument('calendarData')
116
-			);
117
-		});
118
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
119
-			/** @var Backend $backend */
120
-			$backend = $this->getContainer()->query(Backend::class);
121
-			$backend->onCalendarUpdate(
122
-				$event->getArgument('calendarData'),
123
-				$event->getArgument('shares'),
124
-				$event->getArgument('propertyMutations')
125
-			);
126
-		});
127
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
128
-			/** @var Backend $backend */
129
-			$backend = $this->getContainer()->query(Backend::class);
130
-			$backend->onCalendarDelete(
131
-				$event->getArgument('calendarData'),
132
-				$event->getArgument('shares')
133
-			);
134
-		});
135
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
136
-			/** @var Backend $backend */
137
-			$backend = $this->getContainer()->query(Backend::class);
138
-			$backend->onCalendarUpdateShares(
139
-				$event->getArgument('calendarData'),
140
-				$event->getArgument('shares'),
141
-				$event->getArgument('add'),
142
-				$event->getArgument('remove')
143
-			);
144
-		});
145
-
146
-		$listener = function(GenericEvent $event, $eventName) {
147
-			/** @var Backend $backend */
148
-			$backend = $this->getContainer()->query(Backend::class);
149
-
150
-			$subject = Event::SUBJECT_OBJECT_ADD;
151
-			if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
152
-				$subject = Event::SUBJECT_OBJECT_UPDATE;
153
-			} else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
154
-				$subject = Event::SUBJECT_OBJECT_DELETE;
155
-			}
156
-			$backend->onTouchCalendarObject(
157
-				$subject,
158
-				$event->getArgument('calendarData'),
159
-				$event->getArgument('shares'),
160
-				$event->getArgument('objectData')
161
-			);
162
-		};
163
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
164
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
165
-		$dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
166
-	}
167
-
168
-	public function getSyncService() {
169
-		return $this->getContainer()->query(SyncService::class);
170
-	}
51
+        $this->getContainer()->registerCapability(Capabilities::class);
52
+    }
53
+
54
+    /**
55
+     * @param IManager $contactsManager
56
+     * @param string $userID
57
+     */
58
+    public function setupContactsProvider(IManager $contactsManager, $userID) {
59
+        /** @var ContactsManager $cm */
60
+        $cm = $this->getContainer()->query(ContactsManager::class);
61
+        $urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
62
+        $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
63
+    }
64
+
65
+    public function registerHooks() {
66
+        /** @var HookManager $hm */
67
+        $hm = $this->getContainer()->query(HookManager::class);
68
+        $hm->setup();
69
+
70
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71
+
72
+        // first time login event setup
73
+        $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
74
+            if ($event instanceof GenericEvent) {
75
+                $hm->firstLogin($event->getSubject());
76
+            }
77
+        });
78
+
79
+        // carddav/caldav sync event setup
80
+        $listener = function($event) {
81
+            if ($event instanceof GenericEvent) {
82
+                /** @var BirthdayService $b */
83
+                $b = $this->getContainer()->query(BirthdayService::class);
84
+                $b->onCardChanged(
85
+                    $event->getArgument('addressBookId'),
86
+                    $event->getArgument('cardUri'),
87
+                    $event->getArgument('cardData')
88
+                );
89
+            }
90
+        };
91
+
92
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $listener);
93
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $listener);
94
+        $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function($event) {
95
+            if ($event instanceof GenericEvent) {
96
+                /** @var BirthdayService $b */
97
+                $b = $this->getContainer()->query(BirthdayService::class);
98
+                $b->onCardDeleted(
99
+                    $event->getArgument('addressBookId'),
100
+                    $event->getArgument('cardUri')
101
+                );
102
+            }
103
+        });
104
+
105
+        $dispatcher->addListener('OC\AccountManager::userUpdated', function(GenericEvent $event) {
106
+            $user = $event->getSubject();
107
+            $syncService = $this->getContainer()->query(SyncService::class);
108
+            $syncService->updateUser($user);
109
+        });
110
+
111
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', function(GenericEvent $event) {
112
+            /** @var Backend $backend */
113
+            $backend = $this->getContainer()->query(Backend::class);
114
+            $backend->onCalendarAdd(
115
+                $event->getArgument('calendarData')
116
+            );
117
+        });
118
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', function(GenericEvent $event) {
119
+            /** @var Backend $backend */
120
+            $backend = $this->getContainer()->query(Backend::class);
121
+            $backend->onCalendarUpdate(
122
+                $event->getArgument('calendarData'),
123
+                $event->getArgument('shares'),
124
+                $event->getArgument('propertyMutations')
125
+            );
126
+        });
127
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', function(GenericEvent $event) {
128
+            /** @var Backend $backend */
129
+            $backend = $this->getContainer()->query(Backend::class);
130
+            $backend->onCalendarDelete(
131
+                $event->getArgument('calendarData'),
132
+                $event->getArgument('shares')
133
+            );
134
+        });
135
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateShares', function(GenericEvent $event) {
136
+            /** @var Backend $backend */
137
+            $backend = $this->getContainer()->query(Backend::class);
138
+            $backend->onCalendarUpdateShares(
139
+                $event->getArgument('calendarData'),
140
+                $event->getArgument('shares'),
141
+                $event->getArgument('add'),
142
+                $event->getArgument('remove')
143
+            );
144
+        });
145
+
146
+        $listener = function(GenericEvent $event, $eventName) {
147
+            /** @var Backend $backend */
148
+            $backend = $this->getContainer()->query(Backend::class);
149
+
150
+            $subject = Event::SUBJECT_OBJECT_ADD;
151
+            if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject') {
152
+                $subject = Event::SUBJECT_OBJECT_UPDATE;
153
+            } else if ($eventName === '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') {
154
+                $subject = Event::SUBJECT_OBJECT_DELETE;
155
+            }
156
+            $backend->onTouchCalendarObject(
157
+                $subject,
158
+                $event->getArgument('calendarData'),
159
+                $event->getArgument('shares'),
160
+                $event->getArgument('objectData')
161
+            );
162
+        };
163
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', $listener);
164
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', $listener);
165
+        $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', $listener);
166
+    }
167
+
168
+    public function getSyncService() {
169
+        return $this->getContainer()->query(SyncService::class);
170
+    }
171 171
 
172 172
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@
 block discarded – undo
70 70
 		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
71 71
 
72 72
 		// first time login event setup
73
-		$dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) {
73
+		$dispatcher->addListener(IUser::class.'::firstLogin', function($event) use ($hm) {
74 74
 			if ($event instanceof GenericEvent) {
75 75
 				$hm->firstLogin($event->getSubject());
76 76
 			}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/AmazonS3.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -191,6 +191,9 @@  discard block
 block discarded – undo
191 191
 		return false;
192 192
 	}
193 193
 
194
+	/**
195
+	 * @param string $path
196
+	 */
194 197
 	private function batchDelete ($path = null) {
195 198
 		$params = array(
196 199
 			'Bucket' => $this->bucket
@@ -516,6 +519,9 @@  discard block
 block discarded – undo
516 519
 		return $this->id;
517 520
 	}
518 521
 
522
+	/**
523
+	 * @param string $path
524
+	 */
519 525
 	public function writeBack($tmpFile, $path) {
520 526
 		try {
521 527
 			$this->getConnection()->putObject(array(
Please login to merge, or discard this patch.
Indentation   +494 added lines, -494 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 namespace OCA\Files_External\Lib\Storage;
38 38
 
39 39
 set_include_path(get_include_path() . PATH_SEPARATOR .
40
-	\OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
40
+    \OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
41 41
 require_once 'aws-autoloader.php';
42 42
 
43 43
 use Aws\S3\S3Client;
@@ -47,498 +47,498 @@  discard block
 block discarded – undo
47 47
 use OC\Files\ObjectStore\S3ConnectionTrait;
48 48
 
49 49
 class AmazonS3 extends \OC\Files\Storage\Common {
50
-	use S3ConnectionTrait;
51
-
52
-	/**
53
-	 * @var array
54
-	 */
55
-	private static $tmpFiles = array();
56
-
57
-	/**
58
-	 * @var int in seconds
59
-	 */
60
-	private $rescanDelay = 10;
61
-
62
-	public function __construct($parameters) {
63
-		parent::__construct($parameters);
64
-		$this->parseParams($parameters);
65
-	}
66
-
67
-	/**
68
-	 * @param string $path
69
-	 * @return string correctly encoded path
70
-	 */
71
-	private function normalizePath($path) {
72
-		$path = trim($path, '/');
73
-
74
-		if (!$path) {
75
-			$path = '.';
76
-		}
77
-
78
-		return $path;
79
-	}
80
-
81
-	private function isRoot($path) {
82
-		return $path === '.';
83
-	}
84
-
85
-	private function cleanKey($path) {
86
-		if ($this->isRoot($path)) {
87
-			return '/';
88
-		}
89
-		return $path;
90
-	}
91
-
92
-	/**
93
-	 * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
94
-	 * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
95
-	 *
96
-	 * @param array $params
97
-	 */
98
-	public function updateLegacyId (array $params) {
99
-		$oldId = 'amazon::' . $params['key'] . md5($params['secret']);
100
-
101
-		// find by old id or bucket
102
-		$stmt = \OC::$server->getDatabaseConnection()->prepare(
103
-			'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
104
-		);
105
-		$stmt->execute(array($oldId, $this->id));
106
-		while ($row = $stmt->fetch()) {
107
-			$storages[$row['id']] = $row['numeric_id'];
108
-		}
109
-
110
-		if (isset($storages[$this->id]) && isset($storages[$oldId])) {
111
-			// if both ids exist, delete the old storage and corresponding filecache entries
112
-			\OC\Files\Cache\Storage::remove($oldId);
113
-		} else if (isset($storages[$oldId])) {
114
-			// if only the old id exists do an update
115
-			$stmt = \OC::$server->getDatabaseConnection()->prepare(
116
-				'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
117
-			);
118
-			$stmt->execute(array($this->id, $oldId));
119
-		}
120
-		// only the bucket based id may exist, do nothing
121
-	}
122
-
123
-	/**
124
-	 * Remove a file or folder
125
-	 *
126
-	 * @param string $path
127
-	 * @return bool
128
-	 */
129
-	protected function remove($path) {
130
-		// remember fileType to reduce http calls
131
-		$fileType = $this->filetype($path);
132
-		if ($fileType === 'dir') {
133
-			return $this->rmdir($path);
134
-		} else if ($fileType === 'file') {
135
-			return $this->unlink($path);
136
-		} else {
137
-			return false;
138
-		}
139
-	}
140
-
141
-	public function mkdir($path) {
142
-		$path = $this->normalizePath($path);
143
-
144
-		if ($this->is_dir($path)) {
145
-			return false;
146
-		}
147
-
148
-		try {
149
-			$this->getConnection()->putObject(array(
150
-				'Bucket' => $this->bucket,
151
-				'Key' => $path . '/',
152
-				'Body' => '',
153
-				'ContentType' => 'httpd/unix-directory'
154
-			));
155
-			$this->testTimeout();
156
-		} catch (S3Exception $e) {
157
-			\OCP\Util::logException('files_external', $e);
158
-			return false;
159
-		}
160
-
161
-		return true;
162
-	}
163
-
164
-	public function file_exists($path) {
165
-		return $this->filetype($path) !== false;
166
-	}
167
-
168
-
169
-	public function rmdir($path) {
170
-		$path = $this->normalizePath($path);
171
-
172
-		if ($this->isRoot($path)) {
173
-			return $this->clearBucket();
174
-		}
175
-
176
-		if (!$this->file_exists($path)) {
177
-			return false;
178
-		}
179
-
180
-		return $this->batchDelete($path);
181
-	}
182
-
183
-	protected function clearBucket() {
184
-		try {
185
-			$this->getConnection()->clearBucket($this->bucket);
186
-			return true;
187
-			// clearBucket() is not working with Ceph, so if it fails we try the slower approach
188
-		} catch (\Exception $e) {
189
-			return $this->batchDelete();
190
-		}
191
-		return false;
192
-	}
193
-
194
-	private function batchDelete ($path = null) {
195
-		$params = array(
196
-			'Bucket' => $this->bucket
197
-		);
198
-		if ($path !== null) {
199
-			$params['Prefix'] = $path . '/';
200
-		}
201
-		try {
202
-			// Since there are no real directories on S3, we need
203
-			// to delete all objects prefixed with the path.
204
-			do {
205
-				// instead of the iterator, manually loop over the list ...
206
-				$objects = $this->getConnection()->listObjects($params);
207
-				// ... so we can delete the files in batches
208
-				$this->getConnection()->deleteObjects(array(
209
-					'Bucket' => $this->bucket,
210
-					'Objects' => $objects['Contents']
211
-				));
212
-				$this->testTimeout();
213
-				// we reached the end when the list is no longer truncated
214
-			} while ($objects['IsTruncated']);
215
-		} catch (S3Exception $e) {
216
-			\OCP\Util::logException('files_external', $e);
217
-			return false;
218
-		}
219
-		return true;
220
-	}
221
-
222
-	public function opendir($path) {
223
-		$path = $this->normalizePath($path);
224
-
225
-		if ($this->isRoot($path)) {
226
-			$path = '';
227
-		} else {
228
-			$path .= '/';
229
-		}
230
-
231
-		try {
232
-			$files = array();
233
-			$result = $this->getConnection()->getIterator('ListObjects', array(
234
-				'Bucket' => $this->bucket,
235
-				'Delimiter' => '/',
236
-				'Prefix' => $path
237
-			), array('return_prefixes' => true));
238
-
239
-			foreach ($result as $object) {
240
-				if (isset($object['Key']) && $object['Key'] === $path) {
241
-					// it's the directory itself, skip
242
-					continue;
243
-				}
244
-				$file = basename(
245
-					isset($object['Key']) ? $object['Key'] : $object['Prefix']
246
-				);
247
-				$files[] = $file;
248
-			}
249
-
250
-			return IteratorDirectory::wrap($files);
251
-		} catch (S3Exception $e) {
252
-			\OCP\Util::logException('files_external', $e);
253
-			return false;
254
-		}
255
-	}
256
-
257
-	public function stat($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		try {
261
-			$stat = array();
262
-			if ($this->is_dir($path)) {
263
-				//folders don't really exist
264
-				$stat['size'] = -1; //unknown
265
-				$stat['mtime'] = time() - $this->rescanDelay * 1000;
266
-			} else {
267
-				$result = $this->getConnection()->headObject(array(
268
-					'Bucket' => $this->bucket,
269
-					'Key' => $path
270
-				));
271
-
272
-				$stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
273
-				if ($result['Metadata']['lastmodified']) {
274
-					$stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
275
-				} else {
276
-					$stat['mtime'] = strtotime($result['LastModified']);
277
-				}
278
-			}
279
-			$stat['atime'] = time();
280
-
281
-			return $stat;
282
-		} catch(S3Exception $e) {
283
-			\OCP\Util::logException('files_external', $e);
284
-			return false;
285
-		}
286
-	}
287
-
288
-	public function filetype($path) {
289
-		$path = $this->normalizePath($path);
290
-
291
-		if ($this->isRoot($path)) {
292
-			return 'dir';
293
-		}
294
-
295
-		try {
296
-			if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
297
-				return 'file';
298
-			}
299
-			if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
300
-				return 'dir';
301
-			}
302
-		} catch (S3Exception $e) {
303
-			\OCP\Util::logException('files_external', $e);
304
-			return false;
305
-		}
306
-
307
-		return false;
308
-	}
309
-
310
-	public function unlink($path) {
311
-		$path = $this->normalizePath($path);
312
-
313
-		if ($this->is_dir($path)) {
314
-			return $this->rmdir($path);
315
-		}
316
-
317
-		try {
318
-			$this->getConnection()->deleteObject(array(
319
-				'Bucket' => $this->bucket,
320
-				'Key' => $path
321
-			));
322
-			$this->testTimeout();
323
-		} catch (S3Exception $e) {
324
-			\OCP\Util::logException('files_external', $e);
325
-			return false;
326
-		}
327
-
328
-		return true;
329
-	}
330
-
331
-	public function fopen($path, $mode) {
332
-		$path = $this->normalizePath($path);
333
-
334
-		switch ($mode) {
335
-			case 'r':
336
-			case 'rb':
337
-				$tmpFile = \OCP\Files::tmpFile();
338
-				self::$tmpFiles[$tmpFile] = $path;
339
-
340
-				try {
341
-					$this->getConnection()->getObject(array(
342
-						'Bucket' => $this->bucket,
343
-						'Key' => $path,
344
-						'SaveAs' => $tmpFile
345
-					));
346
-				} catch (S3Exception $e) {
347
-					\OCP\Util::logException('files_external', $e);
348
-					return false;
349
-				}
350
-
351
-				return fopen($tmpFile, 'r');
352
-			case 'w':
353
-			case 'wb':
354
-			case 'a':
355
-			case 'ab':
356
-			case 'r+':
357
-			case 'w+':
358
-			case 'wb+':
359
-			case 'a+':
360
-			case 'x':
361
-			case 'x+':
362
-			case 'c':
363
-			case 'c+':
364
-				if (strrpos($path, '.') !== false) {
365
-					$ext = substr($path, strrpos($path, '.'));
366
-				} else {
367
-					$ext = '';
368
-				}
369
-				$tmpFile = \OCP\Files::tmpFile($ext);
370
-				if ($this->file_exists($path)) {
371
-					$source = $this->fopen($path, 'r');
372
-					file_put_contents($tmpFile, $source);
373
-				}
374
-
375
-				$handle = fopen($tmpFile, $mode);
376
-				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
377
-					$this->writeBack($tmpFile, $path);
378
-				});
379
-		}
380
-		return false;
381
-	}
382
-
383
-	public function touch($path, $mtime = null) {
384
-		$path = $this->normalizePath($path);
385
-
386
-		$metadata = array();
387
-		if (is_null($mtime)) {
388
-			$mtime = time();
389
-		}
390
-		$metadata = [
391
-			'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
392
-		];
393
-
394
-		$fileType = $this->filetype($path);
395
-		try {
396
-			if ($fileType !== false) {
397
-				if ($fileType === 'dir' && ! $this->isRoot($path)) {
398
-					$path .= '/';
399
-				}
400
-				$this->getConnection()->copyObject([
401
-					'Bucket' => $this->bucket,
402
-					'Key' => $this->cleanKey($path),
403
-					'Metadata' => $metadata,
404
-					'CopySource' => $this->bucket . '/' . $path,
405
-					'MetadataDirective' => 'REPLACE',
406
-				]);
407
-				$this->testTimeout();
408
-			} else {
409
-				$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
410
-				$this->getConnection()->putObject([
411
-					'Bucket' => $this->bucket,
412
-					'Key' => $this->cleanKey($path),
413
-					'Metadata' => $metadata,
414
-					'Body' => '',
415
-					'ContentType' => $mimeType,
416
-					'MetadataDirective' => 'REPLACE',
417
-				]);
418
-				$this->testTimeout();
419
-			}
420
-		} catch (S3Exception $e) {
421
-			\OCP\Util::logException('files_external', $e);
422
-			return false;
423
-		}
424
-
425
-		return true;
426
-	}
427
-
428
-	public function copy($path1, $path2) {
429
-		$path1 = $this->normalizePath($path1);
430
-		$path2 = $this->normalizePath($path2);
431
-
432
-		if ($this->is_file($path1)) {
433
-			try {
434
-				$this->getConnection()->copyObject(array(
435
-					'Bucket' => $this->bucket,
436
-					'Key' => $this->cleanKey($path2),
437
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
438
-				));
439
-				$this->testTimeout();
440
-			} catch (S3Exception $e) {
441
-				\OCP\Util::logException('files_external', $e);
442
-				return false;
443
-			}
444
-		} else {
445
-			$this->remove($path2);
446
-
447
-			try {
448
-				$this->getConnection()->copyObject(array(
449
-					'Bucket' => $this->bucket,
450
-					'Key' => $path2 . '/',
451
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
452
-				));
453
-				$this->testTimeout();
454
-			} catch (S3Exception $e) {
455
-				\OCP\Util::logException('files_external', $e);
456
-				return false;
457
-			}
458
-
459
-			$dh = $this->opendir($path1);
460
-			if (is_resource($dh)) {
461
-				while (($file = readdir($dh)) !== false) {
462
-					if (\OC\Files\Filesystem::isIgnoredDir($file)) {
463
-						continue;
464
-					}
465
-
466
-					$source = $path1 . '/' . $file;
467
-					$target = $path2 . '/' . $file;
468
-					$this->copy($source, $target);
469
-				}
470
-			}
471
-		}
472
-
473
-		return true;
474
-	}
475
-
476
-	public function rename($path1, $path2) {
477
-		$path1 = $this->normalizePath($path1);
478
-		$path2 = $this->normalizePath($path2);
479
-
480
-		if ($this->is_file($path1)) {
481
-
482
-			if ($this->copy($path1, $path2) === false) {
483
-				return false;
484
-			}
485
-
486
-			if ($this->unlink($path1) === false) {
487
-				$this->unlink($path2);
488
-				return false;
489
-			}
490
-		} else {
491
-
492
-			if ($this->copy($path1, $path2) === false) {
493
-				return false;
494
-			}
495
-
496
-			if ($this->rmdir($path1) === false) {
497
-				$this->rmdir($path2);
498
-				return false;
499
-			}
500
-		}
501
-
502
-		return true;
503
-	}
504
-
505
-	public function test() {
506
-		$test = $this->getConnection()->getBucketAcl(array(
507
-			'Bucket' => $this->bucket,
508
-		));
509
-		if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
510
-			return true;
511
-		}
512
-		return false;
513
-	}
514
-
515
-	public function getId() {
516
-		return $this->id;
517
-	}
518
-
519
-	public function writeBack($tmpFile, $path) {
520
-		try {
521
-			$this->getConnection()->putObject(array(
522
-				'Bucket' => $this->bucket,
523
-				'Key' => $this->cleanKey($path),
524
-				'SourceFile' => $tmpFile,
525
-				'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
526
-				'ContentLength' => filesize($tmpFile)
527
-			));
528
-			$this->testTimeout();
529
-
530
-			unlink($tmpFile);
531
-		} catch (S3Exception $e) {
532
-			\OCP\Util::logException('files_external', $e);
533
-			return false;
534
-		}
535
-	}
536
-
537
-	/**
538
-	 * check if curl is installed
539
-	 */
540
-	public static function checkDependencies() {
541
-		return true;
542
-	}
50
+    use S3ConnectionTrait;
51
+
52
+    /**
53
+     * @var array
54
+     */
55
+    private static $tmpFiles = array();
56
+
57
+    /**
58
+     * @var int in seconds
59
+     */
60
+    private $rescanDelay = 10;
61
+
62
+    public function __construct($parameters) {
63
+        parent::__construct($parameters);
64
+        $this->parseParams($parameters);
65
+    }
66
+
67
+    /**
68
+     * @param string $path
69
+     * @return string correctly encoded path
70
+     */
71
+    private function normalizePath($path) {
72
+        $path = trim($path, '/');
73
+
74
+        if (!$path) {
75
+            $path = '.';
76
+        }
77
+
78
+        return $path;
79
+    }
80
+
81
+    private function isRoot($path) {
82
+        return $path === '.';
83
+    }
84
+
85
+    private function cleanKey($path) {
86
+        if ($this->isRoot($path)) {
87
+            return '/';
88
+        }
89
+        return $path;
90
+    }
91
+
92
+    /**
93
+     * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name.
94
+     * TODO Do this in an update.php. requires iterating over all users and loading the mount.json from their home
95
+     *
96
+     * @param array $params
97
+     */
98
+    public function updateLegacyId (array $params) {
99
+        $oldId = 'amazon::' . $params['key'] . md5($params['secret']);
100
+
101
+        // find by old id or bucket
102
+        $stmt = \OC::$server->getDatabaseConnection()->prepare(
103
+            'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)'
104
+        );
105
+        $stmt->execute(array($oldId, $this->id));
106
+        while ($row = $stmt->fetch()) {
107
+            $storages[$row['id']] = $row['numeric_id'];
108
+        }
109
+
110
+        if (isset($storages[$this->id]) && isset($storages[$oldId])) {
111
+            // if both ids exist, delete the old storage and corresponding filecache entries
112
+            \OC\Files\Cache\Storage::remove($oldId);
113
+        } else if (isset($storages[$oldId])) {
114
+            // if only the old id exists do an update
115
+            $stmt = \OC::$server->getDatabaseConnection()->prepare(
116
+                'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?'
117
+            );
118
+            $stmt->execute(array($this->id, $oldId));
119
+        }
120
+        // only the bucket based id may exist, do nothing
121
+    }
122
+
123
+    /**
124
+     * Remove a file or folder
125
+     *
126
+     * @param string $path
127
+     * @return bool
128
+     */
129
+    protected function remove($path) {
130
+        // remember fileType to reduce http calls
131
+        $fileType = $this->filetype($path);
132
+        if ($fileType === 'dir') {
133
+            return $this->rmdir($path);
134
+        } else if ($fileType === 'file') {
135
+            return $this->unlink($path);
136
+        } else {
137
+            return false;
138
+        }
139
+    }
140
+
141
+    public function mkdir($path) {
142
+        $path = $this->normalizePath($path);
143
+
144
+        if ($this->is_dir($path)) {
145
+            return false;
146
+        }
147
+
148
+        try {
149
+            $this->getConnection()->putObject(array(
150
+                'Bucket' => $this->bucket,
151
+                'Key' => $path . '/',
152
+                'Body' => '',
153
+                'ContentType' => 'httpd/unix-directory'
154
+            ));
155
+            $this->testTimeout();
156
+        } catch (S3Exception $e) {
157
+            \OCP\Util::logException('files_external', $e);
158
+            return false;
159
+        }
160
+
161
+        return true;
162
+    }
163
+
164
+    public function file_exists($path) {
165
+        return $this->filetype($path) !== false;
166
+    }
167
+
168
+
169
+    public function rmdir($path) {
170
+        $path = $this->normalizePath($path);
171
+
172
+        if ($this->isRoot($path)) {
173
+            return $this->clearBucket();
174
+        }
175
+
176
+        if (!$this->file_exists($path)) {
177
+            return false;
178
+        }
179
+
180
+        return $this->batchDelete($path);
181
+    }
182
+
183
+    protected function clearBucket() {
184
+        try {
185
+            $this->getConnection()->clearBucket($this->bucket);
186
+            return true;
187
+            // clearBucket() is not working with Ceph, so if it fails we try the slower approach
188
+        } catch (\Exception $e) {
189
+            return $this->batchDelete();
190
+        }
191
+        return false;
192
+    }
193
+
194
+    private function batchDelete ($path = null) {
195
+        $params = array(
196
+            'Bucket' => $this->bucket
197
+        );
198
+        if ($path !== null) {
199
+            $params['Prefix'] = $path . '/';
200
+        }
201
+        try {
202
+            // Since there are no real directories on S3, we need
203
+            // to delete all objects prefixed with the path.
204
+            do {
205
+                // instead of the iterator, manually loop over the list ...
206
+                $objects = $this->getConnection()->listObjects($params);
207
+                // ... so we can delete the files in batches
208
+                $this->getConnection()->deleteObjects(array(
209
+                    'Bucket' => $this->bucket,
210
+                    'Objects' => $objects['Contents']
211
+                ));
212
+                $this->testTimeout();
213
+                // we reached the end when the list is no longer truncated
214
+            } while ($objects['IsTruncated']);
215
+        } catch (S3Exception $e) {
216
+            \OCP\Util::logException('files_external', $e);
217
+            return false;
218
+        }
219
+        return true;
220
+    }
221
+
222
+    public function opendir($path) {
223
+        $path = $this->normalizePath($path);
224
+
225
+        if ($this->isRoot($path)) {
226
+            $path = '';
227
+        } else {
228
+            $path .= '/';
229
+        }
230
+
231
+        try {
232
+            $files = array();
233
+            $result = $this->getConnection()->getIterator('ListObjects', array(
234
+                'Bucket' => $this->bucket,
235
+                'Delimiter' => '/',
236
+                'Prefix' => $path
237
+            ), array('return_prefixes' => true));
238
+
239
+            foreach ($result as $object) {
240
+                if (isset($object['Key']) && $object['Key'] === $path) {
241
+                    // it's the directory itself, skip
242
+                    continue;
243
+                }
244
+                $file = basename(
245
+                    isset($object['Key']) ? $object['Key'] : $object['Prefix']
246
+                );
247
+                $files[] = $file;
248
+            }
249
+
250
+            return IteratorDirectory::wrap($files);
251
+        } catch (S3Exception $e) {
252
+            \OCP\Util::logException('files_external', $e);
253
+            return false;
254
+        }
255
+    }
256
+
257
+    public function stat($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        try {
261
+            $stat = array();
262
+            if ($this->is_dir($path)) {
263
+                //folders don't really exist
264
+                $stat['size'] = -1; //unknown
265
+                $stat['mtime'] = time() - $this->rescanDelay * 1000;
266
+            } else {
267
+                $result = $this->getConnection()->headObject(array(
268
+                    'Bucket' => $this->bucket,
269
+                    'Key' => $path
270
+                ));
271
+
272
+                $stat['size'] = $result['ContentLength'] ? $result['ContentLength'] : 0;
273
+                if ($result['Metadata']['lastmodified']) {
274
+                    $stat['mtime'] = strtotime($result['Metadata']['lastmodified']);
275
+                } else {
276
+                    $stat['mtime'] = strtotime($result['LastModified']);
277
+                }
278
+            }
279
+            $stat['atime'] = time();
280
+
281
+            return $stat;
282
+        } catch(S3Exception $e) {
283
+            \OCP\Util::logException('files_external', $e);
284
+            return false;
285
+        }
286
+    }
287
+
288
+    public function filetype($path) {
289
+        $path = $this->normalizePath($path);
290
+
291
+        if ($this->isRoot($path)) {
292
+            return 'dir';
293
+        }
294
+
295
+        try {
296
+            if ($this->getConnection()->doesObjectExist($this->bucket, $path)) {
297
+                return 'file';
298
+            }
299
+            if ($this->getConnection()->doesObjectExist($this->bucket, $path.'/')) {
300
+                return 'dir';
301
+            }
302
+        } catch (S3Exception $e) {
303
+            \OCP\Util::logException('files_external', $e);
304
+            return false;
305
+        }
306
+
307
+        return false;
308
+    }
309
+
310
+    public function unlink($path) {
311
+        $path = $this->normalizePath($path);
312
+
313
+        if ($this->is_dir($path)) {
314
+            return $this->rmdir($path);
315
+        }
316
+
317
+        try {
318
+            $this->getConnection()->deleteObject(array(
319
+                'Bucket' => $this->bucket,
320
+                'Key' => $path
321
+            ));
322
+            $this->testTimeout();
323
+        } catch (S3Exception $e) {
324
+            \OCP\Util::logException('files_external', $e);
325
+            return false;
326
+        }
327
+
328
+        return true;
329
+    }
330
+
331
+    public function fopen($path, $mode) {
332
+        $path = $this->normalizePath($path);
333
+
334
+        switch ($mode) {
335
+            case 'r':
336
+            case 'rb':
337
+                $tmpFile = \OCP\Files::tmpFile();
338
+                self::$tmpFiles[$tmpFile] = $path;
339
+
340
+                try {
341
+                    $this->getConnection()->getObject(array(
342
+                        'Bucket' => $this->bucket,
343
+                        'Key' => $path,
344
+                        'SaveAs' => $tmpFile
345
+                    ));
346
+                } catch (S3Exception $e) {
347
+                    \OCP\Util::logException('files_external', $e);
348
+                    return false;
349
+                }
350
+
351
+                return fopen($tmpFile, 'r');
352
+            case 'w':
353
+            case 'wb':
354
+            case 'a':
355
+            case 'ab':
356
+            case 'r+':
357
+            case 'w+':
358
+            case 'wb+':
359
+            case 'a+':
360
+            case 'x':
361
+            case 'x+':
362
+            case 'c':
363
+            case 'c+':
364
+                if (strrpos($path, '.') !== false) {
365
+                    $ext = substr($path, strrpos($path, '.'));
366
+                } else {
367
+                    $ext = '';
368
+                }
369
+                $tmpFile = \OCP\Files::tmpFile($ext);
370
+                if ($this->file_exists($path)) {
371
+                    $source = $this->fopen($path, 'r');
372
+                    file_put_contents($tmpFile, $source);
373
+                }
374
+
375
+                $handle = fopen($tmpFile, $mode);
376
+                return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
377
+                    $this->writeBack($tmpFile, $path);
378
+                });
379
+        }
380
+        return false;
381
+    }
382
+
383
+    public function touch($path, $mtime = null) {
384
+        $path = $this->normalizePath($path);
385
+
386
+        $metadata = array();
387
+        if (is_null($mtime)) {
388
+            $mtime = time();
389
+        }
390
+        $metadata = [
391
+            'lastmodified' => gmdate(\Aws\Common\Enum\DateFormat::RFC1123, $mtime)
392
+        ];
393
+
394
+        $fileType = $this->filetype($path);
395
+        try {
396
+            if ($fileType !== false) {
397
+                if ($fileType === 'dir' && ! $this->isRoot($path)) {
398
+                    $path .= '/';
399
+                }
400
+                $this->getConnection()->copyObject([
401
+                    'Bucket' => $this->bucket,
402
+                    'Key' => $this->cleanKey($path),
403
+                    'Metadata' => $metadata,
404
+                    'CopySource' => $this->bucket . '/' . $path,
405
+                    'MetadataDirective' => 'REPLACE',
406
+                ]);
407
+                $this->testTimeout();
408
+            } else {
409
+                $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
410
+                $this->getConnection()->putObject([
411
+                    'Bucket' => $this->bucket,
412
+                    'Key' => $this->cleanKey($path),
413
+                    'Metadata' => $metadata,
414
+                    'Body' => '',
415
+                    'ContentType' => $mimeType,
416
+                    'MetadataDirective' => 'REPLACE',
417
+                ]);
418
+                $this->testTimeout();
419
+            }
420
+        } catch (S3Exception $e) {
421
+            \OCP\Util::logException('files_external', $e);
422
+            return false;
423
+        }
424
+
425
+        return true;
426
+    }
427
+
428
+    public function copy($path1, $path2) {
429
+        $path1 = $this->normalizePath($path1);
430
+        $path2 = $this->normalizePath($path2);
431
+
432
+        if ($this->is_file($path1)) {
433
+            try {
434
+                $this->getConnection()->copyObject(array(
435
+                    'Bucket' => $this->bucket,
436
+                    'Key' => $this->cleanKey($path2),
437
+                    'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
438
+                ));
439
+                $this->testTimeout();
440
+            } catch (S3Exception $e) {
441
+                \OCP\Util::logException('files_external', $e);
442
+                return false;
443
+            }
444
+        } else {
445
+            $this->remove($path2);
446
+
447
+            try {
448
+                $this->getConnection()->copyObject(array(
449
+                    'Bucket' => $this->bucket,
450
+                    'Key' => $path2 . '/',
451
+                    'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
452
+                ));
453
+                $this->testTimeout();
454
+            } catch (S3Exception $e) {
455
+                \OCP\Util::logException('files_external', $e);
456
+                return false;
457
+            }
458
+
459
+            $dh = $this->opendir($path1);
460
+            if (is_resource($dh)) {
461
+                while (($file = readdir($dh)) !== false) {
462
+                    if (\OC\Files\Filesystem::isIgnoredDir($file)) {
463
+                        continue;
464
+                    }
465
+
466
+                    $source = $path1 . '/' . $file;
467
+                    $target = $path2 . '/' . $file;
468
+                    $this->copy($source, $target);
469
+                }
470
+            }
471
+        }
472
+
473
+        return true;
474
+    }
475
+
476
+    public function rename($path1, $path2) {
477
+        $path1 = $this->normalizePath($path1);
478
+        $path2 = $this->normalizePath($path2);
479
+
480
+        if ($this->is_file($path1)) {
481
+
482
+            if ($this->copy($path1, $path2) === false) {
483
+                return false;
484
+            }
485
+
486
+            if ($this->unlink($path1) === false) {
487
+                $this->unlink($path2);
488
+                return false;
489
+            }
490
+        } else {
491
+
492
+            if ($this->copy($path1, $path2) === false) {
493
+                return false;
494
+            }
495
+
496
+            if ($this->rmdir($path1) === false) {
497
+                $this->rmdir($path2);
498
+                return false;
499
+            }
500
+        }
501
+
502
+        return true;
503
+    }
504
+
505
+    public function test() {
506
+        $test = $this->getConnection()->getBucketAcl(array(
507
+            'Bucket' => $this->bucket,
508
+        ));
509
+        if (isset($test) && !is_null($test->getPath('Owner/ID'))) {
510
+            return true;
511
+        }
512
+        return false;
513
+    }
514
+
515
+    public function getId() {
516
+        return $this->id;
517
+    }
518
+
519
+    public function writeBack($tmpFile, $path) {
520
+        try {
521
+            $this->getConnection()->putObject(array(
522
+                'Bucket' => $this->bucket,
523
+                'Key' => $this->cleanKey($path),
524
+                'SourceFile' => $tmpFile,
525
+                'ContentType' => \OC::$server->getMimeTypeDetector()->detect($tmpFile),
526
+                'ContentLength' => filesize($tmpFile)
527
+            ));
528
+            $this->testTimeout();
529
+
530
+            unlink($tmpFile);
531
+        } catch (S3Exception $e) {
532
+            \OCP\Util::logException('files_external', $e);
533
+            return false;
534
+        }
535
+    }
536
+
537
+    /**
538
+     * check if curl is installed
539
+     */
540
+    public static function checkDependencies() {
541
+        return true;
542
+    }
543 543
 
544 544
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 
37 37
 namespace OCA\Files_External\Lib\Storage;
38 38
 
39
-set_include_path(get_include_path() . PATH_SEPARATOR .
40
-	\OC_App::getAppPath('files_external') . '/3rdparty/aws-sdk-php');
39
+set_include_path(get_include_path().PATH_SEPARATOR.
40
+	\OC_App::getAppPath('files_external').'/3rdparty/aws-sdk-php');
41 41
 require_once 'aws-autoloader.php';
42 42
 
43 43
 use Aws\S3\S3Client;
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
 	 *
96 96
 	 * @param array $params
97 97
 	 */
98
-	public function updateLegacyId (array $params) {
99
-		$oldId = 'amazon::' . $params['key'] . md5($params['secret']);
98
+	public function updateLegacyId(array $params) {
99
+		$oldId = 'amazon::'.$params['key'].md5($params['secret']);
100 100
 
101 101
 		// find by old id or bucket
102 102
 		$stmt = \OC::$server->getDatabaseConnection()->prepare(
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 		try {
149 149
 			$this->getConnection()->putObject(array(
150 150
 				'Bucket' => $this->bucket,
151
-				'Key' => $path . '/',
151
+				'Key' => $path.'/',
152 152
 				'Body' => '',
153 153
 				'ContentType' => 'httpd/unix-directory'
154 154
 			));
@@ -191,12 +191,12 @@  discard block
 block discarded – undo
191 191
 		return false;
192 192
 	}
193 193
 
194
-	private function batchDelete ($path = null) {
194
+	private function batchDelete($path = null) {
195 195
 		$params = array(
196 196
 			'Bucket' => $this->bucket
197 197
 		);
198 198
 		if ($path !== null) {
199
-			$params['Prefix'] = $path . '/';
199
+			$params['Prefix'] = $path.'/';
200 200
 		}
201 201
 		try {
202 202
 			// Since there are no real directories on S3, we need
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 			$stat['atime'] = time();
280 280
 
281 281
 			return $stat;
282
-		} catch(S3Exception $e) {
282
+		} catch (S3Exception $e) {
283 283
 			\OCP\Util::logException('files_external', $e);
284 284
 			return false;
285 285
 		}
@@ -394,14 +394,14 @@  discard block
 block discarded – undo
394 394
 		$fileType = $this->filetype($path);
395 395
 		try {
396 396
 			if ($fileType !== false) {
397
-				if ($fileType === 'dir' && ! $this->isRoot($path)) {
397
+				if ($fileType === 'dir' && !$this->isRoot($path)) {
398 398
 					$path .= '/';
399 399
 				}
400 400
 				$this->getConnection()->copyObject([
401 401
 					'Bucket' => $this->bucket,
402 402
 					'Key' => $this->cleanKey($path),
403 403
 					'Metadata' => $metadata,
404
-					'CopySource' => $this->bucket . '/' . $path,
404
+					'CopySource' => $this->bucket.'/'.$path,
405 405
 					'MetadataDirective' => 'REPLACE',
406 406
 				]);
407 407
 				$this->testTimeout();
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 				$this->getConnection()->copyObject(array(
435 435
 					'Bucket' => $this->bucket,
436 436
 					'Key' => $this->cleanKey($path2),
437
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1)
437
+					'CopySource' => S3Client::encodeKey($this->bucket.'/'.$path1)
438 438
 				));
439 439
 				$this->testTimeout();
440 440
 			} catch (S3Exception $e) {
@@ -447,8 +447,8 @@  discard block
 block discarded – undo
447 447
 			try {
448 448
 				$this->getConnection()->copyObject(array(
449 449
 					'Bucket' => $this->bucket,
450
-					'Key' => $path2 . '/',
451
-					'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/')
450
+					'Key' => $path2.'/',
451
+					'CopySource' => S3Client::encodeKey($this->bucket.'/'.$path1.'/')
452 452
 				));
453 453
 				$this->testTimeout();
454 454
 			} catch (S3Exception $e) {
@@ -463,8 +463,8 @@  discard block
 block discarded – undo
463 463
 						continue;
464 464
 					}
465 465
 
466
-					$source = $path1 . '/' . $file;
467
-					$target = $path2 . '/' . $file;
466
+					$source = $path1.'/'.$file;
467
+					$target = $path2.'/'.$file;
468 468
 					$this->copy($source, $target);
469 469
 				}
470 470
 			}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Dropbox.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -76,6 +76,9 @@  discard block
 block discarded – undo
76 76
 		return false;
77 77
 	}
78 78
 
79
+	/**
80
+	 * @param string $path
81
+	 */
79 82
 	private function setMetaData($path, $metaData) {
80 83
 		$this->metaData[ltrim($path, '/')] = $metaData;
81 84
 	}
@@ -316,6 +319,9 @@  discard block
 block discarded – undo
316 319
 		return false;
317 320
 	}
318 321
 
322
+	/**
323
+	 * @param string $path
324
+	 */
319 325
 	public function writeBack($tmpFile, $path) {
320 326
 		$handle = fopen($tmpFile, 'r');
321 327
 		try {
Please login to merge, or discard this patch.
Indentation   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -40,317 +40,317 @@
 block discarded – undo
40 40
 
41 41
 class Dropbox extends \OC\Files\Storage\Common {
42 42
 
43
-	private $dropbox;
44
-	private $root;
45
-	private $id;
46
-	private $metaData = array();
47
-	private $oauth;
43
+    private $dropbox;
44
+    private $root;
45
+    private $id;
46
+    private $metaData = array();
47
+    private $oauth;
48 48
 
49
-	public function __construct($params) {
50
-		if (isset($params['configured']) && $params['configured'] == 'true'
51
-			&& isset($params['app_key'])
52
-			&& isset($params['app_secret'])
53
-			&& isset($params['token'])
54
-			&& isset($params['token_secret'])
55
-		) {
56
-			$this->root = isset($params['root']) ? $params['root'] : '';
57
-			$this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
58
-			$this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59
-			$this->oauth->setToken($params['token'], $params['token_secret']);
60
-			// note: Dropbox_API connection is lazy
61
-			$this->dropbox = new \Dropbox_API($this->oauth, 'auto');
62
-		} else {
63
-			throw new \Exception('Creating Dropbox storage failed');
64
-		}
65
-	}
49
+    public function __construct($params) {
50
+        if (isset($params['configured']) && $params['configured'] == 'true'
51
+            && isset($params['app_key'])
52
+            && isset($params['app_secret'])
53
+            && isset($params['token'])
54
+            && isset($params['token_secret'])
55
+        ) {
56
+            $this->root = isset($params['root']) ? $params['root'] : '';
57
+            $this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
58
+            $this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59
+            $this->oauth->setToken($params['token'], $params['token_secret']);
60
+            // note: Dropbox_API connection is lazy
61
+            $this->dropbox = new \Dropbox_API($this->oauth, 'auto');
62
+        } else {
63
+            throw new \Exception('Creating Dropbox storage failed');
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * @param string $path
69
-	 */
70
-	private function deleteMetaData($path) {
71
-		$path = ltrim($this->root.$path, '/');
72
-		if (isset($this->metaData[$path])) {
73
-			unset($this->metaData[$path]);
74
-			return true;
75
-		}
76
-		return false;
77
-	}
67
+    /**
68
+     * @param string $path
69
+     */
70
+    private function deleteMetaData($path) {
71
+        $path = ltrim($this->root.$path, '/');
72
+        if (isset($this->metaData[$path])) {
73
+            unset($this->metaData[$path]);
74
+            return true;
75
+        }
76
+        return false;
77
+    }
78 78
 
79
-	private function setMetaData($path, $metaData) {
80
-		$this->metaData[ltrim($path, '/')] = $metaData;
81
-	}
79
+    private function setMetaData($path, $metaData) {
80
+        $this->metaData[ltrim($path, '/')] = $metaData;
81
+    }
82 82
 
83
-	/**
84
-	 * Returns the path's metadata
85
-	 * @param string $path path for which to return the metadata
86
-	 * @param bool $list if true, also return the directory's contents
87
-	 * @return mixed directory contents if $list is true, file metadata if $list is
88
-	 * false, null if the file doesn't exist or "false" if the operation failed
89
-	 */
90
-	private function getDropBoxMetaData($path, $list = false) {
91
-		$path = ltrim($this->root.$path, '/');
92
-		if ( ! $list && isset($this->metaData[$path])) {
93
-			return $this->metaData[$path];
94
-		} else {
95
-			if ($list) {
96
-				try {
97
-					$response = $this->dropbox->getMetaData($path);
98
-				} catch (\Dropbox_Exception_Forbidden $e) {
99
-					throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
100
-				} catch (\Exception $exception) {
101
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
102
-					return false;
103
-				}
104
-				$contents = array();
105
-				if ($response && isset($response['contents'])) {
106
-					// Cache folder's contents
107
-					foreach ($response['contents'] as $file) {
108
-						if (!isset($file['is_deleted']) || !$file['is_deleted']) {
109
-							$this->setMetaData($path.'/'.basename($file['path']), $file);
110
-							$contents[] = $file;
111
-						}
112
-					}
113
-					unset($response['contents']);
114
-				}
115
-				if (!isset($response['is_deleted']) || !$response['is_deleted']) {
116
-					$this->setMetaData($path, $response);
117
-				}
118
-				// Return contents of folder only
119
-				return $contents;
120
-			} else {
121
-				try {
122
-					$requestPath = $path;
123
-					if ($path === '.') {
124
-						$requestPath = '';
125
-					}
83
+    /**
84
+     * Returns the path's metadata
85
+     * @param string $path path for which to return the metadata
86
+     * @param bool $list if true, also return the directory's contents
87
+     * @return mixed directory contents if $list is true, file metadata if $list is
88
+     * false, null if the file doesn't exist or "false" if the operation failed
89
+     */
90
+    private function getDropBoxMetaData($path, $list = false) {
91
+        $path = ltrim($this->root.$path, '/');
92
+        if ( ! $list && isset($this->metaData[$path])) {
93
+            return $this->metaData[$path];
94
+        } else {
95
+            if ($list) {
96
+                try {
97
+                    $response = $this->dropbox->getMetaData($path);
98
+                } catch (\Dropbox_Exception_Forbidden $e) {
99
+                    throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
100
+                } catch (\Exception $exception) {
101
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
102
+                    return false;
103
+                }
104
+                $contents = array();
105
+                if ($response && isset($response['contents'])) {
106
+                    // Cache folder's contents
107
+                    foreach ($response['contents'] as $file) {
108
+                        if (!isset($file['is_deleted']) || !$file['is_deleted']) {
109
+                            $this->setMetaData($path.'/'.basename($file['path']), $file);
110
+                            $contents[] = $file;
111
+                        }
112
+                    }
113
+                    unset($response['contents']);
114
+                }
115
+                if (!isset($response['is_deleted']) || !$response['is_deleted']) {
116
+                    $this->setMetaData($path, $response);
117
+                }
118
+                // Return contents of folder only
119
+                return $contents;
120
+            } else {
121
+                try {
122
+                    $requestPath = $path;
123
+                    if ($path === '.') {
124
+                        $requestPath = '';
125
+                    }
126 126
 
127
-					$response = $this->dropbox->getMetaData($requestPath, 'false');
128
-					if (!isset($response['is_deleted']) || !$response['is_deleted']) {
129
-						$this->setMetaData($path, $response);
130
-						return $response;
131
-					}
132
-					return null;
133
-				} catch (\Dropbox_Exception_Forbidden $e) {
134
-					throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
135
-				} catch (\Exception $exception) {
136
-					if ($exception instanceof \Dropbox_Exception_NotFound) {
137
-						// don't log, might be a file_exist check
138
-						return false;
139
-					}
140
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
141
-					return false;
142
-				}
143
-			}
144
-		}
145
-	}
127
+                    $response = $this->dropbox->getMetaData($requestPath, 'false');
128
+                    if (!isset($response['is_deleted']) || !$response['is_deleted']) {
129
+                        $this->setMetaData($path, $response);
130
+                        return $response;
131
+                    }
132
+                    return null;
133
+                } catch (\Dropbox_Exception_Forbidden $e) {
134
+                    throw new StorageNotAvailableException('Dropbox API rate limit exceeded', StorageNotAvailableException::STATUS_ERROR, $e);
135
+                } catch (\Exception $exception) {
136
+                    if ($exception instanceof \Dropbox_Exception_NotFound) {
137
+                        // don't log, might be a file_exist check
138
+                        return false;
139
+                    }
140
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
141
+                    return false;
142
+                }
143
+            }
144
+        }
145
+    }
146 146
 
147
-	public function getId(){
148
-		return $this->id;
149
-	}
147
+    public function getId(){
148
+        return $this->id;
149
+    }
150 150
 
151
-	public function mkdir($path) {
152
-		$path = $this->root.$path;
153
-		try {
154
-			$this->dropbox->createFolder($path);
155
-			return true;
156
-		} catch (\Exception $exception) {
157
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
158
-			return false;
159
-		}
160
-	}
151
+    public function mkdir($path) {
152
+        $path = $this->root.$path;
153
+        try {
154
+            $this->dropbox->createFolder($path);
155
+            return true;
156
+        } catch (\Exception $exception) {
157
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
158
+            return false;
159
+        }
160
+    }
161 161
 
162
-	public function rmdir($path) {
163
-		return $this->unlink($path);
164
-	}
162
+    public function rmdir($path) {
163
+        return $this->unlink($path);
164
+    }
165 165
 
166
-	public function opendir($path) {
167
-		$contents = $this->getDropBoxMetaData($path, true);
168
-		if ($contents !== false) {
169
-			$files = array();
170
-			foreach ($contents as $file) {
171
-				$files[] = basename($file['path']);
172
-			}
173
-			return IteratorDirectory::wrap($files);
174
-		}
175
-		return false;
176
-	}
166
+    public function opendir($path) {
167
+        $contents = $this->getDropBoxMetaData($path, true);
168
+        if ($contents !== false) {
169
+            $files = array();
170
+            foreach ($contents as $file) {
171
+                $files[] = basename($file['path']);
172
+            }
173
+            return IteratorDirectory::wrap($files);
174
+        }
175
+        return false;
176
+    }
177 177
 
178
-	public function stat($path) {
179
-		$metaData = $this->getDropBoxMetaData($path);
180
-		if ($metaData) {
181
-			$stat['size'] = $metaData['bytes'];
182
-			$stat['atime'] = time();
183
-			$stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
184
-			return $stat;
185
-		}
186
-		return false;
187
-	}
178
+    public function stat($path) {
179
+        $metaData = $this->getDropBoxMetaData($path);
180
+        if ($metaData) {
181
+            $stat['size'] = $metaData['bytes'];
182
+            $stat['atime'] = time();
183
+            $stat['mtime'] = (isset($metaData['modified'])) ? strtotime($metaData['modified']) : time();
184
+            return $stat;
185
+        }
186
+        return false;
187
+    }
188 188
 
189
-	public function filetype($path) {
190
-		if ($path == '' || $path == '/') {
191
-			return 'dir';
192
-		} else {
193
-			$metaData = $this->getDropBoxMetaData($path);
194
-			if ($metaData) {
195
-				if ($metaData['is_dir'] == 'true') {
196
-					return 'dir';
197
-				} else {
198
-					return 'file';
199
-				}
200
-			}
201
-		}
202
-		return false;
203
-	}
189
+    public function filetype($path) {
190
+        if ($path == '' || $path == '/') {
191
+            return 'dir';
192
+        } else {
193
+            $metaData = $this->getDropBoxMetaData($path);
194
+            if ($metaData) {
195
+                if ($metaData['is_dir'] == 'true') {
196
+                    return 'dir';
197
+                } else {
198
+                    return 'file';
199
+                }
200
+            }
201
+        }
202
+        return false;
203
+    }
204 204
 
205
-	public function file_exists($path) {
206
-		if ($path == '' || $path == '/') {
207
-			return true;
208
-		}
209
-		if ($this->getDropBoxMetaData($path)) {
210
-			return true;
211
-		}
212
-		return false;
213
-	}
205
+    public function file_exists($path) {
206
+        if ($path == '' || $path == '/') {
207
+            return true;
208
+        }
209
+        if ($this->getDropBoxMetaData($path)) {
210
+            return true;
211
+        }
212
+        return false;
213
+    }
214 214
 
215
-	public function unlink($path) {
216
-		try {
217
-			$this->dropbox->delete($this->root.$path);
218
-			$this->deleteMetaData($path);
219
-			return true;
220
-		} catch (\Exception $exception) {
221
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
222
-			return false;
223
-		}
224
-	}
215
+    public function unlink($path) {
216
+        try {
217
+            $this->dropbox->delete($this->root.$path);
218
+            $this->deleteMetaData($path);
219
+            return true;
220
+        } catch (\Exception $exception) {
221
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
222
+            return false;
223
+        }
224
+    }
225 225
 
226
-	public function rename($path1, $path2) {
227
-		try {
228
-			// overwrite if target file exists and is not a directory
229
-			$destMetaData = $this->getDropBoxMetaData($path2);
230
-			if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
231
-				$this->unlink($path2);
232
-			}
233
-			$this->dropbox->move($this->root.$path1, $this->root.$path2);
234
-			$this->deleteMetaData($path1);
235
-			return true;
236
-		} catch (\Exception $exception) {
237
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
238
-			return false;
239
-		}
240
-	}
226
+    public function rename($path1, $path2) {
227
+        try {
228
+            // overwrite if target file exists and is not a directory
229
+            $destMetaData = $this->getDropBoxMetaData($path2);
230
+            if (isset($destMetaData) && $destMetaData !== false && !$destMetaData['is_dir']) {
231
+                $this->unlink($path2);
232
+            }
233
+            $this->dropbox->move($this->root.$path1, $this->root.$path2);
234
+            $this->deleteMetaData($path1);
235
+            return true;
236
+        } catch (\Exception $exception) {
237
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
238
+            return false;
239
+        }
240
+    }
241 241
 
242
-	public function copy($path1, $path2) {
243
-		$path1 = $this->root.$path1;
244
-		$path2 = $this->root.$path2;
245
-		try {
246
-			$this->dropbox->copy($path1, $path2);
247
-			return true;
248
-		} catch (\Exception $exception) {
249
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
250
-			return false;
251
-		}
252
-	}
242
+    public function copy($path1, $path2) {
243
+        $path1 = $this->root.$path1;
244
+        $path2 = $this->root.$path2;
245
+        try {
246
+            $this->dropbox->copy($path1, $path2);
247
+            return true;
248
+        } catch (\Exception $exception) {
249
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
250
+            return false;
251
+        }
252
+    }
253 253
 
254
-	public function fopen($path, $mode) {
255
-		$path = $this->root.$path;
256
-		switch ($mode) {
257
-			case 'r':
258
-			case 'rb':
259
-				try {
260
-					// slashes need to stay
261
-					$encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
-					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
263
-					$headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
254
+    public function fopen($path, $mode) {
255
+        $path = $this->root.$path;
256
+        switch ($mode) {
257
+            case 'r':
258
+            case 'rb':
259
+                try {
260
+                    // slashes need to stay
261
+                    $encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
+                    $downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
263
+                    $headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
264 264
 
265
-					$client = \OC::$server->getHTTPClientService()->newClient();
266
-					try {
267
-						$response = $client->get($downloadUrl, [
268
-							'headers' => $headers,
269
-							'stream' => true,
270
-						]);
271
-					} catch (RequestException $e) {
272
-						if (!is_null($e->getResponse())) {
273
-							if ($e->getResponse()->getStatusCode() === 404) {
274
-								return false;
275
-							} else {
276
-								throw $e;
277
-							}
278
-						} else {
279
-							throw $e;
280
-						}
281
-					}
265
+                    $client = \OC::$server->getHTTPClientService()->newClient();
266
+                    try {
267
+                        $response = $client->get($downloadUrl, [
268
+                            'headers' => $headers,
269
+                            'stream' => true,
270
+                        ]);
271
+                    } catch (RequestException $e) {
272
+                        if (!is_null($e->getResponse())) {
273
+                            if ($e->getResponse()->getStatusCode() === 404) {
274
+                                return false;
275
+                            } else {
276
+                                throw $e;
277
+                            }
278
+                        } else {
279
+                            throw $e;
280
+                        }
281
+                    }
282 282
 
283
-					$handle = $response->getBody();
284
-					return RetryWrapper::wrap($handle);
285
-				} catch (\Exception $exception) {
286
-					\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
287
-					return false;
288
-				}
289
-			case 'w':
290
-			case 'wb':
291
-			case 'a':
292
-			case 'ab':
293
-			case 'r+':
294
-			case 'w+':
295
-			case 'wb+':
296
-			case 'a+':
297
-			case 'x':
298
-			case 'x+':
299
-			case 'c':
300
-			case 'c+':
301
-				if (strrpos($path, '.') !== false) {
302
-					$ext = substr($path, strrpos($path, '.'));
303
-				} else {
304
-					$ext = '';
305
-				}
306
-				$tmpFile = \OCP\Files::tmpFile($ext);
307
-				if ($this->file_exists($path)) {
308
-					$source = $this->fopen($path, 'r');
309
-					file_put_contents($tmpFile, $source);
310
-				}
311
-			$handle = fopen($tmpFile, $mode);
312
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
313
-				$this->writeBack($tmpFile, $path);
314
-			});
315
-		}
316
-		return false;
317
-	}
283
+                    $handle = $response->getBody();
284
+                    return RetryWrapper::wrap($handle);
285
+                } catch (\Exception $exception) {
286
+                    \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
287
+                    return false;
288
+                }
289
+            case 'w':
290
+            case 'wb':
291
+            case 'a':
292
+            case 'ab':
293
+            case 'r+':
294
+            case 'w+':
295
+            case 'wb+':
296
+            case 'a+':
297
+            case 'x':
298
+            case 'x+':
299
+            case 'c':
300
+            case 'c+':
301
+                if (strrpos($path, '.') !== false) {
302
+                    $ext = substr($path, strrpos($path, '.'));
303
+                } else {
304
+                    $ext = '';
305
+                }
306
+                $tmpFile = \OCP\Files::tmpFile($ext);
307
+                if ($this->file_exists($path)) {
308
+                    $source = $this->fopen($path, 'r');
309
+                    file_put_contents($tmpFile, $source);
310
+                }
311
+            $handle = fopen($tmpFile, $mode);
312
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
313
+                $this->writeBack($tmpFile, $path);
314
+            });
315
+        }
316
+        return false;
317
+    }
318 318
 
319
-	public function writeBack($tmpFile, $path) {
320
-		$handle = fopen($tmpFile, 'r');
321
-		try {
322
-			$this->dropbox->putFile($path, $handle);
323
-			unlink($tmpFile);
324
-			$this->deleteMetaData($path);
325
-		} catch (\Exception $exception) {
326
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
327
-		}
328
-	}
319
+    public function writeBack($tmpFile, $path) {
320
+        $handle = fopen($tmpFile, 'r');
321
+        try {
322
+            $this->dropbox->putFile($path, $handle);
323
+            unlink($tmpFile);
324
+            $this->deleteMetaData($path);
325
+        } catch (\Exception $exception) {
326
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
327
+        }
328
+    }
329 329
 
330
-	public function free_space($path) {
331
-		try {
332
-			$info = $this->dropbox->getAccountInfo();
333
-			return $info['quota_info']['quota'] - $info['quota_info']['normal'];
334
-		} catch (\Exception $exception) {
335
-			\OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
336
-			return false;
337
-		}
338
-	}
330
+    public function free_space($path) {
331
+        try {
332
+            $info = $this->dropbox->getAccountInfo();
333
+            return $info['quota_info']['quota'] - $info['quota_info']['normal'];
334
+        } catch (\Exception $exception) {
335
+            \OCP\Util::writeLog('files_external', $exception->getMessage(), \OCP\Util::ERROR);
336
+            return false;
337
+        }
338
+    }
339 339
 
340
-	public function touch($path, $mtime = null) {
341
-		if ($this->file_exists($path)) {
342
-			return false;
343
-		} else {
344
-			$this->file_put_contents($path, '');
345
-		}
346
-		return true;
347
-	}
340
+    public function touch($path, $mtime = null) {
341
+        if ($this->file_exists($path)) {
342
+            return false;
343
+        } else {
344
+            $this->file_put_contents($path, '');
345
+        }
346
+        return true;
347
+    }
348 348
 
349
-	/**
350
-	 * check if curl is installed
351
-	 */
352
-	public static function checkDependencies() {
353
-		return true;
354
-	}
349
+    /**
350
+     * check if curl is installed
351
+     */
352
+    public static function checkDependencies() {
353
+        return true;
354
+    }
355 355
 
356 356
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\RetryWrapper;
37 37
 use OCP\Files\StorageNotAvailableException;
38 38
 
39
-require_once __DIR__ . '/../../../3rdparty/Dropbox/autoload.php';
39
+require_once __DIR__.'/../../../3rdparty/Dropbox/autoload.php';
40 40
 
41 41
 class Dropbox extends \OC\Files\Storage\Common {
42 42
 
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 			&& isset($params['token_secret'])
55 55
 		) {
56 56
 			$this->root = isset($params['root']) ? $params['root'] : '';
57
-			$this->id = 'dropbox::'.$params['app_key'] . $params['token']. '/' . $this->root;
57
+			$this->id = 'dropbox::'.$params['app_key'].$params['token'].'/'.$this->root;
58 58
 			$this->oauth = new \Dropbox_OAuth_Curl($params['app_key'], $params['app_secret']);
59 59
 			$this->oauth->setToken($params['token'], $params['token_secret']);
60 60
 			// note: Dropbox_API connection is lazy
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 */
90 90
 	private function getDropBoxMetaData($path, $list = false) {
91 91
 		$path = ltrim($this->root.$path, '/');
92
-		if ( ! $list && isset($this->metaData[$path])) {
92
+		if (!$list && isset($this->metaData[$path])) {
93 93
 			return $this->metaData[$path];
94 94
 		} else {
95 95
 			if ($list) {
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 		}
145 145
 	}
146 146
 
147
-	public function getId(){
147
+	public function getId() {
148 148
 		return $this->id;
149 149
 	}
150 150
 
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 				try {
260 260
 					// slashes need to stay
261 261
 					$encodedPath = str_replace('%2F', '/', rawurlencode(trim($path, '/')));
262
-					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/' . $encodedPath;
262
+					$downloadUrl = 'https://api-content.dropbox.com/1/files/auto/'.$encodedPath;
263 263
 					$headers = $this->oauth->getOAuthHeader($downloadUrl, [], 'GET');
264 264
 
265 265
 					$client = \OC::$server->getHTTPClientService()->newClient();
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 					file_put_contents($tmpFile, $source);
310 310
 				}
311 311
 			$handle = fopen($tmpFile, $mode);
312
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
312
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
313 313
 				$this->writeBack($tmpFile, $path);
314 314
 			});
315 315
 		}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Google.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 	 *
217 217
 	 * @param \Google_Service_Drive_DriveFile
218 218
 	 *
219
-	 * @return true if the file is a Google Doc file, false otherwise
219
+	 * @return boolean if the file is a Google Doc file, false otherwise
220 220
 	 */
221 221
 	private function isGoogleDocFile($file) {
222 222
 		return $this->getGoogleDocExtension($file->getMimeType()) !== '';
@@ -505,6 +505,9 @@  discard block
 block discarded – undo
505 505
 		}
506 506
 	}
507 507
 
508
+	/**
509
+	 * @param string $path
510
+	 */
508 511
 	public function writeBack($tmpFile, $path) {
509 512
 		$parentFolder = $this->getDriveFile(dirname($path));
510 513
 		if ($parentFolder) {
Please login to merge, or discard this patch.
Indentation   +675 added lines, -675 removed lines patch added patch discarded remove patch
@@ -41,684 +41,684 @@
 block discarded – undo
41 41
 use Icewind\Streams\RetryWrapper;
42 42
 
43 43
 set_include_path(get_include_path().PATH_SEPARATOR.
44
-	\OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
44
+    \OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
45 45
 require_once 'Google/autoload.php';
46 46
 
47 47
 class Google extends \OC\Files\Storage\Common {
48 48
 
49
-	private $client;
50
-	private $id;
51
-	private $service;
52
-	private $driveFiles;
53
-
54
-	// Google Doc mimetypes
55
-	const FOLDER = 'application/vnd.google-apps.folder';
56
-	const DOCUMENT = 'application/vnd.google-apps.document';
57
-	const SPREADSHEET = 'application/vnd.google-apps.spreadsheet';
58
-	const DRAWING = 'application/vnd.google-apps.drawing';
59
-	const PRESENTATION = 'application/vnd.google-apps.presentation';
60
-	const MAP = 'application/vnd.google-apps.map';
61
-
62
-	public function __construct($params) {
63
-		if (isset($params['configured']) && $params['configured'] === 'true'
64
-			&& isset($params['client_id']) && isset($params['client_secret'])
65
-			&& isset($params['token'])
66
-		) {
67
-			$this->client = new \Google_Client();
68
-			$this->client->setClientId($params['client_id']);
69
-			$this->client->setClientSecret($params['client_secret']);
70
-			$this->client->setScopes(array('https://www.googleapis.com/auth/drive'));
71
-			$this->client->setAccessToken($params['token']);
72
-			// if curl isn't available we're likely to run into
73
-			// https://github.com/google/google-api-php-client/issues/59
74
-			// - disable gzip to avoid it.
75
-			if (!function_exists('curl_version') || !function_exists('curl_exec')) {
76
-				$this->client->setClassConfig("Google_Http_Request", "disable_gzip", true);
77
-			}
78
-			// note: API connection is lazy
79
-			$this->service = new \Google_Service_Drive($this->client);
80
-			$token = json_decode($params['token'], true);
81
-			$this->id = 'google::'.substr($params['client_id'], 0, 30).$token['created'];
82
-		} else {
83
-			throw new \Exception('Creating Google storage failed');
84
-		}
85
-	}
86
-
87
-	public function getId() {
88
-		return $this->id;
89
-	}
90
-
91
-	/**
92
-	 * Get the Google_Service_Drive_DriveFile object for the specified path.
93
-	 * Returns false on failure.
94
-	 * @param string $path
95
-	 * @return \Google_Service_Drive_DriveFile|false
96
-	 */
97
-	private function getDriveFile($path) {
98
-		// Remove leading and trailing slashes
99
-		$path = trim($path, '/');
100
-		if ($path === '.') {
101
-			$path = '';
102
-		}
103
-		if (isset($this->driveFiles[$path])) {
104
-			return $this->driveFiles[$path];
105
-		} else if ($path === '') {
106
-			$root = $this->service->files->get('root');
107
-			$this->driveFiles[$path] = $root;
108
-			return $root;
109
-		} else {
110
-			// Google Drive SDK does not have methods for retrieving files by path
111
-			// Instead we must find the id of the parent folder of the file
112
-			$parentId = $this->getDriveFile('')->getId();
113
-			$folderNames = explode('/', $path);
114
-			$path = '';
115
-			// Loop through each folder of this path to get to the file
116
-			foreach ($folderNames as $name) {
117
-				// Reconstruct path from beginning
118
-				if ($path === '') {
119
-					$path .= $name;
120
-				} else {
121
-					$path .= '/'.$name;
122
-				}
123
-				if (isset($this->driveFiles[$path])) {
124
-					$parentId = $this->driveFiles[$path]->getId();
125
-				} else {
126
-					$q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
127
-					$result = $this->service->files->listFiles(array('q' => $q))->getItems();
128
-					if (!empty($result)) {
129
-						// Google Drive allows files with the same name, ownCloud doesn't
130
-						if (count($result) > 1) {
131
-							$this->onDuplicateFileDetected($path);
132
-							return false;
133
-						} else {
134
-							$file = current($result);
135
-							$this->driveFiles[$path] = $file;
136
-							$parentId = $file->getId();
137
-						}
138
-					} else {
139
-						// Google Docs have no extension in their title, so try without extension
140
-						$pos = strrpos($path, '.');
141
-						if ($pos !== false) {
142
-							$pathWithoutExt = substr($path, 0, $pos);
143
-							$file = $this->getDriveFile($pathWithoutExt);
144
-							if ($file && $this->isGoogleDocFile($file)) {
145
-								// Switch cached Google_Service_Drive_DriveFile to the correct index
146
-								unset($this->driveFiles[$pathWithoutExt]);
147
-								$this->driveFiles[$path] = $file;
148
-								$parentId = $file->getId();
149
-							} else {
150
-								return false;
151
-							}
152
-						} else {
153
-							return false;
154
-						}
155
-					}
156
-				}
157
-			}
158
-			return $this->driveFiles[$path];
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * Set the Google_Service_Drive_DriveFile object in the cache
164
-	 * @param string $path
165
-	 * @param \Google_Service_Drive_DriveFile|false $file
166
-	 */
167
-	private function setDriveFile($path, $file) {
168
-		$path = trim($path, '/');
169
-		$this->driveFiles[$path] = $file;
170
-		if ($file === false) {
171
-			// Remove all children
172
-			$len = strlen($path);
173
-			foreach ($this->driveFiles as $key => $file) {
174
-				if (substr($key, 0, $len) === $path) {
175
-					unset($this->driveFiles[$key]);
176
-				}
177
-			}
178
-		}
179
-	}
180
-
181
-	/**
182
-	 * Write a log message to inform about duplicate file names
183
-	 * @param string $path
184
-	 */
185
-	private function onDuplicateFileDetected($path) {
186
-		$about = $this->service->about->get();
187
-		$user = $about->getName();
188
-		\OCP\Util::writeLog('files_external',
189
-			'Ignoring duplicate file name: '.$path.' on Google Drive for Google user: '.$user,
190
-			\OCP\Util::INFO
191
-		);
192
-	}
193
-
194
-	/**
195
-	 * Generate file extension for a Google Doc, choosing Open Document formats for download
196
-	 * @param string $mimetype
197
-	 * @return string
198
-	 */
199
-	private function getGoogleDocExtension($mimetype) {
200
-		if ($mimetype === self::DOCUMENT) {
201
-			return 'odt';
202
-		} else if ($mimetype === self::SPREADSHEET) {
203
-			return 'ods';
204
-		} else if ($mimetype === self::DRAWING) {
205
-			return 'jpg';
206
-		} else if ($mimetype === self::PRESENTATION) {
207
-			// Download as .odp is not available
208
-			return 'pdf';
209
-		} else {
210
-			return '';
211
-		}
212
-	}
213
-
214
-	/**
215
-	 * Returns whether the given drive file is a Google Doc file
216
-	 *
217
-	 * @param \Google_Service_Drive_DriveFile
218
-	 *
219
-	 * @return true if the file is a Google Doc file, false otherwise
220
-	 */
221
-	private function isGoogleDocFile($file) {
222
-		return $this->getGoogleDocExtension($file->getMimeType()) !== '';
223
-	}
224
-
225
-	public function mkdir($path) {
226
-		if (!$this->is_dir($path)) {
227
-			$parentFolder = $this->getDriveFile(dirname($path));
228
-			if ($parentFolder) {
229
-				$folder = new \Google_Service_Drive_DriveFile();
230
-				$folder->setTitle(basename($path));
231
-				$folder->setMimeType(self::FOLDER);
232
-				$parent = new \Google_Service_Drive_ParentReference();
233
-				$parent->setId($parentFolder->getId());
234
-				$folder->setParents(array($parent));
235
-				$result = $this->service->files->insert($folder);
236
-				if ($result) {
237
-					$this->setDriveFile($path, $result);
238
-				}
239
-				return (bool)$result;
240
-			}
241
-		}
242
-		return false;
243
-	}
244
-
245
-	public function rmdir($path) {
246
-		if (!$this->isDeletable($path)) {
247
-			return false;
248
-		}
249
-		if (trim($path, '/') === '') {
250
-			$dir = $this->opendir($path);
251
-			if(is_resource($dir)) {
252
-				while (($file = readdir($dir)) !== false) {
253
-					if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254
-						if (!$this->unlink($path.'/'.$file)) {
255
-							return false;
256
-						}
257
-					}
258
-				}
259
-				closedir($dir);
260
-			}
261
-			$this->driveFiles = array();
262
-			return true;
263
-		} else {
264
-			return $this->unlink($path);
265
-		}
266
-	}
267
-
268
-	public function opendir($path) {
269
-		$folder = $this->getDriveFile($path);
270
-		if ($folder) {
271
-			$files = array();
272
-			$duplicates = array();
273
-			$pageToken = true;
274
-			while ($pageToken) {
275
-				$params = array();
276
-				if ($pageToken !== true) {
277
-					$params['pageToken'] = $pageToken;
278
-				}
279
-				$params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
280
-				$children = $this->service->files->listFiles($params);
281
-				foreach ($children->getItems() as $child) {
282
-					$name = $child->getTitle();
283
-					// Check if this is a Google Doc i.e. no extension in name
284
-					$extension = $child->getFileExtension();
285
-					if (empty($extension)) {
286
-						if ($child->getMimeType() === self::MAP) {
287
-							continue; // No method known to transfer map files, ignore it
288
-						} else if ($child->getMimeType() !== self::FOLDER) {
289
-							$name .= '.'.$this->getGoogleDocExtension($child->getMimeType());
290
-						}
291
-					}
292
-					if ($path === '') {
293
-						$filepath = $name;
294
-					} else {
295
-						$filepath = $path.'/'.$name;
296
-					}
297
-					// Google Drive allows files with the same name, ownCloud doesn't
298
-					// Prevent opendir() from returning any duplicate files
299
-					$key = array_search($name, $files);
300
-					if ($key !== false || isset($duplicates[$filepath])) {
301
-						if (!isset($duplicates[$filepath])) {
302
-							$duplicates[$filepath] = true;
303
-							$this->setDriveFile($filepath, false);
304
-							unset($files[$key]);
305
-							$this->onDuplicateFileDetected($filepath);
306
-						}
307
-					} else {
308
-						// Cache the Google_Service_Drive_DriveFile for future use
309
-						$this->setDriveFile($filepath, $child);
310
-						$files[] = $name;
311
-					}
312
-				}
313
-				$pageToken = $children->getNextPageToken();
314
-			}
315
-			return IteratorDirectory::wrap($files);
316
-		} else {
317
-			return false;
318
-		}
319
-	}
320
-
321
-	public function stat($path) {
322
-		$file = $this->getDriveFile($path);
323
-		if ($file) {
324
-			$stat = array();
325
-			if ($this->filetype($path) === 'dir') {
326
-				$stat['size'] = 0;
327
-			} else {
328
-				// Check if this is a Google Doc
329
-				if ($this->isGoogleDocFile($file)) {
330
-					// Return unknown file size
331
-					$stat['size'] = \OCP\Files\FileInfo::SPACE_UNKNOWN;
332
-				} else {
333
-					$stat['size'] = $file->getFileSize();
334
-				}
335
-			}
336
-			$stat['atime'] = strtotime($file->getLastViewedByMeDate());
337
-			$stat['mtime'] = strtotime($file->getModifiedDate());
338
-			$stat['ctime'] = strtotime($file->getCreatedDate());
339
-			return $stat;
340
-		} else {
341
-			return false;
342
-		}
343
-	}
344
-
345
-	public function filetype($path) {
346
-		if ($path === '') {
347
-			return 'dir';
348
-		} else {
349
-			$file = $this->getDriveFile($path);
350
-			if ($file) {
351
-				if ($file->getMimeType() === self::FOLDER) {
352
-					return 'dir';
353
-				} else {
354
-					return 'file';
355
-				}
356
-			} else {
357
-				return false;
358
-			}
359
-		}
360
-	}
361
-
362
-	public function isUpdatable($path) {
363
-		$file = $this->getDriveFile($path);
364
-		if ($file) {
365
-			return $file->getEditable();
366
-		} else {
367
-			return false;
368
-		}
369
-	}
370
-
371
-	public function file_exists($path) {
372
-		return (bool)$this->getDriveFile($path);
373
-	}
374
-
375
-	public function unlink($path) {
376
-		$file = $this->getDriveFile($path);
377
-		if ($file) {
378
-			$result = $this->service->files->trash($file->getId());
379
-			if ($result) {
380
-				$this->setDriveFile($path, false);
381
-			}
382
-			return (bool)$result;
383
-		} else {
384
-			return false;
385
-		}
386
-	}
387
-
388
-	public function rename($path1, $path2) {
389
-		$file = $this->getDriveFile($path1);
390
-		if ($file) {
391
-			$newFile = $this->getDriveFile($path2);
392
-			if (dirname($path1) === dirname($path2)) {
393
-				if ($newFile) {
394
-					// rename to the name of the target file, could be an office file without extension
395
-					$file->setTitle($newFile->getTitle());
396
-				} else {
397
-					$file->setTitle(basename(($path2)));
398
-				}
399
-			} else {
400
-				// Change file parent
401
-				$parentFolder2 = $this->getDriveFile(dirname($path2));
402
-				if ($parentFolder2) {
403
-					$parent = new \Google_Service_Drive_ParentReference();
404
-					$parent->setId($parentFolder2->getId());
405
-					$file->setParents(array($parent));
406
-				} else {
407
-					return false;
408
-				}
409
-			}
410
-			// We need to get the object for the existing file with the same
411
-			// name (if there is one) before we do the patch. If oldfile
412
-			// exists and is a directory we have to delete it before we
413
-			// do the rename too.
414
-			$oldfile = $this->getDriveFile($path2);
415
-			if ($oldfile && $this->is_dir($path2)) {
416
-				$this->rmdir($path2);
417
-				$oldfile = false;
418
-			}
419
-			$result = $this->service->files->patch($file->getId(), $file);
420
-			if ($result) {
421
-				$this->setDriveFile($path1, false);
422
-				$this->setDriveFile($path2, $result);
423
-				if ($oldfile && $newFile) {
424
-					// only delete if they have a different id (same id can happen for part files)
425
-					if ($newFile->getId() !== $oldfile->getId()) {
426
-						$this->service->files->delete($oldfile->getId());
427
-					}
428
-				}
429
-			}
430
-			return (bool)$result;
431
-		} else {
432
-			return false;
433
-		}
434
-	}
435
-
436
-	public function fopen($path, $mode) {
437
-		$pos = strrpos($path, '.');
438
-		if ($pos !== false) {
439
-			$ext = substr($path, $pos);
440
-		} else {
441
-			$ext = '';
442
-		}
443
-		switch ($mode) {
444
-			case 'r':
445
-			case 'rb':
446
-				$file = $this->getDriveFile($path);
447
-				if ($file) {
448
-					$exportLinks = $file->getExportLinks();
449
-					$mimetype = $this->getMimeType($path);
450
-					$downloadUrl = null;
451
-					if ($exportLinks && isset($exportLinks[$mimetype])) {
452
-						$downloadUrl = $exportLinks[$mimetype];
453
-					} else {
454
-						$downloadUrl = $file->getDownloadUrl();
455
-					}
456
-					if (isset($downloadUrl)) {
457
-						$request = new \Google_Http_Request($downloadUrl, 'GET', null, null);
458
-						$httpRequest = $this->client->getAuth()->sign($request);
459
-						// the library's service doesn't support streaming, so we use Guzzle instead
460
-						$client = \OC::$server->getHTTPClientService()->newClient();
461
-						try {
462
-							$response = $client->get($downloadUrl, [
463
-								'headers' => $httpRequest->getRequestHeaders(),
464
-								'stream' => true,
465
-								'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466
-							]);
467
-						} catch (RequestException $e) {
468
-							if(!is_null($e->getResponse())) {
469
-								if ($e->getResponse()->getStatusCode() === 404) {
470
-									return false;
471
-								} else {
472
-									throw $e;
473
-								}
474
-							} else {
475
-								throw $e;
476
-							}
477
-						}
478
-
479
-						$handle = $response->getBody();
480
-						return RetryWrapper::wrap($handle);
481
-					}
482
-				}
483
-				return false;
484
-			case 'w':
485
-			case 'wb':
486
-			case 'a':
487
-			case 'ab':
488
-			case 'r+':
489
-			case 'w+':
490
-			case 'wb+':
491
-			case 'a+':
492
-			case 'x':
493
-			case 'x+':
494
-			case 'c':
495
-			case 'c+':
496
-				$tmpFile = \OCP\Files::tmpFile($ext);
497
-				if ($this->file_exists($path)) {
498
-					$source = $this->fopen($path, 'rb');
499
-					file_put_contents($tmpFile, $source);
500
-				}
501
-				$handle = fopen($tmpFile, $mode);
502
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
503
-					$this->writeBack($tmpFile, $path);
504
-				});
505
-		}
506
-	}
507
-
508
-	public function writeBack($tmpFile, $path) {
509
-		$parentFolder = $this->getDriveFile(dirname($path));
510
-		if ($parentFolder) {
511
-			$mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
512
-			$params = array(
513
-				'mimeType' => $mimetype,
514
-				'uploadType' => 'media'
515
-			);
516
-			$result = false;
517
-
518
-			$chunkSizeBytes = 10 * 1024 * 1024;
519
-
520
-			$useChunking = false;
521
-			$size = filesize($tmpFile);
522
-			if ($size > $chunkSizeBytes) {
523
-				$useChunking = true;
524
-			} else {
525
-				$params['data'] = file_get_contents($tmpFile);
526
-			}
527
-
528
-			if ($this->file_exists($path)) {
529
-				$file = $this->getDriveFile($path);
530
-				$this->client->setDefer($useChunking);
531
-				$request = $this->service->files->update($file->getId(), $file, $params);
532
-			} else {
533
-				$file = new \Google_Service_Drive_DriveFile();
534
-				$file->setTitle(basename($path));
535
-				$file->setMimeType($mimetype);
536
-				$parent = new \Google_Service_Drive_ParentReference();
537
-				$parent->setId($parentFolder->getId());
538
-				$file->setParents(array($parent));
539
-				$this->client->setDefer($useChunking);
540
-				$request = $this->service->files->insert($file, $params);
541
-			}
542
-
543
-			if ($useChunking) {
544
-				// Create a media file upload to represent our upload process.
545
-				$media = new \Google_Http_MediaFileUpload(
546
-					$this->client,
547
-					$request,
548
-					'text/plain',
549
-					null,
550
-					true,
551
-					$chunkSizeBytes
552
-				);
553
-				$media->setFileSize($size);
554
-
555
-				// Upload the various chunks. $status will be false until the process is
556
-				// complete.
557
-				$status = false;
558
-				$handle = fopen($tmpFile, 'rb');
559
-				while (!$status && !feof($handle)) {
560
-					$chunk = fread($handle, $chunkSizeBytes);
561
-					$status = $media->nextChunk($chunk);
562
-				}
563
-
564
-				// The final value of $status will be the data from the API for the object
565
-				// that has been uploaded.
566
-				$result = false;
567
-				if ($status !== false) {
568
-					$result = $status;
569
-				}
570
-
571
-				fclose($handle);
572
-			} else {
573
-				$result = $request;
574
-			}
575
-
576
-			// Reset to the client to execute requests immediately in the future.
577
-			$this->client->setDefer(false);
578
-
579
-			if ($result) {
580
-				$this->setDriveFile($path, $result);
581
-			}
582
-		}
583
-	}
584
-
585
-	public function getMimeType($path) {
586
-		$file = $this->getDriveFile($path);
587
-		if ($file) {
588
-			$mimetype = $file->getMimeType();
589
-			// Convert Google Doc mimetypes, choosing Open Document formats for download
590
-			if ($mimetype === self::FOLDER) {
591
-				return 'httpd/unix-directory';
592
-			} else if ($mimetype === self::DOCUMENT) {
593
-				return 'application/vnd.oasis.opendocument.text';
594
-			} else if ($mimetype === self::SPREADSHEET) {
595
-				return 'application/x-vnd.oasis.opendocument.spreadsheet';
596
-			} else if ($mimetype === self::DRAWING) {
597
-				return 'image/jpeg';
598
-			} else if ($mimetype === self::PRESENTATION) {
599
-				// Download as .odp is not available
600
-				return 'application/pdf';
601
-			} else {
602
-				// use extension-based detection, could be an encrypted file
603
-				return parent::getMimeType($path);
604
-			}
605
-		} else {
606
-			return false;
607
-		}
608
-	}
609
-
610
-	public function free_space($path) {
611
-		$about = $this->service->about->get();
612
-		return $about->getQuotaBytesTotal() - $about->getQuotaBytesUsed();
613
-	}
614
-
615
-	public function touch($path, $mtime = null) {
616
-		$file = $this->getDriveFile($path);
617
-		$result = false;
618
-		if ($file) {
619
-			if (isset($mtime)) {
620
-				// This is just RFC3339, but frustratingly, GDrive's API *requires*
621
-				// the fractions portion be present, while no handy PHP constant
622
-				// for RFC3339 or ISO8601 includes it. So we do it ourselves.
623
-				$file->setModifiedDate(date('Y-m-d\TH:i:s.uP', $mtime));
624
-				$result = $this->service->files->patch($file->getId(), $file, array(
625
-					'setModifiedDate' => true,
626
-				));
627
-			} else {
628
-				$result = $this->service->files->touch($file->getId());
629
-			}
630
-		} else {
631
-			$parentFolder = $this->getDriveFile(dirname($path));
632
-			if ($parentFolder) {
633
-				$file = new \Google_Service_Drive_DriveFile();
634
-				$file->setTitle(basename($path));
635
-				$parent = new \Google_Service_Drive_ParentReference();
636
-				$parent->setId($parentFolder->getId());
637
-				$file->setParents(array($parent));
638
-				$result = $this->service->files->insert($file);
639
-			}
640
-		}
641
-		if ($result) {
642
-			$this->setDriveFile($path, $result);
643
-		}
644
-		return (bool)$result;
645
-	}
646
-
647
-	public function test() {
648
-		if ($this->free_space('')) {
649
-			return true;
650
-		}
651
-		return false;
652
-	}
653
-
654
-	public function hasUpdated($path, $time) {
655
-		$appConfig = \OC::$server->getAppConfig();
656
-		if ($this->is_file($path)) {
657
-			return parent::hasUpdated($path, $time);
658
-		} else {
659
-			// Google Drive doesn't change modified times of folders when files inside are updated
660
-			// Instead we use the Changes API to see if folders have been updated, and it's a pain
661
-			$folder = $this->getDriveFile($path);
662
-			if ($folder) {
663
-				$result = false;
664
-				$folderId = $folder->getId();
665
-				$startChangeId = $appConfig->getValue('files_external', $this->getId().'cId');
666
-				$params = array(
667
-					'includeDeleted' => true,
668
-					'includeSubscribed' => true,
669
-				);
670
-				if (isset($startChangeId)) {
671
-					$startChangeId = (int)$startChangeId;
672
-					$largestChangeId = $startChangeId;
673
-					$params['startChangeId'] = $startChangeId + 1;
674
-				} else {
675
-					$largestChangeId = 0;
676
-				}
677
-				$pageToken = true;
678
-				while ($pageToken) {
679
-					if ($pageToken !== true) {
680
-						$params['pageToken'] = $pageToken;
681
-					}
682
-					$changes = $this->service->changes->listChanges($params);
683
-					if ($largestChangeId === 0 || $largestChangeId === $startChangeId) {
684
-						$largestChangeId = $changes->getLargestChangeId();
685
-					}
686
-					if (isset($startChangeId)) {
687
-						// Check if a file in this folder has been updated
688
-						// There is no way to filter by folder at the API level...
689
-						foreach ($changes->getItems() as $change) {
690
-							$file = $change->getFile();
691
-							if ($file) {
692
-								foreach ($file->getParents() as $parent) {
693
-									if ($parent->getId() === $folderId) {
694
-										$result = true;
695
-									// Check if there are changes in different folders
696
-									} else if ($change->getId() <= $largestChangeId) {
697
-										// Decrement id so this change is fetched when called again
698
-										$largestChangeId = $change->getId();
699
-										$largestChangeId--;
700
-									}
701
-								}
702
-							}
703
-						}
704
-						$pageToken = $changes->getNextPageToken();
705
-					} else {
706
-						// Assuming the initial scan just occurred and changes are negligible
707
-						break;
708
-					}
709
-				}
710
-				$appConfig->setValue('files_external', $this->getId().'cId', $largestChangeId);
711
-				return $result;
712
-			}
713
-		}
714
-		return false;
715
-	}
716
-
717
-	/**
718
-	 * check if curl is installed
719
-	 */
720
-	public static function checkDependencies() {
721
-		return true;
722
-	}
49
+    private $client;
50
+    private $id;
51
+    private $service;
52
+    private $driveFiles;
53
+
54
+    // Google Doc mimetypes
55
+    const FOLDER = 'application/vnd.google-apps.folder';
56
+    const DOCUMENT = 'application/vnd.google-apps.document';
57
+    const SPREADSHEET = 'application/vnd.google-apps.spreadsheet';
58
+    const DRAWING = 'application/vnd.google-apps.drawing';
59
+    const PRESENTATION = 'application/vnd.google-apps.presentation';
60
+    const MAP = 'application/vnd.google-apps.map';
61
+
62
+    public function __construct($params) {
63
+        if (isset($params['configured']) && $params['configured'] === 'true'
64
+            && isset($params['client_id']) && isset($params['client_secret'])
65
+            && isset($params['token'])
66
+        ) {
67
+            $this->client = new \Google_Client();
68
+            $this->client->setClientId($params['client_id']);
69
+            $this->client->setClientSecret($params['client_secret']);
70
+            $this->client->setScopes(array('https://www.googleapis.com/auth/drive'));
71
+            $this->client->setAccessToken($params['token']);
72
+            // if curl isn't available we're likely to run into
73
+            // https://github.com/google/google-api-php-client/issues/59
74
+            // - disable gzip to avoid it.
75
+            if (!function_exists('curl_version') || !function_exists('curl_exec')) {
76
+                $this->client->setClassConfig("Google_Http_Request", "disable_gzip", true);
77
+            }
78
+            // note: API connection is lazy
79
+            $this->service = new \Google_Service_Drive($this->client);
80
+            $token = json_decode($params['token'], true);
81
+            $this->id = 'google::'.substr($params['client_id'], 0, 30).$token['created'];
82
+        } else {
83
+            throw new \Exception('Creating Google storage failed');
84
+        }
85
+    }
86
+
87
+    public function getId() {
88
+        return $this->id;
89
+    }
90
+
91
+    /**
92
+     * Get the Google_Service_Drive_DriveFile object for the specified path.
93
+     * Returns false on failure.
94
+     * @param string $path
95
+     * @return \Google_Service_Drive_DriveFile|false
96
+     */
97
+    private function getDriveFile($path) {
98
+        // Remove leading and trailing slashes
99
+        $path = trim($path, '/');
100
+        if ($path === '.') {
101
+            $path = '';
102
+        }
103
+        if (isset($this->driveFiles[$path])) {
104
+            return $this->driveFiles[$path];
105
+        } else if ($path === '') {
106
+            $root = $this->service->files->get('root');
107
+            $this->driveFiles[$path] = $root;
108
+            return $root;
109
+        } else {
110
+            // Google Drive SDK does not have methods for retrieving files by path
111
+            // Instead we must find the id of the parent folder of the file
112
+            $parentId = $this->getDriveFile('')->getId();
113
+            $folderNames = explode('/', $path);
114
+            $path = '';
115
+            // Loop through each folder of this path to get to the file
116
+            foreach ($folderNames as $name) {
117
+                // Reconstruct path from beginning
118
+                if ($path === '') {
119
+                    $path .= $name;
120
+                } else {
121
+                    $path .= '/'.$name;
122
+                }
123
+                if (isset($this->driveFiles[$path])) {
124
+                    $parentId = $this->driveFiles[$path]->getId();
125
+                } else {
126
+                    $q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
127
+                    $result = $this->service->files->listFiles(array('q' => $q))->getItems();
128
+                    if (!empty($result)) {
129
+                        // Google Drive allows files with the same name, ownCloud doesn't
130
+                        if (count($result) > 1) {
131
+                            $this->onDuplicateFileDetected($path);
132
+                            return false;
133
+                        } else {
134
+                            $file = current($result);
135
+                            $this->driveFiles[$path] = $file;
136
+                            $parentId = $file->getId();
137
+                        }
138
+                    } else {
139
+                        // Google Docs have no extension in their title, so try without extension
140
+                        $pos = strrpos($path, '.');
141
+                        if ($pos !== false) {
142
+                            $pathWithoutExt = substr($path, 0, $pos);
143
+                            $file = $this->getDriveFile($pathWithoutExt);
144
+                            if ($file && $this->isGoogleDocFile($file)) {
145
+                                // Switch cached Google_Service_Drive_DriveFile to the correct index
146
+                                unset($this->driveFiles[$pathWithoutExt]);
147
+                                $this->driveFiles[$path] = $file;
148
+                                $parentId = $file->getId();
149
+                            } else {
150
+                                return false;
151
+                            }
152
+                        } else {
153
+                            return false;
154
+                        }
155
+                    }
156
+                }
157
+            }
158
+            return $this->driveFiles[$path];
159
+        }
160
+    }
161
+
162
+    /**
163
+     * Set the Google_Service_Drive_DriveFile object in the cache
164
+     * @param string $path
165
+     * @param \Google_Service_Drive_DriveFile|false $file
166
+     */
167
+    private function setDriveFile($path, $file) {
168
+        $path = trim($path, '/');
169
+        $this->driveFiles[$path] = $file;
170
+        if ($file === false) {
171
+            // Remove all children
172
+            $len = strlen($path);
173
+            foreach ($this->driveFiles as $key => $file) {
174
+                if (substr($key, 0, $len) === $path) {
175
+                    unset($this->driveFiles[$key]);
176
+                }
177
+            }
178
+        }
179
+    }
180
+
181
+    /**
182
+     * Write a log message to inform about duplicate file names
183
+     * @param string $path
184
+     */
185
+    private function onDuplicateFileDetected($path) {
186
+        $about = $this->service->about->get();
187
+        $user = $about->getName();
188
+        \OCP\Util::writeLog('files_external',
189
+            'Ignoring duplicate file name: '.$path.' on Google Drive for Google user: '.$user,
190
+            \OCP\Util::INFO
191
+        );
192
+    }
193
+
194
+    /**
195
+     * Generate file extension for a Google Doc, choosing Open Document formats for download
196
+     * @param string $mimetype
197
+     * @return string
198
+     */
199
+    private function getGoogleDocExtension($mimetype) {
200
+        if ($mimetype === self::DOCUMENT) {
201
+            return 'odt';
202
+        } else if ($mimetype === self::SPREADSHEET) {
203
+            return 'ods';
204
+        } else if ($mimetype === self::DRAWING) {
205
+            return 'jpg';
206
+        } else if ($mimetype === self::PRESENTATION) {
207
+            // Download as .odp is not available
208
+            return 'pdf';
209
+        } else {
210
+            return '';
211
+        }
212
+    }
213
+
214
+    /**
215
+     * Returns whether the given drive file is a Google Doc file
216
+     *
217
+     * @param \Google_Service_Drive_DriveFile
218
+     *
219
+     * @return true if the file is a Google Doc file, false otherwise
220
+     */
221
+    private function isGoogleDocFile($file) {
222
+        return $this->getGoogleDocExtension($file->getMimeType()) !== '';
223
+    }
224
+
225
+    public function mkdir($path) {
226
+        if (!$this->is_dir($path)) {
227
+            $parentFolder = $this->getDriveFile(dirname($path));
228
+            if ($parentFolder) {
229
+                $folder = new \Google_Service_Drive_DriveFile();
230
+                $folder->setTitle(basename($path));
231
+                $folder->setMimeType(self::FOLDER);
232
+                $parent = new \Google_Service_Drive_ParentReference();
233
+                $parent->setId($parentFolder->getId());
234
+                $folder->setParents(array($parent));
235
+                $result = $this->service->files->insert($folder);
236
+                if ($result) {
237
+                    $this->setDriveFile($path, $result);
238
+                }
239
+                return (bool)$result;
240
+            }
241
+        }
242
+        return false;
243
+    }
244
+
245
+    public function rmdir($path) {
246
+        if (!$this->isDeletable($path)) {
247
+            return false;
248
+        }
249
+        if (trim($path, '/') === '') {
250
+            $dir = $this->opendir($path);
251
+            if(is_resource($dir)) {
252
+                while (($file = readdir($dir)) !== false) {
253
+                    if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254
+                        if (!$this->unlink($path.'/'.$file)) {
255
+                            return false;
256
+                        }
257
+                    }
258
+                }
259
+                closedir($dir);
260
+            }
261
+            $this->driveFiles = array();
262
+            return true;
263
+        } else {
264
+            return $this->unlink($path);
265
+        }
266
+    }
267
+
268
+    public function opendir($path) {
269
+        $folder = $this->getDriveFile($path);
270
+        if ($folder) {
271
+            $files = array();
272
+            $duplicates = array();
273
+            $pageToken = true;
274
+            while ($pageToken) {
275
+                $params = array();
276
+                if ($pageToken !== true) {
277
+                    $params['pageToken'] = $pageToken;
278
+                }
279
+                $params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
280
+                $children = $this->service->files->listFiles($params);
281
+                foreach ($children->getItems() as $child) {
282
+                    $name = $child->getTitle();
283
+                    // Check if this is a Google Doc i.e. no extension in name
284
+                    $extension = $child->getFileExtension();
285
+                    if (empty($extension)) {
286
+                        if ($child->getMimeType() === self::MAP) {
287
+                            continue; // No method known to transfer map files, ignore it
288
+                        } else if ($child->getMimeType() !== self::FOLDER) {
289
+                            $name .= '.'.$this->getGoogleDocExtension($child->getMimeType());
290
+                        }
291
+                    }
292
+                    if ($path === '') {
293
+                        $filepath = $name;
294
+                    } else {
295
+                        $filepath = $path.'/'.$name;
296
+                    }
297
+                    // Google Drive allows files with the same name, ownCloud doesn't
298
+                    // Prevent opendir() from returning any duplicate files
299
+                    $key = array_search($name, $files);
300
+                    if ($key !== false || isset($duplicates[$filepath])) {
301
+                        if (!isset($duplicates[$filepath])) {
302
+                            $duplicates[$filepath] = true;
303
+                            $this->setDriveFile($filepath, false);
304
+                            unset($files[$key]);
305
+                            $this->onDuplicateFileDetected($filepath);
306
+                        }
307
+                    } else {
308
+                        // Cache the Google_Service_Drive_DriveFile for future use
309
+                        $this->setDriveFile($filepath, $child);
310
+                        $files[] = $name;
311
+                    }
312
+                }
313
+                $pageToken = $children->getNextPageToken();
314
+            }
315
+            return IteratorDirectory::wrap($files);
316
+        } else {
317
+            return false;
318
+        }
319
+    }
320
+
321
+    public function stat($path) {
322
+        $file = $this->getDriveFile($path);
323
+        if ($file) {
324
+            $stat = array();
325
+            if ($this->filetype($path) === 'dir') {
326
+                $stat['size'] = 0;
327
+            } else {
328
+                // Check if this is a Google Doc
329
+                if ($this->isGoogleDocFile($file)) {
330
+                    // Return unknown file size
331
+                    $stat['size'] = \OCP\Files\FileInfo::SPACE_UNKNOWN;
332
+                } else {
333
+                    $stat['size'] = $file->getFileSize();
334
+                }
335
+            }
336
+            $stat['atime'] = strtotime($file->getLastViewedByMeDate());
337
+            $stat['mtime'] = strtotime($file->getModifiedDate());
338
+            $stat['ctime'] = strtotime($file->getCreatedDate());
339
+            return $stat;
340
+        } else {
341
+            return false;
342
+        }
343
+    }
344
+
345
+    public function filetype($path) {
346
+        if ($path === '') {
347
+            return 'dir';
348
+        } else {
349
+            $file = $this->getDriveFile($path);
350
+            if ($file) {
351
+                if ($file->getMimeType() === self::FOLDER) {
352
+                    return 'dir';
353
+                } else {
354
+                    return 'file';
355
+                }
356
+            } else {
357
+                return false;
358
+            }
359
+        }
360
+    }
361
+
362
+    public function isUpdatable($path) {
363
+        $file = $this->getDriveFile($path);
364
+        if ($file) {
365
+            return $file->getEditable();
366
+        } else {
367
+            return false;
368
+        }
369
+    }
370
+
371
+    public function file_exists($path) {
372
+        return (bool)$this->getDriveFile($path);
373
+    }
374
+
375
+    public function unlink($path) {
376
+        $file = $this->getDriveFile($path);
377
+        if ($file) {
378
+            $result = $this->service->files->trash($file->getId());
379
+            if ($result) {
380
+                $this->setDriveFile($path, false);
381
+            }
382
+            return (bool)$result;
383
+        } else {
384
+            return false;
385
+        }
386
+    }
387
+
388
+    public function rename($path1, $path2) {
389
+        $file = $this->getDriveFile($path1);
390
+        if ($file) {
391
+            $newFile = $this->getDriveFile($path2);
392
+            if (dirname($path1) === dirname($path2)) {
393
+                if ($newFile) {
394
+                    // rename to the name of the target file, could be an office file without extension
395
+                    $file->setTitle($newFile->getTitle());
396
+                } else {
397
+                    $file->setTitle(basename(($path2)));
398
+                }
399
+            } else {
400
+                // Change file parent
401
+                $parentFolder2 = $this->getDriveFile(dirname($path2));
402
+                if ($parentFolder2) {
403
+                    $parent = new \Google_Service_Drive_ParentReference();
404
+                    $parent->setId($parentFolder2->getId());
405
+                    $file->setParents(array($parent));
406
+                } else {
407
+                    return false;
408
+                }
409
+            }
410
+            // We need to get the object for the existing file with the same
411
+            // name (if there is one) before we do the patch. If oldfile
412
+            // exists and is a directory we have to delete it before we
413
+            // do the rename too.
414
+            $oldfile = $this->getDriveFile($path2);
415
+            if ($oldfile && $this->is_dir($path2)) {
416
+                $this->rmdir($path2);
417
+                $oldfile = false;
418
+            }
419
+            $result = $this->service->files->patch($file->getId(), $file);
420
+            if ($result) {
421
+                $this->setDriveFile($path1, false);
422
+                $this->setDriveFile($path2, $result);
423
+                if ($oldfile && $newFile) {
424
+                    // only delete if they have a different id (same id can happen for part files)
425
+                    if ($newFile->getId() !== $oldfile->getId()) {
426
+                        $this->service->files->delete($oldfile->getId());
427
+                    }
428
+                }
429
+            }
430
+            return (bool)$result;
431
+        } else {
432
+            return false;
433
+        }
434
+    }
435
+
436
+    public function fopen($path, $mode) {
437
+        $pos = strrpos($path, '.');
438
+        if ($pos !== false) {
439
+            $ext = substr($path, $pos);
440
+        } else {
441
+            $ext = '';
442
+        }
443
+        switch ($mode) {
444
+            case 'r':
445
+            case 'rb':
446
+                $file = $this->getDriveFile($path);
447
+                if ($file) {
448
+                    $exportLinks = $file->getExportLinks();
449
+                    $mimetype = $this->getMimeType($path);
450
+                    $downloadUrl = null;
451
+                    if ($exportLinks && isset($exportLinks[$mimetype])) {
452
+                        $downloadUrl = $exportLinks[$mimetype];
453
+                    } else {
454
+                        $downloadUrl = $file->getDownloadUrl();
455
+                    }
456
+                    if (isset($downloadUrl)) {
457
+                        $request = new \Google_Http_Request($downloadUrl, 'GET', null, null);
458
+                        $httpRequest = $this->client->getAuth()->sign($request);
459
+                        // the library's service doesn't support streaming, so we use Guzzle instead
460
+                        $client = \OC::$server->getHTTPClientService()->newClient();
461
+                        try {
462
+                            $response = $client->get($downloadUrl, [
463
+                                'headers' => $httpRequest->getRequestHeaders(),
464
+                                'stream' => true,
465
+                                'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466
+                            ]);
467
+                        } catch (RequestException $e) {
468
+                            if(!is_null($e->getResponse())) {
469
+                                if ($e->getResponse()->getStatusCode() === 404) {
470
+                                    return false;
471
+                                } else {
472
+                                    throw $e;
473
+                                }
474
+                            } else {
475
+                                throw $e;
476
+                            }
477
+                        }
478
+
479
+                        $handle = $response->getBody();
480
+                        return RetryWrapper::wrap($handle);
481
+                    }
482
+                }
483
+                return false;
484
+            case 'w':
485
+            case 'wb':
486
+            case 'a':
487
+            case 'ab':
488
+            case 'r+':
489
+            case 'w+':
490
+            case 'wb+':
491
+            case 'a+':
492
+            case 'x':
493
+            case 'x+':
494
+            case 'c':
495
+            case 'c+':
496
+                $tmpFile = \OCP\Files::tmpFile($ext);
497
+                if ($this->file_exists($path)) {
498
+                    $source = $this->fopen($path, 'rb');
499
+                    file_put_contents($tmpFile, $source);
500
+                }
501
+                $handle = fopen($tmpFile, $mode);
502
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
503
+                    $this->writeBack($tmpFile, $path);
504
+                });
505
+        }
506
+    }
507
+
508
+    public function writeBack($tmpFile, $path) {
509
+        $parentFolder = $this->getDriveFile(dirname($path));
510
+        if ($parentFolder) {
511
+            $mimetype = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
512
+            $params = array(
513
+                'mimeType' => $mimetype,
514
+                'uploadType' => 'media'
515
+            );
516
+            $result = false;
517
+
518
+            $chunkSizeBytes = 10 * 1024 * 1024;
519
+
520
+            $useChunking = false;
521
+            $size = filesize($tmpFile);
522
+            if ($size > $chunkSizeBytes) {
523
+                $useChunking = true;
524
+            } else {
525
+                $params['data'] = file_get_contents($tmpFile);
526
+            }
527
+
528
+            if ($this->file_exists($path)) {
529
+                $file = $this->getDriveFile($path);
530
+                $this->client->setDefer($useChunking);
531
+                $request = $this->service->files->update($file->getId(), $file, $params);
532
+            } else {
533
+                $file = new \Google_Service_Drive_DriveFile();
534
+                $file->setTitle(basename($path));
535
+                $file->setMimeType($mimetype);
536
+                $parent = new \Google_Service_Drive_ParentReference();
537
+                $parent->setId($parentFolder->getId());
538
+                $file->setParents(array($parent));
539
+                $this->client->setDefer($useChunking);
540
+                $request = $this->service->files->insert($file, $params);
541
+            }
542
+
543
+            if ($useChunking) {
544
+                // Create a media file upload to represent our upload process.
545
+                $media = new \Google_Http_MediaFileUpload(
546
+                    $this->client,
547
+                    $request,
548
+                    'text/plain',
549
+                    null,
550
+                    true,
551
+                    $chunkSizeBytes
552
+                );
553
+                $media->setFileSize($size);
554
+
555
+                // Upload the various chunks. $status will be false until the process is
556
+                // complete.
557
+                $status = false;
558
+                $handle = fopen($tmpFile, 'rb');
559
+                while (!$status && !feof($handle)) {
560
+                    $chunk = fread($handle, $chunkSizeBytes);
561
+                    $status = $media->nextChunk($chunk);
562
+                }
563
+
564
+                // The final value of $status will be the data from the API for the object
565
+                // that has been uploaded.
566
+                $result = false;
567
+                if ($status !== false) {
568
+                    $result = $status;
569
+                }
570
+
571
+                fclose($handle);
572
+            } else {
573
+                $result = $request;
574
+            }
575
+
576
+            // Reset to the client to execute requests immediately in the future.
577
+            $this->client->setDefer(false);
578
+
579
+            if ($result) {
580
+                $this->setDriveFile($path, $result);
581
+            }
582
+        }
583
+    }
584
+
585
+    public function getMimeType($path) {
586
+        $file = $this->getDriveFile($path);
587
+        if ($file) {
588
+            $mimetype = $file->getMimeType();
589
+            // Convert Google Doc mimetypes, choosing Open Document formats for download
590
+            if ($mimetype === self::FOLDER) {
591
+                return 'httpd/unix-directory';
592
+            } else if ($mimetype === self::DOCUMENT) {
593
+                return 'application/vnd.oasis.opendocument.text';
594
+            } else if ($mimetype === self::SPREADSHEET) {
595
+                return 'application/x-vnd.oasis.opendocument.spreadsheet';
596
+            } else if ($mimetype === self::DRAWING) {
597
+                return 'image/jpeg';
598
+            } else if ($mimetype === self::PRESENTATION) {
599
+                // Download as .odp is not available
600
+                return 'application/pdf';
601
+            } else {
602
+                // use extension-based detection, could be an encrypted file
603
+                return parent::getMimeType($path);
604
+            }
605
+        } else {
606
+            return false;
607
+        }
608
+    }
609
+
610
+    public function free_space($path) {
611
+        $about = $this->service->about->get();
612
+        return $about->getQuotaBytesTotal() - $about->getQuotaBytesUsed();
613
+    }
614
+
615
+    public function touch($path, $mtime = null) {
616
+        $file = $this->getDriveFile($path);
617
+        $result = false;
618
+        if ($file) {
619
+            if (isset($mtime)) {
620
+                // This is just RFC3339, but frustratingly, GDrive's API *requires*
621
+                // the fractions portion be present, while no handy PHP constant
622
+                // for RFC3339 or ISO8601 includes it. So we do it ourselves.
623
+                $file->setModifiedDate(date('Y-m-d\TH:i:s.uP', $mtime));
624
+                $result = $this->service->files->patch($file->getId(), $file, array(
625
+                    'setModifiedDate' => true,
626
+                ));
627
+            } else {
628
+                $result = $this->service->files->touch($file->getId());
629
+            }
630
+        } else {
631
+            $parentFolder = $this->getDriveFile(dirname($path));
632
+            if ($parentFolder) {
633
+                $file = new \Google_Service_Drive_DriveFile();
634
+                $file->setTitle(basename($path));
635
+                $parent = new \Google_Service_Drive_ParentReference();
636
+                $parent->setId($parentFolder->getId());
637
+                $file->setParents(array($parent));
638
+                $result = $this->service->files->insert($file);
639
+            }
640
+        }
641
+        if ($result) {
642
+            $this->setDriveFile($path, $result);
643
+        }
644
+        return (bool)$result;
645
+    }
646
+
647
+    public function test() {
648
+        if ($this->free_space('')) {
649
+            return true;
650
+        }
651
+        return false;
652
+    }
653
+
654
+    public function hasUpdated($path, $time) {
655
+        $appConfig = \OC::$server->getAppConfig();
656
+        if ($this->is_file($path)) {
657
+            return parent::hasUpdated($path, $time);
658
+        } else {
659
+            // Google Drive doesn't change modified times of folders when files inside are updated
660
+            // Instead we use the Changes API to see if folders have been updated, and it's a pain
661
+            $folder = $this->getDriveFile($path);
662
+            if ($folder) {
663
+                $result = false;
664
+                $folderId = $folder->getId();
665
+                $startChangeId = $appConfig->getValue('files_external', $this->getId().'cId');
666
+                $params = array(
667
+                    'includeDeleted' => true,
668
+                    'includeSubscribed' => true,
669
+                );
670
+                if (isset($startChangeId)) {
671
+                    $startChangeId = (int)$startChangeId;
672
+                    $largestChangeId = $startChangeId;
673
+                    $params['startChangeId'] = $startChangeId + 1;
674
+                } else {
675
+                    $largestChangeId = 0;
676
+                }
677
+                $pageToken = true;
678
+                while ($pageToken) {
679
+                    if ($pageToken !== true) {
680
+                        $params['pageToken'] = $pageToken;
681
+                    }
682
+                    $changes = $this->service->changes->listChanges($params);
683
+                    if ($largestChangeId === 0 || $largestChangeId === $startChangeId) {
684
+                        $largestChangeId = $changes->getLargestChangeId();
685
+                    }
686
+                    if (isset($startChangeId)) {
687
+                        // Check if a file in this folder has been updated
688
+                        // There is no way to filter by folder at the API level...
689
+                        foreach ($changes->getItems() as $change) {
690
+                            $file = $change->getFile();
691
+                            if ($file) {
692
+                                foreach ($file->getParents() as $parent) {
693
+                                    if ($parent->getId() === $folderId) {
694
+                                        $result = true;
695
+                                    // Check if there are changes in different folders
696
+                                    } else if ($change->getId() <= $largestChangeId) {
697
+                                        // Decrement id so this change is fetched when called again
698
+                                        $largestChangeId = $change->getId();
699
+                                        $largestChangeId--;
700
+                                    }
701
+                                }
702
+                            }
703
+                        }
704
+                        $pageToken = $changes->getNextPageToken();
705
+                    } else {
706
+                        // Assuming the initial scan just occurred and changes are negligible
707
+                        break;
708
+                    }
709
+                }
710
+                $appConfig->setValue('files_external', $this->getId().'cId', $largestChangeId);
711
+                return $result;
712
+            }
713
+        }
714
+        return false;
715
+    }
716
+
717
+    /**
718
+     * check if curl is installed
719
+     */
720
+    public static function checkDependencies() {
721
+        return true;
722
+    }
723 723
 
724 724
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 				if (isset($this->driveFiles[$path])) {
124 124
 					$parentId = $this->driveFiles[$path]->getId();
125 125
 				} else {
126
-					$q = "title='" . str_replace("'","\\'", $name) . "' and '" . str_replace("'","\\'", $parentId) . "' in parents and trashed = false";
126
+					$q = "title='".str_replace("'", "\\'", $name)."' and '".str_replace("'", "\\'", $parentId)."' in parents and trashed = false";
127 127
 					$result = $this->service->files->listFiles(array('q' => $q))->getItems();
128 128
 					if (!empty($result)) {
129 129
 						// Google Drive allows files with the same name, ownCloud doesn't
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 				if ($result) {
237 237
 					$this->setDriveFile($path, $result);
238 238
 				}
239
-				return (bool)$result;
239
+				return (bool) $result;
240 240
 			}
241 241
 		}
242 242
 		return false;
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		}
249 249
 		if (trim($path, '/') === '') {
250 250
 			$dir = $this->opendir($path);
251
-			if(is_resource($dir)) {
251
+			if (is_resource($dir)) {
252 252
 				while (($file = readdir($dir)) !== false) {
253 253
 					if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
254 254
 						if (!$this->unlink($path.'/'.$file)) {
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 				if ($pageToken !== true) {
277 277
 					$params['pageToken'] = $pageToken;
278 278
 				}
279
-				$params['q'] = "'" . str_replace("'","\\'", $folder->getId()) . "' in parents and trashed = false";
279
+				$params['q'] = "'".str_replace("'", "\\'", $folder->getId())."' in parents and trashed = false";
280 280
 				$children = $this->service->files->listFiles($params);
281 281
 				foreach ($children->getItems() as $child) {
282 282
 					$name = $child->getTitle();
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 	}
370 370
 
371 371
 	public function file_exists($path) {
372
-		return (bool)$this->getDriveFile($path);
372
+		return (bool) $this->getDriveFile($path);
373 373
 	}
374 374
 
375 375
 	public function unlink($path) {
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 			if ($result) {
380 380
 				$this->setDriveFile($path, false);
381 381
 			}
382
-			return (bool)$result;
382
+			return (bool) $result;
383 383
 		} else {
384 384
 			return false;
385 385
 		}
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 					}
428 428
 				}
429 429
 			}
430
-			return (bool)$result;
430
+			return (bool) $result;
431 431
 		} else {
432 432
 			return false;
433 433
 		}
@@ -462,10 +462,10 @@  discard block
 block discarded – undo
462 462
 							$response = $client->get($downloadUrl, [
463 463
 								'headers' => $httpRequest->getRequestHeaders(),
464 464
 								'stream' => true,
465
-								'verify' => realpath(__DIR__ . '/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
465
+								'verify' => realpath(__DIR__.'/../../../3rdparty/google-api-php-client/src/Google/IO/cacerts.pem'),
466 466
 							]);
467 467
 						} catch (RequestException $e) {
468
-							if(!is_null($e->getResponse())) {
468
+							if (!is_null($e->getResponse())) {
469 469
 								if ($e->getResponse()->getStatusCode() === 404) {
470 470
 									return false;
471 471
 								} else {
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 					file_put_contents($tmpFile, $source);
500 500
 				}
501 501
 				$handle = fopen($tmpFile, $mode);
502
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
502
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
503 503
 					$this->writeBack($tmpFile, $path);
504 504
 				});
505 505
 		}
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 		if ($result) {
642 642
 			$this->setDriveFile($path, $result);
643 643
 		}
644
-		return (bool)$result;
644
+		return (bool) $result;
645 645
 	}
646 646
 
647 647
 	public function test() {
@@ -668,7 +668,7 @@  discard block
 block discarded – undo
668 668
 					'includeSubscribed' => true,
669 669
 				);
670 670
 				if (isset($startChangeId)) {
671
-					$startChangeId = (int)$startChangeId;
671
+					$startChangeId = (int) $startChangeId;
672 672
 					$largestChangeId = $startChangeId;
673 673
 					$params['startChangeId'] = $startChangeId + 1;
674 674
 				} else {
Please login to merge, or discard this patch.
lib/private/Archive/TAR.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -370,6 +370,7 @@
 block discarded – undo
370 370
 
371 371
 	/**
372 372
 	 * write back temporary files
373
+	 * @param string $path
373 374
 	 */
374 375
 	function writeBack($tmpFile, $path) {
375 376
 		$this->addFile($path, $tmpFile);
Please login to merge, or discard this patch.
Indentation   +331 added lines, -331 removed lines patch added patch discarded remove patch
@@ -36,355 +36,355 @@
 block discarded – undo
36 36
 use Icewind\Streams\CallbackWrapper;
37 37
 
38 38
 class TAR extends Archive {
39
-	const PLAIN = 0;
40
-	const GZIP = 1;
41
-	const BZIP = 2;
39
+    const PLAIN = 0;
40
+    const GZIP = 1;
41
+    const BZIP = 2;
42 42
 
43
-	private $fileList;
44
-	private $cachedHeaders;
43
+    private $fileList;
44
+    private $cachedHeaders;
45 45
 
46
-	/**
47
-	 * @var \Archive_Tar tar
48
-	 */
49
-	private $tar = null;
50
-	private $path;
46
+    /**
47
+     * @var \Archive_Tar tar
48
+     */
49
+    private $tar = null;
50
+    private $path;
51 51
 
52
-	/**
53
-	 * @param string $source
54
-	 */
55
-	function __construct($source) {
56
-		$types = array(null, 'gz', 'bz2');
57
-		$this->path = $source;
58
-		$this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
59
-	}
52
+    /**
53
+     * @param string $source
54
+     */
55
+    function __construct($source) {
56
+        $types = array(null, 'gz', 'bz2');
57
+        $this->path = $source;
58
+        $this->tar = new \Archive_Tar($source, $types[self::getTarType($source)]);
59
+    }
60 60
 
61
-	/**
62
-	 * try to detect the type of tar compression
63
-	 *
64
-	 * @param string $file
65
-	 * @return integer
66
-	 */
67
-	static public function getTarType($file) {
68
-		if (strpos($file, '.')) {
69
-			$extension = substr($file, strrpos($file, '.'));
70
-			switch ($extension) {
71
-				case '.gz':
72
-				case '.tgz':
73
-					return self::GZIP;
74
-				case '.bz':
75
-				case '.bz2':
76
-					return self::BZIP;
77
-				case '.tar':
78
-					return self::PLAIN;
79
-				default:
80
-					return self::PLAIN;
81
-			}
82
-		} else {
83
-			return self::PLAIN;
84
-		}
85
-	}
61
+    /**
62
+     * try to detect the type of tar compression
63
+     *
64
+     * @param string $file
65
+     * @return integer
66
+     */
67
+    static public function getTarType($file) {
68
+        if (strpos($file, '.')) {
69
+            $extension = substr($file, strrpos($file, '.'));
70
+            switch ($extension) {
71
+                case '.gz':
72
+                case '.tgz':
73
+                    return self::GZIP;
74
+                case '.bz':
75
+                case '.bz2':
76
+                    return self::BZIP;
77
+                case '.tar':
78
+                    return self::PLAIN;
79
+                default:
80
+                    return self::PLAIN;
81
+            }
82
+        } else {
83
+            return self::PLAIN;
84
+        }
85
+    }
86 86
 
87
-	/**
88
-	 * add an empty folder to the archive
89
-	 *
90
-	 * @param string $path
91
-	 * @return bool
92
-	 */
93
-	function addFolder($path) {
94
-		$tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
95
-		if (substr($path, -1, 1) != '/') {
96
-			$path .= '/';
97
-		}
98
-		if ($this->fileExists($path)) {
99
-			return false;
100
-		}
101
-		$parts = explode('/', $path);
102
-		$folder = $tmpBase;
103
-		foreach ($parts as $part) {
104
-			$folder .= '/' . $part;
105
-			if (!is_dir($folder)) {
106
-				mkdir($folder);
107
-			}
108
-		}
109
-		$result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase);
110
-		rmdir($tmpBase . $path);
111
-		$this->fileList = false;
112
-		$this->cachedHeaders = false;
113
-		return $result;
114
-	}
87
+    /**
88
+     * add an empty folder to the archive
89
+     *
90
+     * @param string $path
91
+     * @return bool
92
+     */
93
+    function addFolder($path) {
94
+        $tmpBase = \OC::$server->getTempManager()->getTemporaryFolder();
95
+        if (substr($path, -1, 1) != '/') {
96
+            $path .= '/';
97
+        }
98
+        if ($this->fileExists($path)) {
99
+            return false;
100
+        }
101
+        $parts = explode('/', $path);
102
+        $folder = $tmpBase;
103
+        foreach ($parts as $part) {
104
+            $folder .= '/' . $part;
105
+            if (!is_dir($folder)) {
106
+                mkdir($folder);
107
+            }
108
+        }
109
+        $result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase);
110
+        rmdir($tmpBase . $path);
111
+        $this->fileList = false;
112
+        $this->cachedHeaders = false;
113
+        return $result;
114
+    }
115 115
 
116
-	/**
117
-	 * add a file to the archive
118
-	 *
119
-	 * @param string $path
120
-	 * @param string $source either a local file or string data
121
-	 * @return bool
122
-	 */
123
-	function addFile($path, $source = '') {
124
-		if ($this->fileExists($path)) {
125
-			$this->remove($path);
126
-		}
127
-		if ($source and $source[0] == '/' and file_exists($source)) {
128
-			$source = file_get_contents($source);
129
-		}
130
-		$result = $this->tar->addString($path, $source);
131
-		$this->fileList = false;
132
-		$this->cachedHeaders = false;
133
-		return $result;
134
-	}
116
+    /**
117
+     * add a file to the archive
118
+     *
119
+     * @param string $path
120
+     * @param string $source either a local file or string data
121
+     * @return bool
122
+     */
123
+    function addFile($path, $source = '') {
124
+        if ($this->fileExists($path)) {
125
+            $this->remove($path);
126
+        }
127
+        if ($source and $source[0] == '/' and file_exists($source)) {
128
+            $source = file_get_contents($source);
129
+        }
130
+        $result = $this->tar->addString($path, $source);
131
+        $this->fileList = false;
132
+        $this->cachedHeaders = false;
133
+        return $result;
134
+    }
135 135
 
136
-	/**
137
-	 * rename a file or folder in the archive
138
-	 *
139
-	 * @param string $source
140
-	 * @param string $dest
141
-	 * @return bool
142
-	 */
143
-	function rename($source, $dest) {
144
-		//no proper way to delete, rename entire archive, rename file and remake archive
145
-		$tmp = \OCP\Files::tmpFolder();
146
-		$this->tar->extract($tmp);
147
-		rename($tmp . $source, $tmp . $dest);
148
-		$this->tar = null;
149
-		unlink($this->path);
150
-		$types = array(null, 'gz', 'bz');
151
-		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
152
-		$this->tar->createModify(array($tmp), '', $tmp . '/');
153
-		$this->fileList = false;
154
-		$this->cachedHeaders = false;
155
-		return true;
156
-	}
136
+    /**
137
+     * rename a file or folder in the archive
138
+     *
139
+     * @param string $source
140
+     * @param string $dest
141
+     * @return bool
142
+     */
143
+    function rename($source, $dest) {
144
+        //no proper way to delete, rename entire archive, rename file and remake archive
145
+        $tmp = \OCP\Files::tmpFolder();
146
+        $this->tar->extract($tmp);
147
+        rename($tmp . $source, $tmp . $dest);
148
+        $this->tar = null;
149
+        unlink($this->path);
150
+        $types = array(null, 'gz', 'bz');
151
+        $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
152
+        $this->tar->createModify(array($tmp), '', $tmp . '/');
153
+        $this->fileList = false;
154
+        $this->cachedHeaders = false;
155
+        return true;
156
+    }
157 157
 
158
-	/**
159
-	 * @param string $file
160
-	 */
161
-	private function getHeader($file) {
162
-		if (!$this->cachedHeaders) {
163
-			$this->cachedHeaders = $this->tar->listContent();
164
-		}
165
-		foreach ($this->cachedHeaders as $header) {
166
-			if ($file == $header['filename']
167
-				or $file . '/' == $header['filename']
168
-				or '/' . $file . '/' == $header['filename']
169
-				or '/' . $file == $header['filename']
170
-			) {
171
-				return $header;
172
-			}
173
-		}
174
-		return null;
175
-	}
158
+    /**
159
+     * @param string $file
160
+     */
161
+    private function getHeader($file) {
162
+        if (!$this->cachedHeaders) {
163
+            $this->cachedHeaders = $this->tar->listContent();
164
+        }
165
+        foreach ($this->cachedHeaders as $header) {
166
+            if ($file == $header['filename']
167
+                or $file . '/' == $header['filename']
168
+                or '/' . $file . '/' == $header['filename']
169
+                or '/' . $file == $header['filename']
170
+            ) {
171
+                return $header;
172
+            }
173
+        }
174
+        return null;
175
+    }
176 176
 
177
-	/**
178
-	 * get the uncompressed size of a file in the archive
179
-	 *
180
-	 * @param string $path
181
-	 * @return int
182
-	 */
183
-	function filesize($path) {
184
-		$stat = $this->getHeader($path);
185
-		return $stat['size'];
186
-	}
177
+    /**
178
+     * get the uncompressed size of a file in the archive
179
+     *
180
+     * @param string $path
181
+     * @return int
182
+     */
183
+    function filesize($path) {
184
+        $stat = $this->getHeader($path);
185
+        return $stat['size'];
186
+    }
187 187
 
188
-	/**
189
-	 * get the last modified time of a file in the archive
190
-	 *
191
-	 * @param string $path
192
-	 * @return int
193
-	 */
194
-	function mtime($path) {
195
-		$stat = $this->getHeader($path);
196
-		return $stat['mtime'];
197
-	}
188
+    /**
189
+     * get the last modified time of a file in the archive
190
+     *
191
+     * @param string $path
192
+     * @return int
193
+     */
194
+    function mtime($path) {
195
+        $stat = $this->getHeader($path);
196
+        return $stat['mtime'];
197
+    }
198 198
 
199
-	/**
200
-	 * get the files in a folder
201
-	 *
202
-	 * @param string $path
203
-	 * @return array
204
-	 */
205
-	function getFolder($path) {
206
-		$files = $this->getFiles();
207
-		$folderContent = array();
208
-		$pathLength = strlen($path);
209
-		foreach ($files as $file) {
210
-			if ($file[0] == '/') {
211
-				$file = substr($file, 1);
212
-			}
213
-			if (substr($file, 0, $pathLength) == $path and $file != $path) {
214
-				$result = substr($file, $pathLength);
215
-				if ($pos = strpos($result, '/')) {
216
-					$result = substr($result, 0, $pos + 1);
217
-				}
218
-				if (array_search($result, $folderContent) === false) {
219
-					$folderContent[] = $result;
220
-				}
221
-			}
222
-		}
223
-		return $folderContent;
224
-	}
199
+    /**
200
+     * get the files in a folder
201
+     *
202
+     * @param string $path
203
+     * @return array
204
+     */
205
+    function getFolder($path) {
206
+        $files = $this->getFiles();
207
+        $folderContent = array();
208
+        $pathLength = strlen($path);
209
+        foreach ($files as $file) {
210
+            if ($file[0] == '/') {
211
+                $file = substr($file, 1);
212
+            }
213
+            if (substr($file, 0, $pathLength) == $path and $file != $path) {
214
+                $result = substr($file, $pathLength);
215
+                if ($pos = strpos($result, '/')) {
216
+                    $result = substr($result, 0, $pos + 1);
217
+                }
218
+                if (array_search($result, $folderContent) === false) {
219
+                    $folderContent[] = $result;
220
+                }
221
+            }
222
+        }
223
+        return $folderContent;
224
+    }
225 225
 
226
-	/**
227
-	 * get all files in the archive
228
-	 *
229
-	 * @return array
230
-	 */
231
-	function getFiles() {
232
-		if ($this->fileList) {
233
-			return $this->fileList;
234
-		}
235
-		if (!$this->cachedHeaders) {
236
-			$this->cachedHeaders = $this->tar->listContent();
237
-		}
238
-		$files = array();
239
-		foreach ($this->cachedHeaders as $header) {
240
-			$files[] = $header['filename'];
241
-		}
242
-		$this->fileList = $files;
243
-		return $files;
244
-	}
226
+    /**
227
+     * get all files in the archive
228
+     *
229
+     * @return array
230
+     */
231
+    function getFiles() {
232
+        if ($this->fileList) {
233
+            return $this->fileList;
234
+        }
235
+        if (!$this->cachedHeaders) {
236
+            $this->cachedHeaders = $this->tar->listContent();
237
+        }
238
+        $files = array();
239
+        foreach ($this->cachedHeaders as $header) {
240
+            $files[] = $header['filename'];
241
+        }
242
+        $this->fileList = $files;
243
+        return $files;
244
+    }
245 245
 
246
-	/**
247
-	 * get the content of a file
248
-	 *
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	function getFile($path) {
253
-		return $this->tar->extractInString($path);
254
-	}
246
+    /**
247
+     * get the content of a file
248
+     *
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    function getFile($path) {
253
+        return $this->tar->extractInString($path);
254
+    }
255 255
 
256
-	/**
257
-	 * extract a single file from the archive
258
-	 *
259
-	 * @param string $path
260
-	 * @param string $dest
261
-	 * @return bool
262
-	 */
263
-	function extractFile($path, $dest) {
264
-		$tmp = \OCP\Files::tmpFolder();
265
-		if (!$this->fileExists($path)) {
266
-			return false;
267
-		}
268
-		if ($this->fileExists('/' . $path)) {
269
-			$success = $this->tar->extractList(array('/' . $path), $tmp);
270
-		} else {
271
-			$success = $this->tar->extractList(array($path), $tmp);
272
-		}
273
-		if ($success) {
274
-			rename($tmp . $path, $dest);
275
-		}
276
-		\OCP\Files::rmdirr($tmp);
277
-		return $success;
278
-	}
256
+    /**
257
+     * extract a single file from the archive
258
+     *
259
+     * @param string $path
260
+     * @param string $dest
261
+     * @return bool
262
+     */
263
+    function extractFile($path, $dest) {
264
+        $tmp = \OCP\Files::tmpFolder();
265
+        if (!$this->fileExists($path)) {
266
+            return false;
267
+        }
268
+        if ($this->fileExists('/' . $path)) {
269
+            $success = $this->tar->extractList(array('/' . $path), $tmp);
270
+        } else {
271
+            $success = $this->tar->extractList(array($path), $tmp);
272
+        }
273
+        if ($success) {
274
+            rename($tmp . $path, $dest);
275
+        }
276
+        \OCP\Files::rmdirr($tmp);
277
+        return $success;
278
+    }
279 279
 
280
-	/**
281
-	 * extract the archive
282
-	 *
283
-	 * @param string $dest
284
-	 * @return bool
285
-	 */
286
-	function extract($dest) {
287
-		return $this->tar->extract($dest);
288
-	}
280
+    /**
281
+     * extract the archive
282
+     *
283
+     * @param string $dest
284
+     * @return bool
285
+     */
286
+    function extract($dest) {
287
+        return $this->tar->extract($dest);
288
+    }
289 289
 
290
-	/**
291
-	 * check if a file or folder exists in the archive
292
-	 *
293
-	 * @param string $path
294
-	 * @return bool
295
-	 */
296
-	function fileExists($path) {
297
-		$files = $this->getFiles();
298
-		if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
299
-			return true;
300
-		} else {
301
-			$folderPath = $path;
302
-			if (substr($folderPath, -1, 1) != '/') {
303
-				$folderPath .= '/';
304
-			}
305
-			$pathLength = strlen($folderPath);
306
-			foreach ($files as $file) {
307
-				if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
308
-					return true;
309
-				}
310
-			}
311
-		}
312
-		if ($path[0] != '/') { //not all programs agree on the use of a leading /
313
-			return $this->fileExists('/' . $path);
314
-		} else {
315
-			return false;
316
-		}
317
-	}
290
+    /**
291
+     * check if a file or folder exists in the archive
292
+     *
293
+     * @param string $path
294
+     * @return bool
295
+     */
296
+    function fileExists($path) {
297
+        $files = $this->getFiles();
298
+        if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
299
+            return true;
300
+        } else {
301
+            $folderPath = $path;
302
+            if (substr($folderPath, -1, 1) != '/') {
303
+                $folderPath .= '/';
304
+            }
305
+            $pathLength = strlen($folderPath);
306
+            foreach ($files as $file) {
307
+                if (strlen($file) > $pathLength and substr($file, 0, $pathLength) == $folderPath) {
308
+                    return true;
309
+                }
310
+            }
311
+        }
312
+        if ($path[0] != '/') { //not all programs agree on the use of a leading /
313
+            return $this->fileExists('/' . $path);
314
+        } else {
315
+            return false;
316
+        }
317
+    }
318 318
 
319
-	/**
320
-	 * remove a file or folder from the archive
321
-	 *
322
-	 * @param string $path
323
-	 * @return bool
324
-	 */
325
-	function remove($path) {
326
-		if (!$this->fileExists($path)) {
327
-			return false;
328
-		}
329
-		$this->fileList = false;
330
-		$this->cachedHeaders = false;
331
-		//no proper way to delete, extract entire archive, delete file and remake archive
332
-		$tmp = \OCP\Files::tmpFolder();
333
-		$this->tar->extract($tmp);
334
-		\OCP\Files::rmdirr($tmp . $path);
335
-		$this->tar = null;
336
-		unlink($this->path);
337
-		$this->reopen();
338
-		$this->tar->createModify(array($tmp), '', $tmp);
339
-		return true;
340
-	}
319
+    /**
320
+     * remove a file or folder from the archive
321
+     *
322
+     * @param string $path
323
+     * @return bool
324
+     */
325
+    function remove($path) {
326
+        if (!$this->fileExists($path)) {
327
+            return false;
328
+        }
329
+        $this->fileList = false;
330
+        $this->cachedHeaders = false;
331
+        //no proper way to delete, extract entire archive, delete file and remake archive
332
+        $tmp = \OCP\Files::tmpFolder();
333
+        $this->tar->extract($tmp);
334
+        \OCP\Files::rmdirr($tmp . $path);
335
+        $this->tar = null;
336
+        unlink($this->path);
337
+        $this->reopen();
338
+        $this->tar->createModify(array($tmp), '', $tmp);
339
+        return true;
340
+    }
341 341
 
342
-	/**
343
-	 * get a file handler
344
-	 *
345
-	 * @param string $path
346
-	 * @param string $mode
347
-	 * @return resource
348
-	 */
349
-	function getStream($path, $mode) {
350
-		if (strrpos($path, '.') !== false) {
351
-			$ext = substr($path, strrpos($path, '.'));
352
-		} else {
353
-			$ext = '';
354
-		}
355
-		$tmpFile = \OCP\Files::tmpFile($ext);
356
-		if ($this->fileExists($path)) {
357
-			$this->extractFile($path, $tmpFile);
358
-		} elseif ($mode == 'r' or $mode == 'rb') {
359
-			return false;
360
-		}
361
-		if ($mode == 'r' or $mode == 'rb') {
362
-			return fopen($tmpFile, $mode);
363
-		} else {
364
-			$handle = fopen($tmpFile, $mode);
365
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
366
-				$this->writeBack($tmpFile, $path);
367
-			});
368
-		}
369
-	}
342
+    /**
343
+     * get a file handler
344
+     *
345
+     * @param string $path
346
+     * @param string $mode
347
+     * @return resource
348
+     */
349
+    function getStream($path, $mode) {
350
+        if (strrpos($path, '.') !== false) {
351
+            $ext = substr($path, strrpos($path, '.'));
352
+        } else {
353
+            $ext = '';
354
+        }
355
+        $tmpFile = \OCP\Files::tmpFile($ext);
356
+        if ($this->fileExists($path)) {
357
+            $this->extractFile($path, $tmpFile);
358
+        } elseif ($mode == 'r' or $mode == 'rb') {
359
+            return false;
360
+        }
361
+        if ($mode == 'r' or $mode == 'rb') {
362
+            return fopen($tmpFile, $mode);
363
+        } else {
364
+            $handle = fopen($tmpFile, $mode);
365
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
366
+                $this->writeBack($tmpFile, $path);
367
+            });
368
+        }
369
+    }
370 370
 
371
-	/**
372
-	 * write back temporary files
373
-	 */
374
-	function writeBack($tmpFile, $path) {
375
-		$this->addFile($path, $tmpFile);
376
-		unlink($tmpFile);
377
-	}
371
+    /**
372
+     * write back temporary files
373
+     */
374
+    function writeBack($tmpFile, $path) {
375
+        $this->addFile($path, $tmpFile);
376
+        unlink($tmpFile);
377
+    }
378 378
 
379
-	/**
380
-	 * reopen the archive to ensure everything is written
381
-	 */
382
-	private function reopen() {
383
-		if ($this->tar) {
384
-			$this->tar->_close();
385
-			$this->tar = null;
386
-		}
387
-		$types = array(null, 'gz', 'bz');
388
-		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
389
-	}
379
+    /**
380
+     * reopen the archive to ensure everything is written
381
+     */
382
+    private function reopen() {
383
+        if ($this->tar) {
384
+            $this->tar->_close();
385
+            $this->tar = null;
386
+        }
387
+        $types = array(null, 'gz', 'bz');
388
+        $this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
389
+    }
390 390
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -101,13 +101,13 @@  discard block
 block discarded – undo
101 101
 		$parts = explode('/', $path);
102 102
 		$folder = $tmpBase;
103 103
 		foreach ($parts as $part) {
104
-			$folder .= '/' . $part;
104
+			$folder .= '/'.$part;
105 105
 			if (!is_dir($folder)) {
106 106
 				mkdir($folder);
107 107
 			}
108 108
 		}
109
-		$result = $this->tar->addModify(array($tmpBase . $path), '', $tmpBase);
110
-		rmdir($tmpBase . $path);
109
+		$result = $this->tar->addModify(array($tmpBase.$path), '', $tmpBase);
110
+		rmdir($tmpBase.$path);
111 111
 		$this->fileList = false;
112 112
 		$this->cachedHeaders = false;
113 113
 		return $result;
@@ -144,12 +144,12 @@  discard block
 block discarded – undo
144 144
 		//no proper way to delete, rename entire archive, rename file and remake archive
145 145
 		$tmp = \OCP\Files::tmpFolder();
146 146
 		$this->tar->extract($tmp);
147
-		rename($tmp . $source, $tmp . $dest);
147
+		rename($tmp.$source, $tmp.$dest);
148 148
 		$this->tar = null;
149 149
 		unlink($this->path);
150 150
 		$types = array(null, 'gz', 'bz');
151 151
 		$this->tar = new \Archive_Tar($this->path, $types[self::getTarType($this->path)]);
152
-		$this->tar->createModify(array($tmp), '', $tmp . '/');
152
+		$this->tar->createModify(array($tmp), '', $tmp.'/');
153 153
 		$this->fileList = false;
154 154
 		$this->cachedHeaders = false;
155 155
 		return true;
@@ -164,9 +164,9 @@  discard block
 block discarded – undo
164 164
 		}
165 165
 		foreach ($this->cachedHeaders as $header) {
166 166
 			if ($file == $header['filename']
167
-				or $file . '/' == $header['filename']
168
-				or '/' . $file . '/' == $header['filename']
169
-				or '/' . $file == $header['filename']
167
+				or $file.'/' == $header['filename']
168
+				or '/'.$file.'/' == $header['filename']
169
+				or '/'.$file == $header['filename']
170 170
 			) {
171 171
 				return $header;
172 172
 			}
@@ -265,13 +265,13 @@  discard block
 block discarded – undo
265 265
 		if (!$this->fileExists($path)) {
266 266
 			return false;
267 267
 		}
268
-		if ($this->fileExists('/' . $path)) {
269
-			$success = $this->tar->extractList(array('/' . $path), $tmp);
268
+		if ($this->fileExists('/'.$path)) {
269
+			$success = $this->tar->extractList(array('/'.$path), $tmp);
270 270
 		} else {
271 271
 			$success = $this->tar->extractList(array($path), $tmp);
272 272
 		}
273 273
 		if ($success) {
274
-			rename($tmp . $path, $dest);
274
+			rename($tmp.$path, $dest);
275 275
 		}
276 276
 		\OCP\Files::rmdirr($tmp);
277 277
 		return $success;
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
 	 */
296 296
 	function fileExists($path) {
297 297
 		$files = $this->getFiles();
298
-		if ((array_search($path, $files) !== false) or (array_search($path . '/', $files) !== false)) {
298
+		if ((array_search($path, $files) !== false) or (array_search($path.'/', $files) !== false)) {
299 299
 			return true;
300 300
 		} else {
301 301
 			$folderPath = $path;
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 			}
311 311
 		}
312 312
 		if ($path[0] != '/') { //not all programs agree on the use of a leading /
313
-			return $this->fileExists('/' . $path);
313
+			return $this->fileExists('/'.$path);
314 314
 		} else {
315 315
 			return false;
316 316
 		}
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 		//no proper way to delete, extract entire archive, delete file and remake archive
332 332
 		$tmp = \OCP\Files::tmpFolder();
333 333
 		$this->tar->extract($tmp);
334
-		\OCP\Files::rmdirr($tmp . $path);
334
+		\OCP\Files::rmdirr($tmp.$path);
335 335
 		$this->tar = null;
336 336
 		unlink($this->path);
337 337
 		$this->reopen();
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			return fopen($tmpFile, $mode);
363 363
 		} else {
364 364
 			$handle = fopen($tmpFile, $mode);
365
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
365
+			return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
366 366
 				$this->writeBack($tmpFile, $path);
367 367
 			});
368 368
 		}
Please login to merge, or discard this patch.
lib/private/Files/ObjectStore/ObjectStoreStorage.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -162,6 +162,9 @@  discard block
 block discarded – undo
162 162
 		return true;
163 163
 	}
164 164
 
165
+	/**
166
+	 * @param string $path
167
+	 */
165 168
 	private function rmObjects($path) {
166 169
 		$children = $this->getCache()->getFolderContents($path);
167 170
 		foreach ($children as $child) {
@@ -364,6 +367,9 @@  discard block
 block discarded – undo
364 367
 		return true;
365 368
 	}
366 369
 
370
+	/**
371
+	 * @param string $path
372
+	 */
367 373
 	public function writeBack($tmpFile, $path) {
368 374
 		$stat = $this->stat($path);
369 375
 		if (empty($stat)) {
Please login to merge, or discard this patch.
Indentation   +370 added lines, -370 removed lines patch added patch discarded remove patch
@@ -31,374 +31,374 @@
 block discarded – undo
31 31
 use OCP\Files\ObjectStore\IObjectStore;
32 32
 
33 33
 class ObjectStoreStorage extends \OC\Files\Storage\Common {
34
-	/**
35
-	 * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
-	 */
37
-	protected $objectStore;
38
-	/**
39
-	 * @var string $id
40
-	 */
41
-	protected $id;
42
-	/**
43
-	 * @var \OC\User\User $user
44
-	 */
45
-	protected $user;
46
-
47
-	private $objectPrefix = 'urn:oid:';
48
-
49
-	public function __construct($params) {
50
-		if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
51
-			$this->objectStore = $params['objectstore'];
52
-		} else {
53
-			throw new \Exception('missing IObjectStore instance');
54
-		}
55
-		if (isset($params['storageid'])) {
56
-			$this->id = 'object::store:' . $params['storageid'];
57
-		} else {
58
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
59
-		}
60
-		if (isset($params['objectPrefix'])) {
61
-			$this->objectPrefix = $params['objectPrefix'];
62
-		}
63
-		//initialize cache with root directory in cache
64
-		if (!$this->is_dir('/')) {
65
-			$this->mkdir('/');
66
-		}
67
-	}
68
-
69
-	public function mkdir($path) {
70
-		$path = $this->normalizePath($path);
71
-
72
-		if ($this->file_exists($path)) {
73
-			return false;
74
-		}
75
-
76
-		$mTime = time();
77
-		$data = [
78
-			'mimetype' => 'httpd/unix-directory',
79
-			'size' => 0,
80
-			'mtime' => $mTime,
81
-			'storage_mtime' => $mTime,
82
-			'permissions' => \OCP\Constants::PERMISSION_ALL,
83
-		];
84
-		if ($path === '') {
85
-			//create root on the fly
86
-			$data['etag'] = $this->getETag('');
87
-			$this->getCache()->put('', $data);
88
-			return true;
89
-		} else {
90
-			// if parent does not exist, create it
91
-			$parent = $this->normalizePath(dirname($path));
92
-			$parentType = $this->filetype($parent);
93
-			if ($parentType === false) {
94
-				if (!$this->mkdir($parent)) {
95
-					// something went wrong
96
-					return false;
97
-				}
98
-			} else if ($parentType === 'file') {
99
-				// parent is a file
100
-				return false;
101
-			}
102
-			// finally create the new dir
103
-			$mTime = time(); // update mtime
104
-			$data['mtime'] = $mTime;
105
-			$data['storage_mtime'] = $mTime;
106
-			$data['etag'] = $this->getETag($path);
107
-			$this->getCache()->put($path, $data);
108
-			return true;
109
-		}
110
-	}
111
-
112
-	/**
113
-	 * @param string $path
114
-	 * @return string
115
-	 */
116
-	private function normalizePath($path) {
117
-		$path = trim($path, '/');
118
-		//FIXME why do we sometimes get a path like 'files//username'?
119
-		$path = str_replace('//', '/', $path);
120
-
121
-		// dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
122
-		if (!$path || $path === '.') {
123
-			$path = '';
124
-		}
125
-
126
-		return $path;
127
-	}
128
-
129
-	/**
130
-	 * Object Stores use a NoopScanner because metadata is directly stored in
131
-	 * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
132
-	 *
133
-	 * @param string $path
134
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
135
-	 * @return \OC\Files\ObjectStore\NoopScanner
136
-	 */
137
-	public function getScanner($path = '', $storage = null) {
138
-		if (!$storage) {
139
-			$storage = $this;
140
-		}
141
-		if (!isset($this->scanner)) {
142
-			$this->scanner = new NoopScanner($storage);
143
-		}
144
-		return $this->scanner;
145
-	}
146
-
147
-	public function getId() {
148
-		return $this->id;
149
-	}
150
-
151
-	public function rmdir($path) {
152
-		$path = $this->normalizePath($path);
153
-
154
-		if (!$this->is_dir($path)) {
155
-			return false;
156
-		}
157
-
158
-		$this->rmObjects($path);
159
-
160
-		$this->getCache()->remove($path);
161
-
162
-		return true;
163
-	}
164
-
165
-	private function rmObjects($path) {
166
-		$children = $this->getCache()->getFolderContents($path);
167
-		foreach ($children as $child) {
168
-			if ($child['mimetype'] === 'httpd/unix-directory') {
169
-				$this->rmObjects($child['path']);
170
-			} else {
171
-				$this->unlink($child['path']);
172
-			}
173
-		}
174
-	}
175
-
176
-	public function unlink($path) {
177
-		$path = $this->normalizePath($path);
178
-		$stat = $this->stat($path);
179
-
180
-		if ($stat && isset($stat['fileid'])) {
181
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
182
-				return $this->rmdir($path);
183
-			}
184
-			try {
185
-				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
186
-			} catch (\Exception $ex) {
187
-				if ($ex->getCode() !== 404) {
188
-					\OCP\Util::writeLog('objectstore', 'Could not delete object: ' . $ex->getMessage(), \OCP\Util::ERROR);
189
-					return false;
190
-				} else {
191
-					//removing from cache is ok as it does not exist in the objectstore anyway
192
-				}
193
-			}
194
-			$this->getCache()->remove($path);
195
-			return true;
196
-		}
197
-		return false;
198
-	}
199
-
200
-	public function stat($path) {
201
-		$path = $this->normalizePath($path);
202
-		$cacheEntry = $this->getCache()->get($path);
203
-		if ($cacheEntry instanceof CacheEntry) {
204
-			return $cacheEntry->getData();
205
-		} else {
206
-			return false;
207
-		}
208
-	}
209
-
210
-	/**
211
-	 * Override this method if you need a different unique resource identifier for your object storage implementation.
212
-	 * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
213
-	 * You may need a mapping table to store your URN if it cannot be generated from the fileid.
214
-	 *
215
-	 * @param int $fileId the fileid
216
-	 * @return null|string the unified resource name used to identify the object
217
-	 */
218
-	protected function getURN($fileId) {
219
-		if (is_numeric($fileId)) {
220
-			return $this->objectPrefix . $fileId;
221
-		}
222
-		return null;
223
-	}
224
-
225
-	public function opendir($path) {
226
-		$path = $this->normalizePath($path);
227
-
228
-		try {
229
-			$files = array();
230
-			$folderContents = $this->getCache()->getFolderContents($path);
231
-			foreach ($folderContents as $file) {
232
-				$files[] = $file['name'];
233
-			}
234
-
235
-			return IteratorDirectory::wrap($files);
236
-		} catch (\Exception $e) {
237
-			\OCP\Util::writeLog('objectstore', $e->getMessage(), \OCP\Util::ERROR);
238
-			return false;
239
-		}
240
-	}
241
-
242
-	public function filetype($path) {
243
-		$path = $this->normalizePath($path);
244
-		$stat = $this->stat($path);
245
-		if ($stat) {
246
-			if ($stat['mimetype'] === 'httpd/unix-directory') {
247
-				return 'dir';
248
-			}
249
-			return 'file';
250
-		} else {
251
-			return false;
252
-		}
253
-	}
254
-
255
-	public function fopen($path, $mode) {
256
-		$path = $this->normalizePath($path);
257
-
258
-		switch ($mode) {
259
-			case 'r':
260
-			case 'rb':
261
-				$stat = $this->stat($path);
262
-				if (is_array($stat)) {
263
-					try {
264
-						return $this->objectStore->readObject($this->getURN($stat['fileid']));
265
-					} catch (\Exception $ex) {
266
-						\OCP\Util::writeLog('objectstore', 'Could not get object: ' . $ex->getMessage(), \OCP\Util::ERROR);
267
-						return false;
268
-					}
269
-				} else {
270
-					return false;
271
-				}
272
-			case 'w':
273
-			case 'wb':
274
-			case 'a':
275
-			case 'ab':
276
-			case 'r+':
277
-			case 'w+':
278
-			case 'wb+':
279
-			case 'a+':
280
-			case 'x':
281
-			case 'x+':
282
-			case 'c':
283
-			case 'c+':
284
-				if (strrpos($path, '.') !== false) {
285
-					$ext = substr($path, strrpos($path, '.'));
286
-				} else {
287
-					$ext = '';
288
-				}
289
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
290
-				if ($this->file_exists($path)) {
291
-					$source = $this->fopen($path, 'r');
292
-					file_put_contents($tmpFile, $source);
293
-				}
294
-				$handle = fopen($tmpFile, $mode);
295
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
296
-					$this->writeBack($tmpFile, $path);
297
-				});
298
-		}
299
-		return false;
300
-	}
301
-
302
-	public function file_exists($path) {
303
-		$path = $this->normalizePath($path);
304
-		return (bool)$this->stat($path);
305
-	}
306
-
307
-	public function rename($source, $target) {
308
-		$source = $this->normalizePath($source);
309
-		$target = $this->normalizePath($target);
310
-		$this->remove($target);
311
-		$this->getCache()->move($source, $target);
312
-		$this->touch(dirname($target));
313
-		return true;
314
-	}
315
-
316
-	public function getMimeType($path) {
317
-		$path = $this->normalizePath($path);
318
-		$stat = $this->stat($path);
319
-		if (is_array($stat)) {
320
-			return $stat['mimetype'];
321
-		} else {
322
-			return false;
323
-		}
324
-	}
325
-
326
-	public function touch($path, $mtime = null) {
327
-		if (is_null($mtime)) {
328
-			$mtime = time();
329
-		}
330
-
331
-		$path = $this->normalizePath($path);
332
-		$dirName = dirname($path);
333
-		$parentExists = $this->is_dir($dirName);
334
-		if (!$parentExists) {
335
-			return false;
336
-		}
337
-
338
-		$stat = $this->stat($path);
339
-		if (is_array($stat)) {
340
-			// update existing mtime in db
341
-			$stat['mtime'] = $mtime;
342
-			$this->getCache()->update($stat['fileid'], $stat);
343
-		} else {
344
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
345
-			// create new file
346
-			$stat = array(
347
-				'etag' => $this->getETag($path),
348
-				'mimetype' => $mimeType,
349
-				'size' => 0,
350
-				'mtime' => $mtime,
351
-				'storage_mtime' => $mtime,
352
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
353
-			);
354
-			$fileId = $this->getCache()->put($path, $stat);
355
-			try {
356
-				//read an empty file from memory
357
-				$this->objectStore->writeObject($this->getURN($fileId), fopen('php://memory', 'r'));
358
-			} catch (\Exception $ex) {
359
-				$this->getCache()->remove($path);
360
-				\OCP\Util::writeLog('objectstore', 'Could not create object: ' . $ex->getMessage(), \OCP\Util::ERROR);
361
-				return false;
362
-			}
363
-		}
364
-		return true;
365
-	}
366
-
367
-	public function writeBack($tmpFile, $path) {
368
-		$stat = $this->stat($path);
369
-		if (empty($stat)) {
370
-			// create new file
371
-			$stat = array(
372
-				'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
373
-			);
374
-		}
375
-		// update stat with new data
376
-		$mTime = time();
377
-		$stat['size'] = filesize($tmpFile);
378
-		$stat['mtime'] = $mTime;
379
-		$stat['storage_mtime'] = $mTime;
380
-		$stat['mimetype'] = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
381
-		$stat['etag'] = $this->getETag($path);
382
-
383
-		$fileId = $this->getCache()->put($path, $stat);
384
-		try {
385
-			//upload to object storage
386
-			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
387
-		} catch (\Exception $ex) {
388
-			$this->getCache()->remove($path);
389
-			\OCP\Util::writeLog('objectstore', 'Could not create object: ' . $ex->getMessage(), \OCP\Util::ERROR);
390
-			throw $ex; // make this bubble up
391
-		}
392
-	}
393
-
394
-	/**
395
-	 * external changes are not supported, exclusive access to the object storage is assumed
396
-	 *
397
-	 * @param string $path
398
-	 * @param int $time
399
-	 * @return false
400
-	 */
401
-	public function hasUpdated($path, $time) {
402
-		return false;
403
-	}
34
+    /**
35
+     * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
36
+     */
37
+    protected $objectStore;
38
+    /**
39
+     * @var string $id
40
+     */
41
+    protected $id;
42
+    /**
43
+     * @var \OC\User\User $user
44
+     */
45
+    protected $user;
46
+
47
+    private $objectPrefix = 'urn:oid:';
48
+
49
+    public function __construct($params) {
50
+        if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
51
+            $this->objectStore = $params['objectstore'];
52
+        } else {
53
+            throw new \Exception('missing IObjectStore instance');
54
+        }
55
+        if (isset($params['storageid'])) {
56
+            $this->id = 'object::store:' . $params['storageid'];
57
+        } else {
58
+            $this->id = 'object::store:' . $this->objectStore->getStorageId();
59
+        }
60
+        if (isset($params['objectPrefix'])) {
61
+            $this->objectPrefix = $params['objectPrefix'];
62
+        }
63
+        //initialize cache with root directory in cache
64
+        if (!$this->is_dir('/')) {
65
+            $this->mkdir('/');
66
+        }
67
+    }
68
+
69
+    public function mkdir($path) {
70
+        $path = $this->normalizePath($path);
71
+
72
+        if ($this->file_exists($path)) {
73
+            return false;
74
+        }
75
+
76
+        $mTime = time();
77
+        $data = [
78
+            'mimetype' => 'httpd/unix-directory',
79
+            'size' => 0,
80
+            'mtime' => $mTime,
81
+            'storage_mtime' => $mTime,
82
+            'permissions' => \OCP\Constants::PERMISSION_ALL,
83
+        ];
84
+        if ($path === '') {
85
+            //create root on the fly
86
+            $data['etag'] = $this->getETag('');
87
+            $this->getCache()->put('', $data);
88
+            return true;
89
+        } else {
90
+            // if parent does not exist, create it
91
+            $parent = $this->normalizePath(dirname($path));
92
+            $parentType = $this->filetype($parent);
93
+            if ($parentType === false) {
94
+                if (!$this->mkdir($parent)) {
95
+                    // something went wrong
96
+                    return false;
97
+                }
98
+            } else if ($parentType === 'file') {
99
+                // parent is a file
100
+                return false;
101
+            }
102
+            // finally create the new dir
103
+            $mTime = time(); // update mtime
104
+            $data['mtime'] = $mTime;
105
+            $data['storage_mtime'] = $mTime;
106
+            $data['etag'] = $this->getETag($path);
107
+            $this->getCache()->put($path, $data);
108
+            return true;
109
+        }
110
+    }
111
+
112
+    /**
113
+     * @param string $path
114
+     * @return string
115
+     */
116
+    private function normalizePath($path) {
117
+        $path = trim($path, '/');
118
+        //FIXME why do we sometimes get a path like 'files//username'?
119
+        $path = str_replace('//', '/', $path);
120
+
121
+        // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
122
+        if (!$path || $path === '.') {
123
+            $path = '';
124
+        }
125
+
126
+        return $path;
127
+    }
128
+
129
+    /**
130
+     * Object Stores use a NoopScanner because metadata is directly stored in
131
+     * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
132
+     *
133
+     * @param string $path
134
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
135
+     * @return \OC\Files\ObjectStore\NoopScanner
136
+     */
137
+    public function getScanner($path = '', $storage = null) {
138
+        if (!$storage) {
139
+            $storage = $this;
140
+        }
141
+        if (!isset($this->scanner)) {
142
+            $this->scanner = new NoopScanner($storage);
143
+        }
144
+        return $this->scanner;
145
+    }
146
+
147
+    public function getId() {
148
+        return $this->id;
149
+    }
150
+
151
+    public function rmdir($path) {
152
+        $path = $this->normalizePath($path);
153
+
154
+        if (!$this->is_dir($path)) {
155
+            return false;
156
+        }
157
+
158
+        $this->rmObjects($path);
159
+
160
+        $this->getCache()->remove($path);
161
+
162
+        return true;
163
+    }
164
+
165
+    private function rmObjects($path) {
166
+        $children = $this->getCache()->getFolderContents($path);
167
+        foreach ($children as $child) {
168
+            if ($child['mimetype'] === 'httpd/unix-directory') {
169
+                $this->rmObjects($child['path']);
170
+            } else {
171
+                $this->unlink($child['path']);
172
+            }
173
+        }
174
+    }
175
+
176
+    public function unlink($path) {
177
+        $path = $this->normalizePath($path);
178
+        $stat = $this->stat($path);
179
+
180
+        if ($stat && isset($stat['fileid'])) {
181
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
182
+                return $this->rmdir($path);
183
+            }
184
+            try {
185
+                $this->objectStore->deleteObject($this->getURN($stat['fileid']));
186
+            } catch (\Exception $ex) {
187
+                if ($ex->getCode() !== 404) {
188
+                    \OCP\Util::writeLog('objectstore', 'Could not delete object: ' . $ex->getMessage(), \OCP\Util::ERROR);
189
+                    return false;
190
+                } else {
191
+                    //removing from cache is ok as it does not exist in the objectstore anyway
192
+                }
193
+            }
194
+            $this->getCache()->remove($path);
195
+            return true;
196
+        }
197
+        return false;
198
+    }
199
+
200
+    public function stat($path) {
201
+        $path = $this->normalizePath($path);
202
+        $cacheEntry = $this->getCache()->get($path);
203
+        if ($cacheEntry instanceof CacheEntry) {
204
+            return $cacheEntry->getData();
205
+        } else {
206
+            return false;
207
+        }
208
+    }
209
+
210
+    /**
211
+     * Override this method if you need a different unique resource identifier for your object storage implementation.
212
+     * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
213
+     * You may need a mapping table to store your URN if it cannot be generated from the fileid.
214
+     *
215
+     * @param int $fileId the fileid
216
+     * @return null|string the unified resource name used to identify the object
217
+     */
218
+    protected function getURN($fileId) {
219
+        if (is_numeric($fileId)) {
220
+            return $this->objectPrefix . $fileId;
221
+        }
222
+        return null;
223
+    }
224
+
225
+    public function opendir($path) {
226
+        $path = $this->normalizePath($path);
227
+
228
+        try {
229
+            $files = array();
230
+            $folderContents = $this->getCache()->getFolderContents($path);
231
+            foreach ($folderContents as $file) {
232
+                $files[] = $file['name'];
233
+            }
234
+
235
+            return IteratorDirectory::wrap($files);
236
+        } catch (\Exception $e) {
237
+            \OCP\Util::writeLog('objectstore', $e->getMessage(), \OCP\Util::ERROR);
238
+            return false;
239
+        }
240
+    }
241
+
242
+    public function filetype($path) {
243
+        $path = $this->normalizePath($path);
244
+        $stat = $this->stat($path);
245
+        if ($stat) {
246
+            if ($stat['mimetype'] === 'httpd/unix-directory') {
247
+                return 'dir';
248
+            }
249
+            return 'file';
250
+        } else {
251
+            return false;
252
+        }
253
+    }
254
+
255
+    public function fopen($path, $mode) {
256
+        $path = $this->normalizePath($path);
257
+
258
+        switch ($mode) {
259
+            case 'r':
260
+            case 'rb':
261
+                $stat = $this->stat($path);
262
+                if (is_array($stat)) {
263
+                    try {
264
+                        return $this->objectStore->readObject($this->getURN($stat['fileid']));
265
+                    } catch (\Exception $ex) {
266
+                        \OCP\Util::writeLog('objectstore', 'Could not get object: ' . $ex->getMessage(), \OCP\Util::ERROR);
267
+                        return false;
268
+                    }
269
+                } else {
270
+                    return false;
271
+                }
272
+            case 'w':
273
+            case 'wb':
274
+            case 'a':
275
+            case 'ab':
276
+            case 'r+':
277
+            case 'w+':
278
+            case 'wb+':
279
+            case 'a+':
280
+            case 'x':
281
+            case 'x+':
282
+            case 'c':
283
+            case 'c+':
284
+                if (strrpos($path, '.') !== false) {
285
+                    $ext = substr($path, strrpos($path, '.'));
286
+                } else {
287
+                    $ext = '';
288
+                }
289
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
290
+                if ($this->file_exists($path)) {
291
+                    $source = $this->fopen($path, 'r');
292
+                    file_put_contents($tmpFile, $source);
293
+                }
294
+                $handle = fopen($tmpFile, $mode);
295
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
296
+                    $this->writeBack($tmpFile, $path);
297
+                });
298
+        }
299
+        return false;
300
+    }
301
+
302
+    public function file_exists($path) {
303
+        $path = $this->normalizePath($path);
304
+        return (bool)$this->stat($path);
305
+    }
306
+
307
+    public function rename($source, $target) {
308
+        $source = $this->normalizePath($source);
309
+        $target = $this->normalizePath($target);
310
+        $this->remove($target);
311
+        $this->getCache()->move($source, $target);
312
+        $this->touch(dirname($target));
313
+        return true;
314
+    }
315
+
316
+    public function getMimeType($path) {
317
+        $path = $this->normalizePath($path);
318
+        $stat = $this->stat($path);
319
+        if (is_array($stat)) {
320
+            return $stat['mimetype'];
321
+        } else {
322
+            return false;
323
+        }
324
+    }
325
+
326
+    public function touch($path, $mtime = null) {
327
+        if (is_null($mtime)) {
328
+            $mtime = time();
329
+        }
330
+
331
+        $path = $this->normalizePath($path);
332
+        $dirName = dirname($path);
333
+        $parentExists = $this->is_dir($dirName);
334
+        if (!$parentExists) {
335
+            return false;
336
+        }
337
+
338
+        $stat = $this->stat($path);
339
+        if (is_array($stat)) {
340
+            // update existing mtime in db
341
+            $stat['mtime'] = $mtime;
342
+            $this->getCache()->update($stat['fileid'], $stat);
343
+        } else {
344
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
345
+            // create new file
346
+            $stat = array(
347
+                'etag' => $this->getETag($path),
348
+                'mimetype' => $mimeType,
349
+                'size' => 0,
350
+                'mtime' => $mtime,
351
+                'storage_mtime' => $mtime,
352
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
353
+            );
354
+            $fileId = $this->getCache()->put($path, $stat);
355
+            try {
356
+                //read an empty file from memory
357
+                $this->objectStore->writeObject($this->getURN($fileId), fopen('php://memory', 'r'));
358
+            } catch (\Exception $ex) {
359
+                $this->getCache()->remove($path);
360
+                \OCP\Util::writeLog('objectstore', 'Could not create object: ' . $ex->getMessage(), \OCP\Util::ERROR);
361
+                return false;
362
+            }
363
+        }
364
+        return true;
365
+    }
366
+
367
+    public function writeBack($tmpFile, $path) {
368
+        $stat = $this->stat($path);
369
+        if (empty($stat)) {
370
+            // create new file
371
+            $stat = array(
372
+                'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
373
+            );
374
+        }
375
+        // update stat with new data
376
+        $mTime = time();
377
+        $stat['size'] = filesize($tmpFile);
378
+        $stat['mtime'] = $mTime;
379
+        $stat['storage_mtime'] = $mTime;
380
+        $stat['mimetype'] = \OC::$server->getMimeTypeDetector()->detect($tmpFile);
381
+        $stat['etag'] = $this->getETag($path);
382
+
383
+        $fileId = $this->getCache()->put($path, $stat);
384
+        try {
385
+            //upload to object storage
386
+            $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
387
+        } catch (\Exception $ex) {
388
+            $this->getCache()->remove($path);
389
+            \OCP\Util::writeLog('objectstore', 'Could not create object: ' . $ex->getMessage(), \OCP\Util::ERROR);
390
+            throw $ex; // make this bubble up
391
+        }
392
+    }
393
+
394
+    /**
395
+     * external changes are not supported, exclusive access to the object storage is assumed
396
+     *
397
+     * @param string $path
398
+     * @param int $time
399
+     * @return false
400
+     */
401
+    public function hasUpdated($path, $time) {
402
+        return false;
403
+    }
404 404
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -53,9 +53,9 @@  discard block
 block discarded – undo
53 53
 			throw new \Exception('missing IObjectStore instance');
54 54
 		}
55 55
 		if (isset($params['storageid'])) {
56
-			$this->id = 'object::store:' . $params['storageid'];
56
+			$this->id = 'object::store:'.$params['storageid'];
57 57
 		} else {
58
-			$this->id = 'object::store:' . $this->objectStore->getStorageId();
58
+			$this->id = 'object::store:'.$this->objectStore->getStorageId();
59 59
 		}
60 60
 		if (isset($params['objectPrefix'])) {
61 61
 			$this->objectPrefix = $params['objectPrefix'];
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 				$this->objectStore->deleteObject($this->getURN($stat['fileid']));
186 186
 			} catch (\Exception $ex) {
187 187
 				if ($ex->getCode() !== 404) {
188
-					\OCP\Util::writeLog('objectstore', 'Could not delete object: ' . $ex->getMessage(), \OCP\Util::ERROR);
188
+					\OCP\Util::writeLog('objectstore', 'Could not delete object: '.$ex->getMessage(), \OCP\Util::ERROR);
189 189
 					return false;
190 190
 				} else {
191 191
 					//removing from cache is ok as it does not exist in the objectstore anyway
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 	 */
218 218
 	protected function getURN($fileId) {
219 219
 		if (is_numeric($fileId)) {
220
-			return $this->objectPrefix . $fileId;
220
+			return $this->objectPrefix.$fileId;
221 221
 		}
222 222
 		return null;
223 223
 	}
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
 					try {
264 264
 						return $this->objectStore->readObject($this->getURN($stat['fileid']));
265 265
 					} catch (\Exception $ex) {
266
-						\OCP\Util::writeLog('objectstore', 'Could not get object: ' . $ex->getMessage(), \OCP\Util::ERROR);
266
+						\OCP\Util::writeLog('objectstore', 'Could not get object: '.$ex->getMessage(), \OCP\Util::ERROR);
267 267
 						return false;
268 268
 					}
269 269
 				} else {
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
 					file_put_contents($tmpFile, $source);
293 293
 				}
294 294
 				$handle = fopen($tmpFile, $mode);
295
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
295
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
296 296
 					$this->writeBack($tmpFile, $path);
297 297
 				});
298 298
 		}
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 
302 302
 	public function file_exists($path) {
303 303
 		$path = $this->normalizePath($path);
304
-		return (bool)$this->stat($path);
304
+		return (bool) $this->stat($path);
305 305
 	}
306 306
 
307 307
 	public function rename($source, $target) {
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 				$this->objectStore->writeObject($this->getURN($fileId), fopen('php://memory', 'r'));
358 358
 			} catch (\Exception $ex) {
359 359
 				$this->getCache()->remove($path);
360
-				\OCP\Util::writeLog('objectstore', 'Could not create object: ' . $ex->getMessage(), \OCP\Util::ERROR);
360
+				\OCP\Util::writeLog('objectstore', 'Could not create object: '.$ex->getMessage(), \OCP\Util::ERROR);
361 361
 				return false;
362 362
 			}
363 363
 		}
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 			$this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
387 387
 		} catch (\Exception $ex) {
388 388
 			$this->getCache()->remove($path);
389
-			\OCP\Util::writeLog('objectstore', 'Could not create object: ' . $ex->getMessage(), \OCP\Util::ERROR);
389
+			\OCP\Util::writeLog('objectstore', 'Could not create object: '.$ex->getMessage(), \OCP\Util::ERROR);
390 390
 			throw $ex; // make this bubble up
391 391
 		}
392 392
 	}
Please login to merge, or discard this patch.
lib/private/Files/Storage/DAV.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -38,7 +38,6 @@
 block discarded – undo
38 38
 use GuzzleHttp\Message\ResponseInterface;
39 39
 use Icewind\Streams\CallbackWrapper;
40 40
 use OC\Files\Filesystem;
41
-use OC\Files\Stream\Close;
42 41
 use Icewind\Streams\IteratorDirectory;
43 42
 use OC\MemCache\ArrayCache;
44 43
 use OCP\AppFramework\Http;
Please login to merge, or discard this patch.
Braces   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,8 +90,11 @@
 block discarded – undo
90 90
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
91 91
 			$host = $params['host'];
92 92
 			//remove leading http[s], will be generated in createBaseUri()
93
-			if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
94
-			else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
93
+			if (substr($host, 0, 8) == "https://") {
94
+			    $host = substr($host, 8);
95
+			} else if (substr($host, 0, 7) == "http://") {
96
+			    $host = substr($host, 7);
97
+			}
95 98
 			$this->host = $host;
96 99
 			$this->user = $params['user'];
97 100
 			$this->password = $params['password'];
Please login to merge, or discard this patch.
Indentation   +793 added lines, -793 removed lines patch added patch discarded remove patch
@@ -59,798 +59,798 @@
 block discarded – undo
59 59
  * @package OC\Files\Storage
60 60
  */
61 61
 class DAV extends Common {
62
-	/** @var string */
63
-	protected $password;
64
-	/** @var string */
65
-	protected $user;
66
-	/** @var string */
67
-	protected $authType;
68
-	/** @var string */
69
-	protected $host;
70
-	/** @var bool */
71
-	protected $secure;
72
-	/** @var string */
73
-	protected $root;
74
-	/** @var string */
75
-	protected $certPath;
76
-	/** @var bool */
77
-	protected $ready;
78
-	/** @var Client */
79
-	protected $client;
80
-	/** @var ArrayCache */
81
-	protected $statCache;
82
-	/** @var \OCP\Http\Client\IClientService */
83
-	protected $httpClientService;
84
-
85
-	/**
86
-	 * @param array $params
87
-	 * @throws \Exception
88
-	 */
89
-	public function __construct($params) {
90
-		$this->statCache = new ArrayCache();
91
-		$this->httpClientService = \OC::$server->getHTTPClientService();
92
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
93
-			$host = $params['host'];
94
-			//remove leading http[s], will be generated in createBaseUri()
95
-			if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
96
-			else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
97
-			$this->host = $host;
98
-			$this->user = $params['user'];
99
-			$this->password = $params['password'];
100
-			if (isset($params['authType'])) {
101
-				$this->authType = $params['authType'];
102
-			}
103
-			if (isset($params['secure'])) {
104
-				if (is_string($params['secure'])) {
105
-					$this->secure = ($params['secure'] === 'true');
106
-				} else {
107
-					$this->secure = (bool)$params['secure'];
108
-				}
109
-			} else {
110
-				$this->secure = false;
111
-			}
112
-			if ($this->secure === true) {
113
-				// inject mock for testing
114
-				$certManager = \OC::$server->getCertificateManager();
115
-				if (is_null($certManager)) { //no user
116
-					$certManager = \OC::$server->getCertificateManager(null);
117
-				}
118
-				$certPath = $certManager->getAbsoluteBundlePath();
119
-				if (file_exists($certPath)) {
120
-					$this->certPath = $certPath;
121
-				}
122
-			}
123
-			$this->root = isset($params['root']) ? $params['root'] : '/';
124
-			if (!$this->root || $this->root[0] != '/') {
125
-				$this->root = '/' . $this->root;
126
-			}
127
-			if (substr($this->root, -1, 1) != '/') {
128
-				$this->root .= '/';
129
-			}
130
-		} else {
131
-			throw new \Exception('Invalid webdav storage configuration');
132
-		}
133
-	}
134
-
135
-	protected function init() {
136
-		if ($this->ready) {
137
-			return;
138
-		}
139
-		$this->ready = true;
140
-
141
-		$settings = [
142
-			'baseUri' => $this->createBaseUri(),
143
-			'userName' => $this->user,
144
-			'password' => $this->password,
145
-		];
146
-		if (isset($this->authType)) {
147
-			$settings['authType'] = $this->authType;
148
-		}
149
-
150
-		$proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
151
-		if($proxy !== '') {
152
-			$settings['proxy'] = $proxy;
153
-		}
154
-
155
-		$this->client = new Client($settings);
156
-		$this->client->setThrowExceptions(true);
157
-		if ($this->secure === true && $this->certPath) {
158
-			$this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * Clear the stat cache
164
-	 */
165
-	public function clearStatCache() {
166
-		$this->statCache->clear();
167
-	}
168
-
169
-	/** {@inheritdoc} */
170
-	public function getId() {
171
-		return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
172
-	}
173
-
174
-	/** {@inheritdoc} */
175
-	public function createBaseUri() {
176
-		$baseUri = 'http';
177
-		if ($this->secure) {
178
-			$baseUri .= 's';
179
-		}
180
-		$baseUri .= '://' . $this->host . $this->root;
181
-		return $baseUri;
182
-	}
183
-
184
-	/** {@inheritdoc} */
185
-	public function mkdir($path) {
186
-		$this->init();
187
-		$path = $this->cleanPath($path);
188
-		$result = $this->simpleResponse('MKCOL', $path, null, 201);
189
-		if ($result) {
190
-			$this->statCache->set($path, true);
191
-		}
192
-		return $result;
193
-	}
194
-
195
-	/** {@inheritdoc} */
196
-	public function rmdir($path) {
197
-		$this->init();
198
-		$path = $this->cleanPath($path);
199
-		// FIXME: some WebDAV impl return 403 when trying to DELETE
200
-		// a non-empty folder
201
-		$result = $this->simpleResponse('DELETE', $path . '/', null, 204);
202
-		$this->statCache->clear($path . '/');
203
-		$this->statCache->remove($path);
204
-		return $result;
205
-	}
206
-
207
-	/** {@inheritdoc} */
208
-	public function opendir($path) {
209
-		$this->init();
210
-		$path = $this->cleanPath($path);
211
-		try {
212
-			$response = $this->client->propFind(
213
-				$this->encodePath($path),
214
-				['{DAV:}href'],
215
-				1
216
-			);
217
-			if ($response === false) {
218
-				return false;
219
-			}
220
-			$content = [];
221
-			$files = array_keys($response);
222
-			array_shift($files); //the first entry is the current directory
223
-
224
-			if (!$this->statCache->hasKey($path)) {
225
-				$this->statCache->set($path, true);
226
-			}
227
-			foreach ($files as $file) {
228
-				$file = urldecode($file);
229
-				// do not store the real entry, we might not have all properties
230
-				if (!$this->statCache->hasKey($path)) {
231
-					$this->statCache->set($file, true);
232
-				}
233
-				$file = basename($file);
234
-				$content[] = $file;
235
-			}
236
-			return IteratorDirectory::wrap($content);
237
-		} catch (\Exception $e) {
238
-			$this->convertException($e, $path);
239
-		}
240
-		return false;
241
-	}
242
-
243
-	/**
244
-	 * Propfind call with cache handling.
245
-	 *
246
-	 * First checks if information is cached.
247
-	 * If not, request it from the server then store to cache.
248
-	 *
249
-	 * @param string $path path to propfind
250
-	 *
251
-	 * @return array|boolean propfind response or false if the entry was not found
252
-	 *
253
-	 * @throws ClientHttpException
254
-	 */
255
-	protected function propfind($path) {
256
-		$path = $this->cleanPath($path);
257
-		$cachedResponse = $this->statCache->get($path);
258
-		// we either don't know it, or we know it exists but need more details
259
-		if (is_null($cachedResponse) || $cachedResponse === true) {
260
-			$this->init();
261
-			try {
262
-				$response = $this->client->propFind(
263
-					$this->encodePath($path),
264
-					array(
265
-						'{DAV:}getlastmodified',
266
-						'{DAV:}getcontentlength',
267
-						'{DAV:}getcontenttype',
268
-						'{http://owncloud.org/ns}permissions',
269
-						'{http://open-collaboration-services.org/ns}share-permissions',
270
-						'{DAV:}resourcetype',
271
-						'{DAV:}getetag',
272
-					)
273
-				);
274
-				$this->statCache->set($path, $response);
275
-			} catch (ClientHttpException $e) {
276
-				if ($e->getHttpStatus() === 404) {
277
-					$this->statCache->clear($path . '/');
278
-					$this->statCache->set($path, false);
279
-					return false;
280
-				}
281
-				$this->convertException($e, $path);
282
-			} catch (\Exception $e) {
283
-				$this->convertException($e, $path);
284
-			}
285
-		} else {
286
-			$response = $cachedResponse;
287
-		}
288
-		return $response;
289
-	}
290
-
291
-	/** {@inheritdoc} */
292
-	public function filetype($path) {
293
-		try {
294
-			$response = $this->propfind($path);
295
-			if ($response === false) {
296
-				return false;
297
-			}
298
-			$responseType = [];
299
-			if (isset($response["{DAV:}resourcetype"])) {
300
-				/** @var ResourceType[] $response */
301
-				$responseType = $response["{DAV:}resourcetype"]->getValue();
302
-			}
303
-			return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
304
-		} catch (\Exception $e) {
305
-			$this->convertException($e, $path);
306
-		}
307
-		return false;
308
-	}
309
-
310
-	/** {@inheritdoc} */
311
-	public function file_exists($path) {
312
-		try {
313
-			$path = $this->cleanPath($path);
314
-			$cachedState = $this->statCache->get($path);
315
-			if ($cachedState === false) {
316
-				// we know the file doesn't exist
317
-				return false;
318
-			} else if (!is_null($cachedState)) {
319
-				return true;
320
-			}
321
-			// need to get from server
322
-			return ($this->propfind($path) !== false);
323
-		} catch (\Exception $e) {
324
-			$this->convertException($e, $path);
325
-		}
326
-		return false;
327
-	}
328
-
329
-	/** {@inheritdoc} */
330
-	public function unlink($path) {
331
-		$this->init();
332
-		$path = $this->cleanPath($path);
333
-		$result = $this->simpleResponse('DELETE', $path, null, 204);
334
-		$this->statCache->clear($path . '/');
335
-		$this->statCache->remove($path);
336
-		return $result;
337
-	}
338
-
339
-	/** {@inheritdoc} */
340
-	public function fopen($path, $mode) {
341
-		$this->init();
342
-		$path = $this->cleanPath($path);
343
-		switch ($mode) {
344
-			case 'r':
345
-			case 'rb':
346
-				try {
347
-					$response = $this->httpClientService
348
-							->newClient()
349
-							->get($this->createBaseUri() . $this->encodePath($path), [
350
-									'auth' => [$this->user, $this->password],
351
-									'stream' => true
352
-							]);
353
-				} catch (RequestException $e) {
354
-					if ($e->getResponse() instanceof ResponseInterface
355
-						&& $e->getResponse()->getStatusCode() === 404) {
356
-						return false;
357
-					} else {
358
-						throw $e;
359
-					}
360
-				}
361
-
362
-				if ($response->getStatusCode() !== Http::STATUS_OK) {
363
-					if ($response->getStatusCode() === Http::STATUS_LOCKED) {
364
-						throw new \OCP\Lock\LockedException($path);
365
-					} else {
366
-						Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), Util::ERROR);
367
-					}
368
-				}
369
-
370
-				return $response->getBody();
371
-			case 'w':
372
-			case 'wb':
373
-			case 'a':
374
-			case 'ab':
375
-			case 'r+':
376
-			case 'w+':
377
-			case 'wb+':
378
-			case 'a+':
379
-			case 'x':
380
-			case 'x+':
381
-			case 'c':
382
-			case 'c+':
383
-				//emulate these
384
-				$tempManager = \OC::$server->getTempManager();
385
-				if (strrpos($path, '.') !== false) {
386
-					$ext = substr($path, strrpos($path, '.'));
387
-				} else {
388
-					$ext = '';
389
-				}
390
-				if ($this->file_exists($path)) {
391
-					if (!$this->isUpdatable($path)) {
392
-						return false;
393
-					}
394
-					if ($mode === 'w' or $mode === 'w+') {
395
-						$tmpFile = $tempManager->getTemporaryFile($ext);
396
-					} else {
397
-						$tmpFile = $this->getCachedFile($path);
398
-					}
399
-				} else {
400
-					if (!$this->isCreatable(dirname($path))) {
401
-						return false;
402
-					}
403
-					$tmpFile = $tempManager->getTemporaryFile($ext);
404
-				}
405
-				$handle = fopen($tmpFile, $mode);
406
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
407
-					$this->writeBack($tmpFile, $path);
408
-				});
409
-		}
410
-	}
411
-
412
-	/**
413
-	 * @param string $tmpFile
414
-	 */
415
-	public function writeBack($tmpFile, $path) {
416
-		$this->uploadFile($tmpFile, $path);
417
-		unlink($tmpFile);
418
-	}
419
-
420
-	/** {@inheritdoc} */
421
-	public function free_space($path) {
422
-		$this->init();
423
-		$path = $this->cleanPath($path);
424
-		try {
425
-			// TODO: cacheable ?
426
-			$response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
427
-			if ($response === false) {
428
-				return FileInfo::SPACE_UNKNOWN;
429
-			}
430
-			if (isset($response['{DAV:}quota-available-bytes'])) {
431
-				return (int)$response['{DAV:}quota-available-bytes'];
432
-			} else {
433
-				return FileInfo::SPACE_UNKNOWN;
434
-			}
435
-		} catch (\Exception $e) {
436
-			return FileInfo::SPACE_UNKNOWN;
437
-		}
438
-	}
439
-
440
-	/** {@inheritdoc} */
441
-	public function touch($path, $mtime = null) {
442
-		$this->init();
443
-		if (is_null($mtime)) {
444
-			$mtime = time();
445
-		}
446
-		$path = $this->cleanPath($path);
447
-
448
-		// if file exists, update the mtime, else create a new empty file
449
-		if ($this->file_exists($path)) {
450
-			try {
451
-				$this->statCache->remove($path);
452
-				$this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
453
-				// non-owncloud clients might not have accepted the property, need to recheck it
454
-				$response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
455
-				if ($response === false) {
456
-					return false;
457
-				}
458
-				if (isset($response['{DAV:}getlastmodified'])) {
459
-					$remoteMtime = strtotime($response['{DAV:}getlastmodified']);
460
-					if ($remoteMtime !== $mtime) {
461
-						// server has not accepted the mtime
462
-						return false;
463
-					}
464
-				}
465
-			} catch (ClientHttpException $e) {
466
-				if ($e->getHttpStatus() === 501) {
467
-					return false;
468
-				}
469
-				$this->convertException($e, $path);
470
-				return false;
471
-			} catch (\Exception $e) {
472
-				$this->convertException($e, $path);
473
-				return false;
474
-			}
475
-		} else {
476
-			$this->file_put_contents($path, '');
477
-		}
478
-		return true;
479
-	}
480
-
481
-	/**
482
-	 * @param string $path
483
-	 * @param string $data
484
-	 * @return int
485
-	 */
486
-	public function file_put_contents($path, $data) {
487
-		$path = $this->cleanPath($path);
488
-		$result = parent::file_put_contents($path, $data);
489
-		$this->statCache->remove($path);
490
-		return $result;
491
-	}
492
-
493
-	/**
494
-	 * @param string $path
495
-	 * @param string $target
496
-	 */
497
-	protected function uploadFile($path, $target) {
498
-		$this->init();
499
-
500
-		// invalidate
501
-		$target = $this->cleanPath($target);
502
-		$this->statCache->remove($target);
503
-		$source = fopen($path, 'r');
504
-
505
-		$this->httpClientService
506
-			->newClient()
507
-			->put($this->createBaseUri() . $this->encodePath($target), [
508
-				'body' => $source,
509
-				'auth' => [$this->user, $this->password]
510
-			]);
511
-
512
-		$this->removeCachedFile($target);
513
-	}
514
-
515
-	/** {@inheritdoc} */
516
-	public function rename($path1, $path2) {
517
-		$this->init();
518
-		$path1 = $this->cleanPath($path1);
519
-		$path2 = $this->cleanPath($path2);
520
-		try {
521
-			// overwrite directory ?
522
-			if ($this->is_dir($path2)) {
523
-				// needs trailing slash in destination
524
-				$path2 = rtrim($path2, '/') . '/';
525
-			}
526
-			$this->client->request(
527
-				'MOVE',
528
-				$this->encodePath($path1),
529
-				null,
530
-				[
531
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
532
-				]
533
-			);
534
-			$this->statCache->clear($path1 . '/');
535
-			$this->statCache->clear($path2 . '/');
536
-			$this->statCache->set($path1, false);
537
-			$this->statCache->set($path2, true);
538
-			$this->removeCachedFile($path1);
539
-			$this->removeCachedFile($path2);
540
-			return true;
541
-		} catch (\Exception $e) {
542
-			$this->convertException($e);
543
-		}
544
-		return false;
545
-	}
546
-
547
-	/** {@inheritdoc} */
548
-	public function copy($path1, $path2) {
549
-		$this->init();
550
-		$path1 = $this->cleanPath($path1);
551
-		$path2 = $this->cleanPath($path2);
552
-		try {
553
-			// overwrite directory ?
554
-			if ($this->is_dir($path2)) {
555
-				// needs trailing slash in destination
556
-				$path2 = rtrim($path2, '/') . '/';
557
-			}
558
-			$this->client->request(
559
-				'COPY',
560
-				$this->encodePath($path1),
561
-				null,
562
-				[
563
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
564
-				]
565
-			);
566
-			$this->statCache->clear($path2 . '/');
567
-			$this->statCache->set($path2, true);
568
-			$this->removeCachedFile($path2);
569
-			return true;
570
-		} catch (\Exception $e) {
571
-			$this->convertException($e);
572
-		}
573
-		return false;
574
-	}
575
-
576
-	/** {@inheritdoc} */
577
-	public function stat($path) {
578
-		try {
579
-			$response = $this->propfind($path);
580
-			if (!$response) {
581
-				return false;
582
-			}
583
-			return [
584
-				'mtime' => strtotime($response['{DAV:}getlastmodified']),
585
-				'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
586
-			];
587
-		} catch (\Exception $e) {
588
-			$this->convertException($e, $path);
589
-		}
590
-		return array();
591
-	}
592
-
593
-	/** {@inheritdoc} */
594
-	public function getMimeType($path) {
595
-		try {
596
-			$response = $this->propfind($path);
597
-			if ($response === false) {
598
-				return false;
599
-			}
600
-			$responseType = [];
601
-			if (isset($response["{DAV:}resourcetype"])) {
602
-				/** @var ResourceType[] $response */
603
-				$responseType = $response["{DAV:}resourcetype"]->getValue();
604
-			}
605
-			$type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
606
-			if ($type == 'dir') {
607
-				return 'httpd/unix-directory';
608
-			} elseif (isset($response['{DAV:}getcontenttype'])) {
609
-				return $response['{DAV:}getcontenttype'];
610
-			} else {
611
-				return false;
612
-			}
613
-		} catch (\Exception $e) {
614
-			$this->convertException($e, $path);
615
-		}
616
-		return false;
617
-	}
618
-
619
-	/**
620
-	 * @param string $path
621
-	 * @return string
622
-	 */
623
-	public function cleanPath($path) {
624
-		if ($path === '') {
625
-			return $path;
626
-		}
627
-		$path = Filesystem::normalizePath($path);
628
-		// remove leading slash
629
-		return substr($path, 1);
630
-	}
631
-
632
-	/**
633
-	 * URL encodes the given path but keeps the slashes
634
-	 *
635
-	 * @param string $path to encode
636
-	 * @return string encoded path
637
-	 */
638
-	protected function encodePath($path) {
639
-		// slashes need to stay
640
-		return str_replace('%2F', '/', rawurlencode($path));
641
-	}
642
-
643
-	/**
644
-	 * @param string $method
645
-	 * @param string $path
646
-	 * @param string|resource|null $body
647
-	 * @param int $expected
648
-	 * @return bool
649
-	 * @throws StorageInvalidException
650
-	 * @throws StorageNotAvailableException
651
-	 */
652
-	protected function simpleResponse($method, $path, $body, $expected) {
653
-		$path = $this->cleanPath($path);
654
-		try {
655
-			$response = $this->client->request($method, $this->encodePath($path), $body);
656
-			return $response['statusCode'] == $expected;
657
-		} catch (ClientHttpException $e) {
658
-			if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
659
-				$this->statCache->clear($path . '/');
660
-				$this->statCache->set($path, false);
661
-				return false;
662
-			}
663
-
664
-			$this->convertException($e, $path);
665
-		} catch (\Exception $e) {
666
-			$this->convertException($e, $path);
667
-		}
668
-		return false;
669
-	}
670
-
671
-	/**
672
-	 * check if curl is installed
673
-	 */
674
-	public static function checkDependencies() {
675
-		return true;
676
-	}
677
-
678
-	/** {@inheritdoc} */
679
-	public function isUpdatable($path) {
680
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
681
-	}
682
-
683
-	/** {@inheritdoc} */
684
-	public function isCreatable($path) {
685
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
686
-	}
687
-
688
-	/** {@inheritdoc} */
689
-	public function isSharable($path) {
690
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
691
-	}
692
-
693
-	/** {@inheritdoc} */
694
-	public function isDeletable($path) {
695
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
696
-	}
697
-
698
-	/** {@inheritdoc} */
699
-	public function getPermissions($path) {
700
-		$this->init();
701
-		$path = $this->cleanPath($path);
702
-		$response = $this->propfind($path);
703
-		if ($response === false) {
704
-			return 0;
705
-		}
706
-		if (isset($response['{http://owncloud.org/ns}permissions'])) {
707
-			return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
708
-		} else if ($this->is_dir($path)) {
709
-			return Constants::PERMISSION_ALL;
710
-		} else if ($this->file_exists($path)) {
711
-			return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
712
-		} else {
713
-			return 0;
714
-		}
715
-	}
716
-
717
-	/** {@inheritdoc} */
718
-	public function getETag($path) {
719
-		$this->init();
720
-		$path = $this->cleanPath($path);
721
-		$response = $this->propfind($path);
722
-		if ($response === false) {
723
-			return null;
724
-		}
725
-		if (isset($response['{DAV:}getetag'])) {
726
-			return trim($response['{DAV:}getetag'], '"');
727
-		}
728
-		return parent::getEtag($path);
729
-	}
730
-
731
-	/**
732
-	 * @param string $permissionsString
733
-	 * @return int
734
-	 */
735
-	protected function parsePermissions($permissionsString) {
736
-		$permissions = Constants::PERMISSION_READ;
737
-		if (strpos($permissionsString, 'R') !== false) {
738
-			$permissions |= Constants::PERMISSION_SHARE;
739
-		}
740
-		if (strpos($permissionsString, 'D') !== false) {
741
-			$permissions |= Constants::PERMISSION_DELETE;
742
-		}
743
-		if (strpos($permissionsString, 'W') !== false) {
744
-			$permissions |= Constants::PERMISSION_UPDATE;
745
-		}
746
-		if (strpos($permissionsString, 'CK') !== false) {
747
-			$permissions |= Constants::PERMISSION_CREATE;
748
-			$permissions |= Constants::PERMISSION_UPDATE;
749
-		}
750
-		return $permissions;
751
-	}
752
-
753
-	/**
754
-	 * check if a file or folder has been updated since $time
755
-	 *
756
-	 * @param string $path
757
-	 * @param int $time
758
-	 * @throws \OCP\Files\StorageNotAvailableException
759
-	 * @return bool
760
-	 */
761
-	public function hasUpdated($path, $time) {
762
-		$this->init();
763
-		$path = $this->cleanPath($path);
764
-		try {
765
-			// force refresh for $path
766
-			$this->statCache->remove($path);
767
-			$response = $this->propfind($path);
768
-			if ($response === false) {
769
-				if ($path === '') {
770
-					// if root is gone it means the storage is not available
771
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
772
-				}
773
-				return false;
774
-			}
775
-			if (isset($response['{DAV:}getetag'])) {
776
-				$cachedData = $this->getCache()->get($path);
777
-				$etag = null;
778
-				if (isset($response['{DAV:}getetag'])) {
779
-					$etag = trim($response['{DAV:}getetag'], '"');
780
-				}
781
-				if (!empty($etag) && $cachedData['etag'] !== $etag) {
782
-					return true;
783
-				} else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
784
-					$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
785
-					return $sharePermissions !== $cachedData['permissions'];
786
-				} else if (isset($response['{http://owncloud.org/ns}permissions'])) {
787
-					$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
788
-					return $permissions !== $cachedData['permissions'];
789
-				} else {
790
-					return false;
791
-				}
792
-			} else {
793
-				$remoteMtime = strtotime($response['{DAV:}getlastmodified']);
794
-				return $remoteMtime > $time;
795
-			}
796
-		} catch (ClientHttpException $e) {
797
-			if ($e->getHttpStatus() === 405) {
798
-				if ($path === '') {
799
-					// if root is gone it means the storage is not available
800
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
801
-				}
802
-				return false;
803
-			}
804
-			$this->convertException($e, $path);
805
-			return false;
806
-		} catch (\Exception $e) {
807
-			$this->convertException($e, $path);
808
-			return false;
809
-		}
810
-	}
811
-
812
-	/**
813
-	 * Interpret the given exception and decide whether it is due to an
814
-	 * unavailable storage, invalid storage or other.
815
-	 * This will either throw StorageInvalidException, StorageNotAvailableException
816
-	 * or do nothing.
817
-	 *
818
-	 * @param Exception $e sabre exception
819
-	 * @param string $path optional path from the operation
820
-	 *
821
-	 * @throws StorageInvalidException if the storage is invalid, for example
822
-	 * when the authentication expired or is invalid
823
-	 * @throws StorageNotAvailableException if the storage is not available,
824
-	 * which might be temporary
825
-	 */
826
-	protected function convertException(Exception $e, $path = '') {
827
-		\OC::$server->getLogger()->logException($e);
828
-		Util::writeLog('files_external', $e->getMessage(), Util::ERROR);
829
-		if ($e instanceof ClientHttpException) {
830
-			if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
831
-				throw new \OCP\Lock\LockedException($path);
832
-			}
833
-			if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
834
-				// either password was changed or was invalid all along
835
-				throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
836
-			} else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
837
-				// ignore exception for MethodNotAllowed, false will be returned
838
-				return;
839
-			}
840
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
841
-		} else if ($e instanceof ClientException) {
842
-			// connection timeout or refused, server could be temporarily down
843
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
844
-		} else if ($e instanceof \InvalidArgumentException) {
845
-			// parse error because the server returned HTML instead of XML,
846
-			// possibly temporarily down
847
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
848
-		} else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
849
-			// rethrow
850
-			throw $e;
851
-		}
852
-
853
-		// TODO: only log for now, but in the future need to wrap/rethrow exception
854
-	}
62
+    /** @var string */
63
+    protected $password;
64
+    /** @var string */
65
+    protected $user;
66
+    /** @var string */
67
+    protected $authType;
68
+    /** @var string */
69
+    protected $host;
70
+    /** @var bool */
71
+    protected $secure;
72
+    /** @var string */
73
+    protected $root;
74
+    /** @var string */
75
+    protected $certPath;
76
+    /** @var bool */
77
+    protected $ready;
78
+    /** @var Client */
79
+    protected $client;
80
+    /** @var ArrayCache */
81
+    protected $statCache;
82
+    /** @var \OCP\Http\Client\IClientService */
83
+    protected $httpClientService;
84
+
85
+    /**
86
+     * @param array $params
87
+     * @throws \Exception
88
+     */
89
+    public function __construct($params) {
90
+        $this->statCache = new ArrayCache();
91
+        $this->httpClientService = \OC::$server->getHTTPClientService();
92
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
93
+            $host = $params['host'];
94
+            //remove leading http[s], will be generated in createBaseUri()
95
+            if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
96
+            else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
97
+            $this->host = $host;
98
+            $this->user = $params['user'];
99
+            $this->password = $params['password'];
100
+            if (isset($params['authType'])) {
101
+                $this->authType = $params['authType'];
102
+            }
103
+            if (isset($params['secure'])) {
104
+                if (is_string($params['secure'])) {
105
+                    $this->secure = ($params['secure'] === 'true');
106
+                } else {
107
+                    $this->secure = (bool)$params['secure'];
108
+                }
109
+            } else {
110
+                $this->secure = false;
111
+            }
112
+            if ($this->secure === true) {
113
+                // inject mock for testing
114
+                $certManager = \OC::$server->getCertificateManager();
115
+                if (is_null($certManager)) { //no user
116
+                    $certManager = \OC::$server->getCertificateManager(null);
117
+                }
118
+                $certPath = $certManager->getAbsoluteBundlePath();
119
+                if (file_exists($certPath)) {
120
+                    $this->certPath = $certPath;
121
+                }
122
+            }
123
+            $this->root = isset($params['root']) ? $params['root'] : '/';
124
+            if (!$this->root || $this->root[0] != '/') {
125
+                $this->root = '/' . $this->root;
126
+            }
127
+            if (substr($this->root, -1, 1) != '/') {
128
+                $this->root .= '/';
129
+            }
130
+        } else {
131
+            throw new \Exception('Invalid webdav storage configuration');
132
+        }
133
+    }
134
+
135
+    protected function init() {
136
+        if ($this->ready) {
137
+            return;
138
+        }
139
+        $this->ready = true;
140
+
141
+        $settings = [
142
+            'baseUri' => $this->createBaseUri(),
143
+            'userName' => $this->user,
144
+            'password' => $this->password,
145
+        ];
146
+        if (isset($this->authType)) {
147
+            $settings['authType'] = $this->authType;
148
+        }
149
+
150
+        $proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
151
+        if($proxy !== '') {
152
+            $settings['proxy'] = $proxy;
153
+        }
154
+
155
+        $this->client = new Client($settings);
156
+        $this->client->setThrowExceptions(true);
157
+        if ($this->secure === true && $this->certPath) {
158
+            $this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
159
+        }
160
+    }
161
+
162
+    /**
163
+     * Clear the stat cache
164
+     */
165
+    public function clearStatCache() {
166
+        $this->statCache->clear();
167
+    }
168
+
169
+    /** {@inheritdoc} */
170
+    public function getId() {
171
+        return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
172
+    }
173
+
174
+    /** {@inheritdoc} */
175
+    public function createBaseUri() {
176
+        $baseUri = 'http';
177
+        if ($this->secure) {
178
+            $baseUri .= 's';
179
+        }
180
+        $baseUri .= '://' . $this->host . $this->root;
181
+        return $baseUri;
182
+    }
183
+
184
+    /** {@inheritdoc} */
185
+    public function mkdir($path) {
186
+        $this->init();
187
+        $path = $this->cleanPath($path);
188
+        $result = $this->simpleResponse('MKCOL', $path, null, 201);
189
+        if ($result) {
190
+            $this->statCache->set($path, true);
191
+        }
192
+        return $result;
193
+    }
194
+
195
+    /** {@inheritdoc} */
196
+    public function rmdir($path) {
197
+        $this->init();
198
+        $path = $this->cleanPath($path);
199
+        // FIXME: some WebDAV impl return 403 when trying to DELETE
200
+        // a non-empty folder
201
+        $result = $this->simpleResponse('DELETE', $path . '/', null, 204);
202
+        $this->statCache->clear($path . '/');
203
+        $this->statCache->remove($path);
204
+        return $result;
205
+    }
206
+
207
+    /** {@inheritdoc} */
208
+    public function opendir($path) {
209
+        $this->init();
210
+        $path = $this->cleanPath($path);
211
+        try {
212
+            $response = $this->client->propFind(
213
+                $this->encodePath($path),
214
+                ['{DAV:}href'],
215
+                1
216
+            );
217
+            if ($response === false) {
218
+                return false;
219
+            }
220
+            $content = [];
221
+            $files = array_keys($response);
222
+            array_shift($files); //the first entry is the current directory
223
+
224
+            if (!$this->statCache->hasKey($path)) {
225
+                $this->statCache->set($path, true);
226
+            }
227
+            foreach ($files as $file) {
228
+                $file = urldecode($file);
229
+                // do not store the real entry, we might not have all properties
230
+                if (!$this->statCache->hasKey($path)) {
231
+                    $this->statCache->set($file, true);
232
+                }
233
+                $file = basename($file);
234
+                $content[] = $file;
235
+            }
236
+            return IteratorDirectory::wrap($content);
237
+        } catch (\Exception $e) {
238
+            $this->convertException($e, $path);
239
+        }
240
+        return false;
241
+    }
242
+
243
+    /**
244
+     * Propfind call with cache handling.
245
+     *
246
+     * First checks if information is cached.
247
+     * If not, request it from the server then store to cache.
248
+     *
249
+     * @param string $path path to propfind
250
+     *
251
+     * @return array|boolean propfind response or false if the entry was not found
252
+     *
253
+     * @throws ClientHttpException
254
+     */
255
+    protected function propfind($path) {
256
+        $path = $this->cleanPath($path);
257
+        $cachedResponse = $this->statCache->get($path);
258
+        // we either don't know it, or we know it exists but need more details
259
+        if (is_null($cachedResponse) || $cachedResponse === true) {
260
+            $this->init();
261
+            try {
262
+                $response = $this->client->propFind(
263
+                    $this->encodePath($path),
264
+                    array(
265
+                        '{DAV:}getlastmodified',
266
+                        '{DAV:}getcontentlength',
267
+                        '{DAV:}getcontenttype',
268
+                        '{http://owncloud.org/ns}permissions',
269
+                        '{http://open-collaboration-services.org/ns}share-permissions',
270
+                        '{DAV:}resourcetype',
271
+                        '{DAV:}getetag',
272
+                    )
273
+                );
274
+                $this->statCache->set($path, $response);
275
+            } catch (ClientHttpException $e) {
276
+                if ($e->getHttpStatus() === 404) {
277
+                    $this->statCache->clear($path . '/');
278
+                    $this->statCache->set($path, false);
279
+                    return false;
280
+                }
281
+                $this->convertException($e, $path);
282
+            } catch (\Exception $e) {
283
+                $this->convertException($e, $path);
284
+            }
285
+        } else {
286
+            $response = $cachedResponse;
287
+        }
288
+        return $response;
289
+    }
290
+
291
+    /** {@inheritdoc} */
292
+    public function filetype($path) {
293
+        try {
294
+            $response = $this->propfind($path);
295
+            if ($response === false) {
296
+                return false;
297
+            }
298
+            $responseType = [];
299
+            if (isset($response["{DAV:}resourcetype"])) {
300
+                /** @var ResourceType[] $response */
301
+                $responseType = $response["{DAV:}resourcetype"]->getValue();
302
+            }
303
+            return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
304
+        } catch (\Exception $e) {
305
+            $this->convertException($e, $path);
306
+        }
307
+        return false;
308
+    }
309
+
310
+    /** {@inheritdoc} */
311
+    public function file_exists($path) {
312
+        try {
313
+            $path = $this->cleanPath($path);
314
+            $cachedState = $this->statCache->get($path);
315
+            if ($cachedState === false) {
316
+                // we know the file doesn't exist
317
+                return false;
318
+            } else if (!is_null($cachedState)) {
319
+                return true;
320
+            }
321
+            // need to get from server
322
+            return ($this->propfind($path) !== false);
323
+        } catch (\Exception $e) {
324
+            $this->convertException($e, $path);
325
+        }
326
+        return false;
327
+    }
328
+
329
+    /** {@inheritdoc} */
330
+    public function unlink($path) {
331
+        $this->init();
332
+        $path = $this->cleanPath($path);
333
+        $result = $this->simpleResponse('DELETE', $path, null, 204);
334
+        $this->statCache->clear($path . '/');
335
+        $this->statCache->remove($path);
336
+        return $result;
337
+    }
338
+
339
+    /** {@inheritdoc} */
340
+    public function fopen($path, $mode) {
341
+        $this->init();
342
+        $path = $this->cleanPath($path);
343
+        switch ($mode) {
344
+            case 'r':
345
+            case 'rb':
346
+                try {
347
+                    $response = $this->httpClientService
348
+                            ->newClient()
349
+                            ->get($this->createBaseUri() . $this->encodePath($path), [
350
+                                    'auth' => [$this->user, $this->password],
351
+                                    'stream' => true
352
+                            ]);
353
+                } catch (RequestException $e) {
354
+                    if ($e->getResponse() instanceof ResponseInterface
355
+                        && $e->getResponse()->getStatusCode() === 404) {
356
+                        return false;
357
+                    } else {
358
+                        throw $e;
359
+                    }
360
+                }
361
+
362
+                if ($response->getStatusCode() !== Http::STATUS_OK) {
363
+                    if ($response->getStatusCode() === Http::STATUS_LOCKED) {
364
+                        throw new \OCP\Lock\LockedException($path);
365
+                    } else {
366
+                        Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), Util::ERROR);
367
+                    }
368
+                }
369
+
370
+                return $response->getBody();
371
+            case 'w':
372
+            case 'wb':
373
+            case 'a':
374
+            case 'ab':
375
+            case 'r+':
376
+            case 'w+':
377
+            case 'wb+':
378
+            case 'a+':
379
+            case 'x':
380
+            case 'x+':
381
+            case 'c':
382
+            case 'c+':
383
+                //emulate these
384
+                $tempManager = \OC::$server->getTempManager();
385
+                if (strrpos($path, '.') !== false) {
386
+                    $ext = substr($path, strrpos($path, '.'));
387
+                } else {
388
+                    $ext = '';
389
+                }
390
+                if ($this->file_exists($path)) {
391
+                    if (!$this->isUpdatable($path)) {
392
+                        return false;
393
+                    }
394
+                    if ($mode === 'w' or $mode === 'w+') {
395
+                        $tmpFile = $tempManager->getTemporaryFile($ext);
396
+                    } else {
397
+                        $tmpFile = $this->getCachedFile($path);
398
+                    }
399
+                } else {
400
+                    if (!$this->isCreatable(dirname($path))) {
401
+                        return false;
402
+                    }
403
+                    $tmpFile = $tempManager->getTemporaryFile($ext);
404
+                }
405
+                $handle = fopen($tmpFile, $mode);
406
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
407
+                    $this->writeBack($tmpFile, $path);
408
+                });
409
+        }
410
+    }
411
+
412
+    /**
413
+     * @param string $tmpFile
414
+     */
415
+    public function writeBack($tmpFile, $path) {
416
+        $this->uploadFile($tmpFile, $path);
417
+        unlink($tmpFile);
418
+    }
419
+
420
+    /** {@inheritdoc} */
421
+    public function free_space($path) {
422
+        $this->init();
423
+        $path = $this->cleanPath($path);
424
+        try {
425
+            // TODO: cacheable ?
426
+            $response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
427
+            if ($response === false) {
428
+                return FileInfo::SPACE_UNKNOWN;
429
+            }
430
+            if (isset($response['{DAV:}quota-available-bytes'])) {
431
+                return (int)$response['{DAV:}quota-available-bytes'];
432
+            } else {
433
+                return FileInfo::SPACE_UNKNOWN;
434
+            }
435
+        } catch (\Exception $e) {
436
+            return FileInfo::SPACE_UNKNOWN;
437
+        }
438
+    }
439
+
440
+    /** {@inheritdoc} */
441
+    public function touch($path, $mtime = null) {
442
+        $this->init();
443
+        if (is_null($mtime)) {
444
+            $mtime = time();
445
+        }
446
+        $path = $this->cleanPath($path);
447
+
448
+        // if file exists, update the mtime, else create a new empty file
449
+        if ($this->file_exists($path)) {
450
+            try {
451
+                $this->statCache->remove($path);
452
+                $this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
453
+                // non-owncloud clients might not have accepted the property, need to recheck it
454
+                $response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
455
+                if ($response === false) {
456
+                    return false;
457
+                }
458
+                if (isset($response['{DAV:}getlastmodified'])) {
459
+                    $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
460
+                    if ($remoteMtime !== $mtime) {
461
+                        // server has not accepted the mtime
462
+                        return false;
463
+                    }
464
+                }
465
+            } catch (ClientHttpException $e) {
466
+                if ($e->getHttpStatus() === 501) {
467
+                    return false;
468
+                }
469
+                $this->convertException($e, $path);
470
+                return false;
471
+            } catch (\Exception $e) {
472
+                $this->convertException($e, $path);
473
+                return false;
474
+            }
475
+        } else {
476
+            $this->file_put_contents($path, '');
477
+        }
478
+        return true;
479
+    }
480
+
481
+    /**
482
+     * @param string $path
483
+     * @param string $data
484
+     * @return int
485
+     */
486
+    public function file_put_contents($path, $data) {
487
+        $path = $this->cleanPath($path);
488
+        $result = parent::file_put_contents($path, $data);
489
+        $this->statCache->remove($path);
490
+        return $result;
491
+    }
492
+
493
+    /**
494
+     * @param string $path
495
+     * @param string $target
496
+     */
497
+    protected function uploadFile($path, $target) {
498
+        $this->init();
499
+
500
+        // invalidate
501
+        $target = $this->cleanPath($target);
502
+        $this->statCache->remove($target);
503
+        $source = fopen($path, 'r');
504
+
505
+        $this->httpClientService
506
+            ->newClient()
507
+            ->put($this->createBaseUri() . $this->encodePath($target), [
508
+                'body' => $source,
509
+                'auth' => [$this->user, $this->password]
510
+            ]);
511
+
512
+        $this->removeCachedFile($target);
513
+    }
514
+
515
+    /** {@inheritdoc} */
516
+    public function rename($path1, $path2) {
517
+        $this->init();
518
+        $path1 = $this->cleanPath($path1);
519
+        $path2 = $this->cleanPath($path2);
520
+        try {
521
+            // overwrite directory ?
522
+            if ($this->is_dir($path2)) {
523
+                // needs trailing slash in destination
524
+                $path2 = rtrim($path2, '/') . '/';
525
+            }
526
+            $this->client->request(
527
+                'MOVE',
528
+                $this->encodePath($path1),
529
+                null,
530
+                [
531
+                    'Destination' => $this->createBaseUri() . $this->encodePath($path2),
532
+                ]
533
+            );
534
+            $this->statCache->clear($path1 . '/');
535
+            $this->statCache->clear($path2 . '/');
536
+            $this->statCache->set($path1, false);
537
+            $this->statCache->set($path2, true);
538
+            $this->removeCachedFile($path1);
539
+            $this->removeCachedFile($path2);
540
+            return true;
541
+        } catch (\Exception $e) {
542
+            $this->convertException($e);
543
+        }
544
+        return false;
545
+    }
546
+
547
+    /** {@inheritdoc} */
548
+    public function copy($path1, $path2) {
549
+        $this->init();
550
+        $path1 = $this->cleanPath($path1);
551
+        $path2 = $this->cleanPath($path2);
552
+        try {
553
+            // overwrite directory ?
554
+            if ($this->is_dir($path2)) {
555
+                // needs trailing slash in destination
556
+                $path2 = rtrim($path2, '/') . '/';
557
+            }
558
+            $this->client->request(
559
+                'COPY',
560
+                $this->encodePath($path1),
561
+                null,
562
+                [
563
+                    'Destination' => $this->createBaseUri() . $this->encodePath($path2),
564
+                ]
565
+            );
566
+            $this->statCache->clear($path2 . '/');
567
+            $this->statCache->set($path2, true);
568
+            $this->removeCachedFile($path2);
569
+            return true;
570
+        } catch (\Exception $e) {
571
+            $this->convertException($e);
572
+        }
573
+        return false;
574
+    }
575
+
576
+    /** {@inheritdoc} */
577
+    public function stat($path) {
578
+        try {
579
+            $response = $this->propfind($path);
580
+            if (!$response) {
581
+                return false;
582
+            }
583
+            return [
584
+                'mtime' => strtotime($response['{DAV:}getlastmodified']),
585
+                'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
586
+            ];
587
+        } catch (\Exception $e) {
588
+            $this->convertException($e, $path);
589
+        }
590
+        return array();
591
+    }
592
+
593
+    /** {@inheritdoc} */
594
+    public function getMimeType($path) {
595
+        try {
596
+            $response = $this->propfind($path);
597
+            if ($response === false) {
598
+                return false;
599
+            }
600
+            $responseType = [];
601
+            if (isset($response["{DAV:}resourcetype"])) {
602
+                /** @var ResourceType[] $response */
603
+                $responseType = $response["{DAV:}resourcetype"]->getValue();
604
+            }
605
+            $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
606
+            if ($type == 'dir') {
607
+                return 'httpd/unix-directory';
608
+            } elseif (isset($response['{DAV:}getcontenttype'])) {
609
+                return $response['{DAV:}getcontenttype'];
610
+            } else {
611
+                return false;
612
+            }
613
+        } catch (\Exception $e) {
614
+            $this->convertException($e, $path);
615
+        }
616
+        return false;
617
+    }
618
+
619
+    /**
620
+     * @param string $path
621
+     * @return string
622
+     */
623
+    public function cleanPath($path) {
624
+        if ($path === '') {
625
+            return $path;
626
+        }
627
+        $path = Filesystem::normalizePath($path);
628
+        // remove leading slash
629
+        return substr($path, 1);
630
+    }
631
+
632
+    /**
633
+     * URL encodes the given path but keeps the slashes
634
+     *
635
+     * @param string $path to encode
636
+     * @return string encoded path
637
+     */
638
+    protected function encodePath($path) {
639
+        // slashes need to stay
640
+        return str_replace('%2F', '/', rawurlencode($path));
641
+    }
642
+
643
+    /**
644
+     * @param string $method
645
+     * @param string $path
646
+     * @param string|resource|null $body
647
+     * @param int $expected
648
+     * @return bool
649
+     * @throws StorageInvalidException
650
+     * @throws StorageNotAvailableException
651
+     */
652
+    protected function simpleResponse($method, $path, $body, $expected) {
653
+        $path = $this->cleanPath($path);
654
+        try {
655
+            $response = $this->client->request($method, $this->encodePath($path), $body);
656
+            return $response['statusCode'] == $expected;
657
+        } catch (ClientHttpException $e) {
658
+            if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
659
+                $this->statCache->clear($path . '/');
660
+                $this->statCache->set($path, false);
661
+                return false;
662
+            }
663
+
664
+            $this->convertException($e, $path);
665
+        } catch (\Exception $e) {
666
+            $this->convertException($e, $path);
667
+        }
668
+        return false;
669
+    }
670
+
671
+    /**
672
+     * check if curl is installed
673
+     */
674
+    public static function checkDependencies() {
675
+        return true;
676
+    }
677
+
678
+    /** {@inheritdoc} */
679
+    public function isUpdatable($path) {
680
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
681
+    }
682
+
683
+    /** {@inheritdoc} */
684
+    public function isCreatable($path) {
685
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
686
+    }
687
+
688
+    /** {@inheritdoc} */
689
+    public function isSharable($path) {
690
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
691
+    }
692
+
693
+    /** {@inheritdoc} */
694
+    public function isDeletable($path) {
695
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
696
+    }
697
+
698
+    /** {@inheritdoc} */
699
+    public function getPermissions($path) {
700
+        $this->init();
701
+        $path = $this->cleanPath($path);
702
+        $response = $this->propfind($path);
703
+        if ($response === false) {
704
+            return 0;
705
+        }
706
+        if (isset($response['{http://owncloud.org/ns}permissions'])) {
707
+            return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
708
+        } else if ($this->is_dir($path)) {
709
+            return Constants::PERMISSION_ALL;
710
+        } else if ($this->file_exists($path)) {
711
+            return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
712
+        } else {
713
+            return 0;
714
+        }
715
+    }
716
+
717
+    /** {@inheritdoc} */
718
+    public function getETag($path) {
719
+        $this->init();
720
+        $path = $this->cleanPath($path);
721
+        $response = $this->propfind($path);
722
+        if ($response === false) {
723
+            return null;
724
+        }
725
+        if (isset($response['{DAV:}getetag'])) {
726
+            return trim($response['{DAV:}getetag'], '"');
727
+        }
728
+        return parent::getEtag($path);
729
+    }
730
+
731
+    /**
732
+     * @param string $permissionsString
733
+     * @return int
734
+     */
735
+    protected function parsePermissions($permissionsString) {
736
+        $permissions = Constants::PERMISSION_READ;
737
+        if (strpos($permissionsString, 'R') !== false) {
738
+            $permissions |= Constants::PERMISSION_SHARE;
739
+        }
740
+        if (strpos($permissionsString, 'D') !== false) {
741
+            $permissions |= Constants::PERMISSION_DELETE;
742
+        }
743
+        if (strpos($permissionsString, 'W') !== false) {
744
+            $permissions |= Constants::PERMISSION_UPDATE;
745
+        }
746
+        if (strpos($permissionsString, 'CK') !== false) {
747
+            $permissions |= Constants::PERMISSION_CREATE;
748
+            $permissions |= Constants::PERMISSION_UPDATE;
749
+        }
750
+        return $permissions;
751
+    }
752
+
753
+    /**
754
+     * check if a file or folder has been updated since $time
755
+     *
756
+     * @param string $path
757
+     * @param int $time
758
+     * @throws \OCP\Files\StorageNotAvailableException
759
+     * @return bool
760
+     */
761
+    public function hasUpdated($path, $time) {
762
+        $this->init();
763
+        $path = $this->cleanPath($path);
764
+        try {
765
+            // force refresh for $path
766
+            $this->statCache->remove($path);
767
+            $response = $this->propfind($path);
768
+            if ($response === false) {
769
+                if ($path === '') {
770
+                    // if root is gone it means the storage is not available
771
+                    throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
772
+                }
773
+                return false;
774
+            }
775
+            if (isset($response['{DAV:}getetag'])) {
776
+                $cachedData = $this->getCache()->get($path);
777
+                $etag = null;
778
+                if (isset($response['{DAV:}getetag'])) {
779
+                    $etag = trim($response['{DAV:}getetag'], '"');
780
+                }
781
+                if (!empty($etag) && $cachedData['etag'] !== $etag) {
782
+                    return true;
783
+                } else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
784
+                    $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
785
+                    return $sharePermissions !== $cachedData['permissions'];
786
+                } else if (isset($response['{http://owncloud.org/ns}permissions'])) {
787
+                    $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
788
+                    return $permissions !== $cachedData['permissions'];
789
+                } else {
790
+                    return false;
791
+                }
792
+            } else {
793
+                $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
794
+                return $remoteMtime > $time;
795
+            }
796
+        } catch (ClientHttpException $e) {
797
+            if ($e->getHttpStatus() === 405) {
798
+                if ($path === '') {
799
+                    // if root is gone it means the storage is not available
800
+                    throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
801
+                }
802
+                return false;
803
+            }
804
+            $this->convertException($e, $path);
805
+            return false;
806
+        } catch (\Exception $e) {
807
+            $this->convertException($e, $path);
808
+            return false;
809
+        }
810
+    }
811
+
812
+    /**
813
+     * Interpret the given exception and decide whether it is due to an
814
+     * unavailable storage, invalid storage or other.
815
+     * This will either throw StorageInvalidException, StorageNotAvailableException
816
+     * or do nothing.
817
+     *
818
+     * @param Exception $e sabre exception
819
+     * @param string $path optional path from the operation
820
+     *
821
+     * @throws StorageInvalidException if the storage is invalid, for example
822
+     * when the authentication expired or is invalid
823
+     * @throws StorageNotAvailableException if the storage is not available,
824
+     * which might be temporary
825
+     */
826
+    protected function convertException(Exception $e, $path = '') {
827
+        \OC::$server->getLogger()->logException($e);
828
+        Util::writeLog('files_external', $e->getMessage(), Util::ERROR);
829
+        if ($e instanceof ClientHttpException) {
830
+            if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
831
+                throw new \OCP\Lock\LockedException($path);
832
+            }
833
+            if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
834
+                // either password was changed or was invalid all along
835
+                throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
836
+            } else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
837
+                // ignore exception for MethodNotAllowed, false will be returned
838
+                return;
839
+            }
840
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
841
+        } else if ($e instanceof ClientException) {
842
+            // connection timeout or refused, server could be temporarily down
843
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
844
+        } else if ($e instanceof \InvalidArgumentException) {
845
+            // parse error because the server returned HTML instead of XML,
846
+            // possibly temporarily down
847
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
848
+        } else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
849
+            // rethrow
850
+            throw $e;
851
+        }
852
+
853
+        // TODO: only log for now, but in the future need to wrap/rethrow exception
854
+    }
855 855
 }
856 856
 
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 				if (is_string($params['secure'])) {
105 105
 					$this->secure = ($params['secure'] === 'true');
106 106
 				} else {
107
-					$this->secure = (bool)$params['secure'];
107
+					$this->secure = (bool) $params['secure'];
108 108
 				}
109 109
 			} else {
110 110
 				$this->secure = false;
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 			}
123 123
 			$this->root = isset($params['root']) ? $params['root'] : '/';
124 124
 			if (!$this->root || $this->root[0] != '/') {
125
-				$this->root = '/' . $this->root;
125
+				$this->root = '/'.$this->root;
126 126
 			}
127 127
 			if (substr($this->root, -1, 1) != '/') {
128 128
 				$this->root .= '/';
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 		}
149 149
 
150 150
 		$proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
151
-		if($proxy !== '') {
151
+		if ($proxy !== '') {
152 152
 			$settings['proxy'] = $proxy;
153 153
 		}
154 154
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 
169 169
 	/** {@inheritdoc} */
170 170
 	public function getId() {
171
-		return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
171
+		return 'webdav::'.$this->user.'@'.$this->host.'/'.$this->root;
172 172
 	}
173 173
 
174 174
 	/** {@inheritdoc} */
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		if ($this->secure) {
178 178
 			$baseUri .= 's';
179 179
 		}
180
-		$baseUri .= '://' . $this->host . $this->root;
180
+		$baseUri .= '://'.$this->host.$this->root;
181 181
 		return $baseUri;
182 182
 	}
183 183
 
@@ -198,8 +198,8 @@  discard block
 block discarded – undo
198 198
 		$path = $this->cleanPath($path);
199 199
 		// FIXME: some WebDAV impl return 403 when trying to DELETE
200 200
 		// a non-empty folder
201
-		$result = $this->simpleResponse('DELETE', $path . '/', null, 204);
202
-		$this->statCache->clear($path . '/');
201
+		$result = $this->simpleResponse('DELETE', $path.'/', null, 204);
202
+		$this->statCache->clear($path.'/');
203 203
 		$this->statCache->remove($path);
204 204
 		return $result;
205 205
 	}
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 				$this->statCache->set($path, $response);
275 275
 			} catch (ClientHttpException $e) {
276 276
 				if ($e->getHttpStatus() === 404) {
277
-					$this->statCache->clear($path . '/');
277
+					$this->statCache->clear($path.'/');
278 278
 					$this->statCache->set($path, false);
279 279
 					return false;
280 280
 				}
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 		$this->init();
332 332
 		$path = $this->cleanPath($path);
333 333
 		$result = $this->simpleResponse('DELETE', $path, null, 204);
334
-		$this->statCache->clear($path . '/');
334
+		$this->statCache->clear($path.'/');
335 335
 		$this->statCache->remove($path);
336 336
 		return $result;
337 337
 	}
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 				try {
347 347
 					$response = $this->httpClientService
348 348
 							->newClient()
349
-							->get($this->createBaseUri() . $this->encodePath($path), [
349
+							->get($this->createBaseUri().$this->encodePath($path), [
350 350
 									'auth' => [$this->user, $this->password],
351 351
 									'stream' => true
352 352
 							]);
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 					if ($response->getStatusCode() === Http::STATUS_LOCKED) {
364 364
 						throw new \OCP\Lock\LockedException($path);
365 365
 					} else {
366
-						Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), Util::ERROR);
366
+						Util::writeLog("webdav client", 'Guzzle get returned status code '.$response->getStatusCode(), Util::ERROR);
367 367
 					}
368 368
 				}
369 369
 
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 					$tmpFile = $tempManager->getTemporaryFile($ext);
404 404
 				}
405 405
 				$handle = fopen($tmpFile, $mode);
406
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
406
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
407 407
 					$this->writeBack($tmpFile, $path);
408 408
 				});
409 409
 		}
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 				return FileInfo::SPACE_UNKNOWN;
429 429
 			}
430 430
 			if (isset($response['{DAV:}quota-available-bytes'])) {
431
-				return (int)$response['{DAV:}quota-available-bytes'];
431
+				return (int) $response['{DAV:}quota-available-bytes'];
432 432
 			} else {
433 433
 				return FileInfo::SPACE_UNKNOWN;
434 434
 			}
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 
505 505
 		$this->httpClientService
506 506
 			->newClient()
507
-			->put($this->createBaseUri() . $this->encodePath($target), [
507
+			->put($this->createBaseUri().$this->encodePath($target), [
508 508
 				'body' => $source,
509 509
 				'auth' => [$this->user, $this->password]
510 510
 			]);
@@ -521,18 +521,18 @@  discard block
 block discarded – undo
521 521
 			// overwrite directory ?
522 522
 			if ($this->is_dir($path2)) {
523 523
 				// needs trailing slash in destination
524
-				$path2 = rtrim($path2, '/') . '/';
524
+				$path2 = rtrim($path2, '/').'/';
525 525
 			}
526 526
 			$this->client->request(
527 527
 				'MOVE',
528 528
 				$this->encodePath($path1),
529 529
 				null,
530 530
 				[
531
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
531
+					'Destination' => $this->createBaseUri().$this->encodePath($path2),
532 532
 				]
533 533
 			);
534
-			$this->statCache->clear($path1 . '/');
535
-			$this->statCache->clear($path2 . '/');
534
+			$this->statCache->clear($path1.'/');
535
+			$this->statCache->clear($path2.'/');
536 536
 			$this->statCache->set($path1, false);
537 537
 			$this->statCache->set($path2, true);
538 538
 			$this->removeCachedFile($path1);
@@ -553,17 +553,17 @@  discard block
 block discarded – undo
553 553
 			// overwrite directory ?
554 554
 			if ($this->is_dir($path2)) {
555 555
 				// needs trailing slash in destination
556
-				$path2 = rtrim($path2, '/') . '/';
556
+				$path2 = rtrim($path2, '/').'/';
557 557
 			}
558 558
 			$this->client->request(
559 559
 				'COPY',
560 560
 				$this->encodePath($path1),
561 561
 				null,
562 562
 				[
563
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
563
+					'Destination' => $this->createBaseUri().$this->encodePath($path2),
564 564
 				]
565 565
 			);
566
-			$this->statCache->clear($path2 . '/');
566
+			$this->statCache->clear($path2.'/');
567 567
 			$this->statCache->set($path2, true);
568 568
 			$this->removeCachedFile($path2);
569 569
 			return true;
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 			}
583 583
 			return [
584 584
 				'mtime' => strtotime($response['{DAV:}getlastmodified']),
585
-				'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
585
+				'size' => (int) isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
586 586
 			];
587 587
 		} catch (\Exception $e) {
588 588
 			$this->convertException($e, $path);
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
 			return $response['statusCode'] == $expected;
657 657
 		} catch (ClientHttpException $e) {
658 658
 			if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
659
-				$this->statCache->clear($path . '/');
659
+				$this->statCache->clear($path.'/');
660 660
 				$this->statCache->set($path, false);
661 661
 				return false;
662 662
 			}
@@ -677,22 +677,22 @@  discard block
 block discarded – undo
677 677
 
678 678
 	/** {@inheritdoc} */
679 679
 	public function isUpdatable($path) {
680
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
680
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
681 681
 	}
682 682
 
683 683
 	/** {@inheritdoc} */
684 684
 	public function isCreatable($path) {
685
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
685
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_CREATE);
686 686
 	}
687 687
 
688 688
 	/** {@inheritdoc} */
689 689
 	public function isSharable($path) {
690
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
690
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_SHARE);
691 691
 	}
692 692
 
693 693
 	/** {@inheritdoc} */
694 694
 	public function isDeletable($path) {
695
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
695
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_DELETE);
696 696
 	}
697 697
 
698 698
 	/** {@inheritdoc} */
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
 			if ($response === false) {
769 769
 				if ($path === '') {
770 770
 					// if root is gone it means the storage is not available
771
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
771
+					throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
772 772
 				}
773 773
 				return false;
774 774
 			}
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
 				if (!empty($etag) && $cachedData['etag'] !== $etag) {
782 782
 					return true;
783 783
 				} else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
784
-					$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
784
+					$sharePermissions = (int) $response['{http://open-collaboration-services.org/ns}share-permissions'];
785 785
 					return $sharePermissions !== $cachedData['permissions'];
786 786
 				} else if (isset($response['{http://owncloud.org/ns}permissions'])) {
787 787
 					$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
@@ -797,7 +797,7 @@  discard block
 block discarded – undo
797 797
 			if ($e->getHttpStatus() === 405) {
798 798
 				if ($path === '') {
799 799
 					// if root is gone it means the storage is not available
800
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
800
+					throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
801 801
 				}
802 802
 				return false;
803 803
 			}
@@ -832,19 +832,19 @@  discard block
 block discarded – undo
832 832
 			}
833 833
 			if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
834 834
 				// either password was changed or was invalid all along
835
-				throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
835
+				throw new StorageInvalidException(get_class($e).': '.$e->getMessage());
836 836
 			} else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
837 837
 				// ignore exception for MethodNotAllowed, false will be returned
838 838
 				return;
839 839
 			}
840
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
840
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
841 841
 		} else if ($e instanceof ClientException) {
842 842
 			// connection timeout or refused, server could be temporarily down
843
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
843
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
844 844
 		} else if ($e instanceof \InvalidArgumentException) {
845 845
 			// parse error because the server returned HTML instead of XML,
846 846
 			// possibly temporarily down
847
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
847
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
848 848
 		} else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
849 849
 			// rethrow
850 850
 			throw $e;
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@
 block discarded – undo
102 102
 
103 103
 	/**
104 104
 	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
105
+	 * @return null|Change
106 106
 	 */
107 107
 	private function mapChange(\Icewind\SMB\Change $change) {
108 108
 		$path = $this->relativePath($change->getPath());
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -29,122 +29,122 @@
 block discarded – undo
29 29
 use OCP\Files\Notify\INotifyHandler;
30 30
 
31 31
 class SMBNotifyHandler implements INotifyHandler {
32
-	/**
33
-	 * @var \Icewind\SMB\INotifyHandler
34
-	 */
35
-	private $shareNotifyHandler;
32
+    /**
33
+     * @var \Icewind\SMB\INotifyHandler
34
+     */
35
+    private $shareNotifyHandler;
36 36
 
37
-	/**
38
-	 * @var string
39
-	 */
40
-	private $root;
37
+    /**
38
+     * @var string
39
+     */
40
+    private $root;
41 41
 
42
-	private $oldRenamePath = null;
42
+    private $oldRenamePath = null;
43 43
 
44
-	/**
45
-	 * SMBNotifyHandler constructor.
46
-	 *
47
-	 * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
-	 * @param string $root
49
-	 */
50
-	public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
-		$this->shareNotifyHandler = $shareNotifyHandler;
52
-		$this->root = $root;
53
-	}
44
+    /**
45
+     * SMBNotifyHandler constructor.
46
+     *
47
+     * @param \Icewind\SMB\INotifyHandler $shareNotifyHandler
48
+     * @param string $root
49
+     */
50
+    public function __construct(\Icewind\SMB\INotifyHandler $shareNotifyHandler, $root) {
51
+        $this->shareNotifyHandler = $shareNotifyHandler;
52
+        $this->root = $root;
53
+    }
54 54
 
55
-	private function relativePath($fullPath) {
56
-		if ($fullPath === $this->root) {
57
-			return '';
58
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
-			return substr($fullPath, strlen($this->root));
60
-		} else {
61
-			return null;
62
-		}
63
-	}
55
+    private function relativePath($fullPath) {
56
+        if ($fullPath === $this->root) {
57
+            return '';
58
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
59
+            return substr($fullPath, strlen($this->root));
60
+        } else {
61
+            return null;
62
+        }
63
+    }
64 64
 
65
-	public function listen(callable $callback) {
66
-		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
-			$change = $this->mapChange($shareChange);
69
-			if (!is_null($change)) {
70
-				return $callback($change);
71
-			} else {
72
-				return true;
73
-			}
74
-		});
75
-	}
65
+    public function listen(callable $callback) {
66
+        $oldRenamePath = null;
67
+        $this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
68
+            $change = $this->mapChange($shareChange);
69
+            if (!is_null($change)) {
70
+                return $callback($change);
71
+            } else {
72
+                return true;
73
+            }
74
+        });
75
+    }
76 76
 
77
-	/**
78
-	 * Get all changes detected since the start of the notify process or the last call to getChanges
79
-	 *
80
-	 * @return IChange[]
81
-	 */
82
-	public function getChanges() {
83
-		$shareChanges = $this->shareNotifyHandler->getChanges();
84
-		$changes = [];
85
-		foreach ($shareChanges as $shareChange) {
86
-			$change = $this->mapChange($shareChange);
87
-			if ($change) {
88
-				$changes[] = $change;
89
-			}
90
-		}
91
-		return $changes;
92
-	}
77
+    /**
78
+     * Get all changes detected since the start of the notify process or the last call to getChanges
79
+     *
80
+     * @return IChange[]
81
+     */
82
+    public function getChanges() {
83
+        $shareChanges = $this->shareNotifyHandler->getChanges();
84
+        $changes = [];
85
+        foreach ($shareChanges as $shareChange) {
86
+            $change = $this->mapChange($shareChange);
87
+            if ($change) {
88
+                $changes[] = $change;
89
+            }
90
+        }
91
+        return $changes;
92
+    }
93 93
 
94
-	/**
95
-	 * Stop listening for changes
96
-	 *
97
-	 * Note that any pending changes will be discarded
98
-	 */
99
-	public function stop() {
100
-		$this->shareNotifyHandler->stop();
101
-	}
94
+    /**
95
+     * Stop listening for changes
96
+     *
97
+     * Note that any pending changes will be discarded
98
+     */
99
+    public function stop() {
100
+        $this->shareNotifyHandler->stop();
101
+    }
102 102
 
103
-	/**
104
-	 * @param \Icewind\SMB\Change $change
105
-	 * @return IChange|null
106
-	 */
107
-	private function mapChange(\Icewind\SMB\Change $change) {
108
-		$path = $this->relativePath($change->getPath());
109
-		if (is_null($path)) {
110
-			return null;
111
-		}
112
-		if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
-			$this->oldRenamePath = $path;
114
-			return null;
115
-		}
116
-		$type = $this->mapNotifyType($change->getCode());
117
-		if (is_null($type)) {
118
-			return null;
119
-		}
120
-		if ($type === IChange::RENAMED) {
121
-			if (!is_null($this->oldRenamePath)) {
122
-				$result = new RenameChange($type, $this->oldRenamePath, $path);
123
-				$this->oldRenamePath = null;
124
-			} else {
125
-				$result = null;
126
-			}
127
-		} else {
128
-			$result = new Change($type, $path);
129
-		}
130
-		return $result;
131
-	}
103
+    /**
104
+     * @param \Icewind\SMB\Change $change
105
+     * @return IChange|null
106
+     */
107
+    private function mapChange(\Icewind\SMB\Change $change) {
108
+        $path = $this->relativePath($change->getPath());
109
+        if (is_null($path)) {
110
+            return null;
111
+        }
112
+        if ($change->getCode() === \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_OLD) {
113
+            $this->oldRenamePath = $path;
114
+            return null;
115
+        }
116
+        $type = $this->mapNotifyType($change->getCode());
117
+        if (is_null($type)) {
118
+            return null;
119
+        }
120
+        if ($type === IChange::RENAMED) {
121
+            if (!is_null($this->oldRenamePath)) {
122
+                $result = new RenameChange($type, $this->oldRenamePath, $path);
123
+                $this->oldRenamePath = null;
124
+            } else {
125
+                $result = null;
126
+            }
127
+        } else {
128
+            $result = new Change($type, $path);
129
+        }
130
+        return $result;
131
+    }
132 132
 
133
-	private function mapNotifyType($smbType) {
134
-		switch ($smbType) {
135
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
-				return IChange::ADDED;
137
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
-				return IChange::REMOVED;
139
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
-			case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
-			case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
-			case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
-				return IChange::MODIFIED;
144
-			case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
-				return IChange::RENAMED;
146
-			default:
147
-				return null;
148
-		}
149
-	}
133
+    private function mapNotifyType($smbType) {
134
+        switch ($smbType) {
135
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED:
136
+                return IChange::ADDED;
137
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED:
138
+                return IChange::REMOVED;
139
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED:
140
+            case \Icewind\SMB\INotifyHandler::NOTIFY_ADDED_STREAM:
141
+            case \Icewind\SMB\INotifyHandler::NOTIFY_MODIFIED_STREAM:
142
+            case \Icewind\SMB\INotifyHandler::NOTIFY_REMOVED_STREAM:
143
+                return IChange::MODIFIED;
144
+            case \Icewind\SMB\INotifyHandler::NOTIFY_RENAMED_NEW:
145
+                return IChange::RENAMED;
146
+            default:
147
+                return null;
148
+        }
149
+    }
150 150
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@
 block discarded – undo
64 64
 
65 65
 	public function listen(callable $callback) {
66 66
 		$oldRenamePath = null;
67
-		$this->shareNotifyHandler->listen(function (\Icewind\SMB\Change $shareChange) use ($callback) {
67
+		$this->shareNotifyHandler->listen(function(\Icewind\SMB\Change $shareChange) use ($callback) {
68 68
 			$change = $this->mapChange($shareChange);
69 69
 			if (!is_null($change)) {
70 70
 				return $callback($change);
Please login to merge, or discard this patch.