Completed
Pull Request — master (#3590)
by Individual IT
11:38
created
apps/files_external/lib/Lib/Storage/Swift.php 1 patch
Indentation   +604 added lines, -604 removed lines patch added patch discarded remove patch
@@ -48,609 +48,609 @@
 block discarded – undo
48 48
 
49 49
 class Swift extends \OC\Files\Storage\Common {
50 50
 
51
-	/**
52
-	 * @var \OpenCloud\ObjectStore\Service
53
-	 */
54
-	private $connection;
55
-	/**
56
-	 * @var \OpenCloud\ObjectStore\Resource\Container
57
-	 */
58
-	private $container;
59
-	/**
60
-	 * @var \OpenCloud\OpenStack
61
-	 */
62
-	private $anchor;
63
-	/**
64
-	 * @var string
65
-	 */
66
-	private $bucket;
67
-	/**
68
-	 * Connection parameters
69
-	 *
70
-	 * @var array
71
-	 */
72
-	private $params;
73
-
74
-	/** @var string  */
75
-	private $id;
76
-
77
-	/**
78
-	 * @var array
79
-	 */
80
-	private static $tmpFiles = array();
81
-
82
-	/**
83
-	 * Key value cache mapping path to data object. Maps path to
84
-	 * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
-	 * paths and path to false for not existing paths.
86
-	 * @var \OCP\ICache
87
-	 */
88
-	private $objectCache;
89
-
90
-	/**
91
-	 * @param string $path
92
-	 */
93
-	private function normalizePath($path) {
94
-		$path = trim($path, '/');
95
-
96
-		if (!$path) {
97
-			$path = '.';
98
-		}
99
-
100
-		$path = str_replace('#', '%23', $path);
101
-
102
-		return $path;
103
-	}
104
-
105
-	const SUBCONTAINER_FILE = '.subcontainers';
106
-
107
-	/**
108
-	 * translate directory path to container name
109
-	 *
110
-	 * @param string $path
111
-	 * @return string
112
-	 */
113
-
114
-	/**
115
-	 * Fetches an object from the API.
116
-	 * If the object is cached already or a
117
-	 * failed "doesn't exist" response was cached,
118
-	 * that one will be returned.
119
-	 *
120
-	 * @param string $path
121
-	 * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
-	 * or false if the object did not exist
123
-	 */
124
-	private function fetchObject($path) {
125
-		if ($this->objectCache->hasKey($path)) {
126
-			// might be "false" if object did not exist from last check
127
-			return $this->objectCache->get($path);
128
-		}
129
-		try {
130
-			$object = $this->getContainer()->getPartialObject($path);
131
-			$this->objectCache->set($path, $object);
132
-			return $object;
133
-		} catch (ClientErrorResponseException $e) {
134
-			// this exception happens when the object does not exist, which
135
-			// is expected in most cases
136
-			$this->objectCache->set($path, false);
137
-			return false;
138
-		} catch (ClientErrorResponseException $e) {
139
-			// Expected response is "404 Not Found", so only log if it isn't
140
-			if ($e->getResponse()->getStatusCode() !== 404) {
141
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
-			}
143
-			return false;
144
-		}
145
-	}
146
-
147
-	/**
148
-	 * Returns whether the given path exists.
149
-	 *
150
-	 * @param string $path
151
-	 *
152
-	 * @return bool true if the object exist, false otherwise
153
-	 */
154
-	private function doesObjectExist($path) {
155
-		return $this->fetchObject($path) !== false;
156
-	}
157
-
158
-	public function __construct($params) {
159
-		if ((empty($params['key']) and empty($params['password']))
160
-			or empty($params['user']) or empty($params['bucket'])
161
-			or empty($params['region'])
162
-		) {
163
-			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
-		}
165
-
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
-
168
-		$bucketUrl = Url::factory($params['bucket']);
169
-		if ($bucketUrl->isAbsolute()) {
170
-			$this->bucket = end(($bucketUrl->getPathSegments()));
171
-			$params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
-		} else {
173
-			$this->bucket = $params['bucket'];
174
-		}
175
-
176
-		if (empty($params['url'])) {
177
-			$params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
-		}
179
-
180
-		if (empty($params['service_name'])) {
181
-			$params['service_name'] = 'cloudFiles';
182
-		}
183
-
184
-		$this->params = $params;
185
-		// FIXME: private class...
186
-		$this->objectCache = new \OC\Cache\CappedMemoryCache();
187
-	}
188
-
189
-	public function mkdir($path) {
190
-		$path = $this->normalizePath($path);
191
-
192
-		if ($this->is_dir($path)) {
193
-			return false;
194
-		}
195
-
196
-		if ($path !== '.') {
197
-			$path .= '/';
198
-		}
199
-
200
-		try {
201
-			$customHeaders = array('content-type' => 'httpd/unix-directory');
202
-			$metadataHeaders = DataObject::stockHeaders(array());
203
-			$allHeaders = $customHeaders + $metadataHeaders;
204
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
205
-			// invalidate so that the next access gets the real object
206
-			// with all properties
207
-			$this->objectCache->remove($path);
208
-		} catch (Exceptions\CreateUpdateError $e) {
209
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
-			return false;
211
-		}
212
-
213
-		return true;
214
-	}
215
-
216
-	public function file_exists($path) {
217
-		$path = $this->normalizePath($path);
218
-
219
-		if ($path !== '.' && $this->is_dir($path)) {
220
-			$path .= '/';
221
-		}
222
-
223
-		return $this->doesObjectExist($path);
224
-	}
225
-
226
-	public function rmdir($path) {
227
-		$path = $this->normalizePath($path);
228
-
229
-		if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
-			return false;
231
-		}
232
-
233
-		$dh = $this->opendir($path);
234
-		while ($file = readdir($dh)) {
235
-			if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
-				continue;
237
-			}
238
-
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
241
-			} else {
242
-				$this->unlink($path . '/' . $file);
243
-			}
244
-		}
245
-
246
-		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
249
-		} catch (Exceptions\DeleteError $e) {
250
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
-			return false;
252
-		}
253
-
254
-		return true;
255
-	}
256
-
257
-	public function opendir($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		if ($path === '.') {
261
-			$path = '';
262
-		} else {
263
-			$path .= '/';
264
-		}
265
-
266
-		$path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
-
268
-		try {
269
-			$files = array();
270
-			/** @var OpenCloud\Common\Collection $objects */
271
-			$objects = $this->getContainer()->objectList(array(
272
-				'prefix' => $path,
273
-				'delimiter' => '/'
274
-			));
275
-
276
-			/** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
-			foreach ($objects as $object) {
278
-				$file = basename($object->getName());
279
-				if ($file !== basename($path)) {
280
-					$files[] = $file;
281
-				}
282
-			}
283
-
284
-			return IteratorDirectory::wrap($files);
285
-		} catch (\Exception $e) {
286
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
-			return false;
288
-		}
289
-
290
-	}
291
-
292
-	public function stat($path) {
293
-		$path = $this->normalizePath($path);
294
-
295
-		if ($path === '.') {
296
-			$path = '';
297
-		} else if ($this->is_dir($path)) {
298
-			$path .= '/';
299
-		}
300
-
301
-		try {
302
-			/** @var DataObject $object */
303
-			$object = $this->fetchObject($path);
304
-			if (!$object) {
305
-				return false;
306
-			}
307
-		} catch (ClientErrorResponseException $e) {
308
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
-			return false;
310
-		}
311
-
312
-		$dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
-		if ($dateTime !== false) {
314
-			$mtime = $dateTime->getTimestamp();
315
-		} else {
316
-			$mtime = null;
317
-		}
318
-		$objectMetadata = $object->getMetadata();
319
-		$metaTimestamp = $objectMetadata->getProperty('timestamp');
320
-		if (isset($metaTimestamp)) {
321
-			$mtime = $metaTimestamp;
322
-		}
323
-
324
-		if (!empty($mtime)) {
325
-			$mtime = floor($mtime);
326
-		}
327
-
328
-		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
330
-		$stat['mtime'] = $mtime;
331
-		$stat['atime'] = time();
332
-		return $stat;
333
-	}
334
-
335
-	public function filetype($path) {
336
-		$path = $this->normalizePath($path);
337
-
338
-		if ($path !== '.' && $this->doesObjectExist($path)) {
339
-			return 'file';
340
-		}
341
-
342
-		if ($path !== '.') {
343
-			$path .= '/';
344
-		}
345
-
346
-		if ($this->doesObjectExist($path)) {
347
-			return 'dir';
348
-		}
349
-	}
350
-
351
-	public function unlink($path) {
352
-		$path = $this->normalizePath($path);
353
-
354
-		if ($this->is_dir($path)) {
355
-			return $this->rmdir($path);
356
-		}
357
-
358
-		try {
359
-			$this->getContainer()->dataObject()->setName($path)->delete();
360
-			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
362
-		} catch (ClientErrorResponseException $e) {
363
-			if ($e->getResponse()->getStatusCode() !== 404) {
364
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
-			}
366
-			return false;
367
-		}
368
-
369
-		return true;
370
-	}
371
-
372
-	public function fopen($path, $mode) {
373
-		$path = $this->normalizePath($path);
374
-
375
-		switch ($mode) {
376
-			case 'r':
377
-			case 'rb':
378
-				try {
379
-					$c = $this->getContainer();
380
-					$streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
381
-					$streamInterface = $streamFactory->fromRequest(
382
-						$c->getClient()
383
-							->get($c->getUrl($path)));
384
-					$streamInterface->rewind();
385
-					$stream = $streamInterface->getStream();
386
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
387
-					if(!strrpos($streamInterface
388
-						->getMetaData('wrapper_data')[0], '404 Not Found')) {
389
-						return $stream;
390
-					}
391
-					return false;
392
-				} catch (\Guzzle\Http\Exception\BadResponseException $e) {
393
-					\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
394
-					return false;
395
-				}
396
-			case 'w':
397
-			case 'wb':
398
-			case 'a':
399
-			case 'ab':
400
-			case 'r+':
401
-			case 'w+':
402
-			case 'wb+':
403
-			case 'a+':
404
-			case 'x':
405
-			case 'x+':
406
-			case 'c':
407
-			case 'c+':
408
-				if (strrpos($path, '.') !== false) {
409
-					$ext = substr($path, strrpos($path, '.'));
410
-				} else {
411
-					$ext = '';
412
-				}
413
-				$tmpFile = \OCP\Files::tmpFile($ext);
414
-				// Fetch existing file if required
415
-				if ($mode[0] !== 'w' && $this->file_exists($path)) {
416
-					if ($mode[0] === 'x') {
417
-						// File cannot already exist
418
-						return false;
419
-					}
420
-					$source = $this->fopen($path, 'r');
421
-					file_put_contents($tmpFile, $source);
422
-					// Seek to end if required
423
-					if ($mode[0] === 'a') {
424
-						fseek($tmpFile, 0, SEEK_END);
425
-					}
426
-				}
427
-				$handle = fopen($tmpFile, $mode);
428
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
429
-					$this->writeBack($tmpFile, $path);
430
-				});
431
-		}
432
-	}
433
-
434
-	public function touch($path, $mtime = null) {
435
-		$path = $this->normalizePath($path);
436
-		if (is_null($mtime)) {
437
-			$mtime = time();
438
-		}
439
-		$metadata = array('timestamp' => $mtime);
440
-		if ($this->file_exists($path)) {
441
-			if ($this->is_dir($path) && $path != '.') {
442
-				$path .= '/';
443
-			}
444
-
445
-			$object = $this->fetchObject($path);
446
-			if ($object->saveMetadata($metadata)) {
447
-				// invalidate target object to force repopulation on fetch
448
-				$this->objectCache->remove($path);
449
-			}
450
-			return true;
451
-		} else {
452
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
453
-			$customHeaders = array('content-type' => $mimeType);
454
-			$metadataHeaders = DataObject::stockHeaders($metadata);
455
-			$allHeaders = $customHeaders + $metadataHeaders;
456
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
457
-			// invalidate target object to force repopulation on fetch
458
-			$this->objectCache->remove($path);
459
-			return true;
460
-		}
461
-	}
462
-
463
-	public function copy($path1, $path2) {
464
-		$path1 = $this->normalizePath($path1);
465
-		$path2 = $this->normalizePath($path2);
466
-
467
-		$fileType = $this->filetype($path1);
468
-		if ($fileType === 'file') {
469
-
470
-			// make way
471
-			$this->unlink($path2);
472
-
473
-			try {
474
-				$source = $this->fetchObject($path1);
475
-				$source->copy($this->bucket . '/' . $path2);
476
-				// invalidate target object to force repopulation on fetch
477
-				$this->objectCache->remove($path2);
478
-				$this->objectCache->remove($path2 . '/');
479
-			} catch (ClientErrorResponseException $e) {
480
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481
-				return false;
482
-			}
483
-
484
-		} else if ($fileType === 'dir') {
485
-
486
-			// make way
487
-			$this->unlink($path2);
488
-
489
-			try {
490
-				$source = $this->fetchObject($path1 . '/');
491
-				$source->copy($this->bucket . '/' . $path2 . '/');
492
-				// invalidate target object to force repopulation on fetch
493
-				$this->objectCache->remove($path2);
494
-				$this->objectCache->remove($path2 . '/');
495
-			} catch (ClientErrorResponseException $e) {
496
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497
-				return false;
498
-			}
499
-
500
-			$dh = $this->opendir($path1);
501
-			while ($file = readdir($dh)) {
502
-				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
503
-					continue;
504
-				}
505
-
506
-				$source = $path1 . '/' . $file;
507
-				$target = $path2 . '/' . $file;
508
-				$this->copy($source, $target);
509
-			}
510
-
511
-		} else {
512
-			//file does not exist
513
-			return false;
514
-		}
515
-
516
-		return true;
517
-	}
518
-
519
-	public function rename($path1, $path2) {
520
-		$path1 = $this->normalizePath($path1);
521
-		$path2 = $this->normalizePath($path2);
522
-
523
-		$fileType = $this->filetype($path1);
524
-
525
-		if ($fileType === 'dir' || $fileType === 'file') {
526
-			// copy
527
-			if ($this->copy($path1, $path2) === false) {
528
-				return false;
529
-			}
530
-
531
-			// cleanup
532
-			if ($this->unlink($path1) === false) {
533
-				$this->unlink($path2);
534
-				return false;
535
-			}
536
-
537
-			return true;
538
-		}
539
-
540
-		return false;
541
-	}
542
-
543
-	public function getId() {
544
-		return $this->id;
545
-	}
546
-
547
-	/**
548
-	 * Returns the connection
549
-	 *
550
-	 * @return OpenCloud\ObjectStore\Service connected client
551
-	 * @throws \Exception if connection could not be made
552
-	 */
553
-	public function getConnection() {
554
-		if (!is_null($this->connection)) {
555
-			return $this->connection;
556
-		}
557
-
558
-		$settings = array(
559
-			'username' => $this->params['user'],
560
-		);
561
-
562
-		if (!empty($this->params['password'])) {
563
-			$settings['password'] = $this->params['password'];
564
-		} else if (!empty($this->params['key'])) {
565
-			$settings['apiKey'] = $this->params['key'];
566
-		}
567
-
568
-		if (!empty($this->params['tenant'])) {
569
-			$settings['tenantName'] = $this->params['tenant'];
570
-		}
571
-
572
-		if (!empty($this->params['timeout'])) {
573
-			$settings['timeout'] = $this->params['timeout'];
574
-		}
575
-
576
-		if (isset($settings['apiKey'])) {
577
-			$this->anchor = new Rackspace($this->params['url'], $settings);
578
-		} else {
579
-			$this->anchor = new OpenStack($this->params['url'], $settings);
580
-		}
581
-
582
-		$connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
583
-
584
-		if (!empty($this->params['endpoint_url'])) {
585
-			$endpoint = $connection->getEndpoint();
586
-			$endpoint->setPublicUrl($this->params['endpoint_url']);
587
-			$endpoint->setPrivateUrl($this->params['endpoint_url']);
588
-			$connection->setEndpoint($endpoint);
589
-		}
590
-
591
-		$this->connection = $connection;
592
-
593
-		return $this->connection;
594
-	}
595
-
596
-	/**
597
-	 * Returns the initialized object store container.
598
-	 *
599
-	 * @return OpenCloud\ObjectStore\Resource\Container
600
-	 */
601
-	public function getContainer() {
602
-		if (!is_null($this->container)) {
603
-			return $this->container;
604
-		}
605
-
606
-		try {
607
-			$this->container = $this->getConnection()->getContainer($this->bucket);
608
-		} catch (ClientErrorResponseException $e) {
609
-			$this->container = $this->getConnection()->createContainer($this->bucket);
610
-		}
611
-
612
-		if (!$this->file_exists('.')) {
613
-			$this->mkdir('.');
614
-		}
615
-
616
-		return $this->container;
617
-	}
618
-
619
-	public function writeBack($tmpFile, $path) {
620
-		$fileData = fopen($tmpFile, 'r');
621
-		$this->getContainer()->uploadObject($path, $fileData);
622
-		// invalidate target object to force repopulation on fetch
623
-		$this->objectCache->remove(self::$tmpFiles[$tmpFile]);
624
-		unlink($tmpFile);
625
-	}
626
-
627
-	public function hasUpdated($path, $time) {
628
-		if ($this->is_file($path)) {
629
-			return parent::hasUpdated($path, $time);
630
-		}
631
-		$path = $this->normalizePath($path);
632
-		$dh = $this->opendir($path);
633
-		$content = array();
634
-		while (($file = readdir($dh)) !== false) {
635
-			$content[] = $file;
636
-		}
637
-		if ($path === '.') {
638
-			$path = '';
639
-		}
640
-		$cachedContent = $this->getCache()->getFolderContents($path);
641
-		$cachedNames = array_map(function ($content) {
642
-			return $content['name'];
643
-		}, $cachedContent);
644
-		sort($cachedNames);
645
-		sort($content);
646
-		return $cachedNames != $content;
647
-	}
648
-
649
-	/**
650
-	 * check if curl is installed
651
-	 */
652
-	public static function checkDependencies() {
653
-		return true;
654
-	}
51
+    /**
52
+     * @var \OpenCloud\ObjectStore\Service
53
+     */
54
+    private $connection;
55
+    /**
56
+     * @var \OpenCloud\ObjectStore\Resource\Container
57
+     */
58
+    private $container;
59
+    /**
60
+     * @var \OpenCloud\OpenStack
61
+     */
62
+    private $anchor;
63
+    /**
64
+     * @var string
65
+     */
66
+    private $bucket;
67
+    /**
68
+     * Connection parameters
69
+     *
70
+     * @var array
71
+     */
72
+    private $params;
73
+
74
+    /** @var string  */
75
+    private $id;
76
+
77
+    /**
78
+     * @var array
79
+     */
80
+    private static $tmpFiles = array();
81
+
82
+    /**
83
+     * Key value cache mapping path to data object. Maps path to
84
+     * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
+     * paths and path to false for not existing paths.
86
+     * @var \OCP\ICache
87
+     */
88
+    private $objectCache;
89
+
90
+    /**
91
+     * @param string $path
92
+     */
93
+    private function normalizePath($path) {
94
+        $path = trim($path, '/');
95
+
96
+        if (!$path) {
97
+            $path = '.';
98
+        }
99
+
100
+        $path = str_replace('#', '%23', $path);
101
+
102
+        return $path;
103
+    }
104
+
105
+    const SUBCONTAINER_FILE = '.subcontainers';
106
+
107
+    /**
108
+     * translate directory path to container name
109
+     *
110
+     * @param string $path
111
+     * @return string
112
+     */
113
+
114
+    /**
115
+     * Fetches an object from the API.
116
+     * If the object is cached already or a
117
+     * failed "doesn't exist" response was cached,
118
+     * that one will be returned.
119
+     *
120
+     * @param string $path
121
+     * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
+     * or false if the object did not exist
123
+     */
124
+    private function fetchObject($path) {
125
+        if ($this->objectCache->hasKey($path)) {
126
+            // might be "false" if object did not exist from last check
127
+            return $this->objectCache->get($path);
128
+        }
129
+        try {
130
+            $object = $this->getContainer()->getPartialObject($path);
131
+            $this->objectCache->set($path, $object);
132
+            return $object;
133
+        } catch (ClientErrorResponseException $e) {
134
+            // this exception happens when the object does not exist, which
135
+            // is expected in most cases
136
+            $this->objectCache->set($path, false);
137
+            return false;
138
+        } catch (ClientErrorResponseException $e) {
139
+            // Expected response is "404 Not Found", so only log if it isn't
140
+            if ($e->getResponse()->getStatusCode() !== 404) {
141
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
+            }
143
+            return false;
144
+        }
145
+    }
146
+
147
+    /**
148
+     * Returns whether the given path exists.
149
+     *
150
+     * @param string $path
151
+     *
152
+     * @return bool true if the object exist, false otherwise
153
+     */
154
+    private function doesObjectExist($path) {
155
+        return $this->fetchObject($path) !== false;
156
+    }
157
+
158
+    public function __construct($params) {
159
+        if ((empty($params['key']) and empty($params['password']))
160
+            or empty($params['user']) or empty($params['bucket'])
161
+            or empty($params['region'])
162
+        ) {
163
+            throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
+        }
165
+
166
+        $this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
+
168
+        $bucketUrl = Url::factory($params['bucket']);
169
+        if ($bucketUrl->isAbsolute()) {
170
+            $this->bucket = end(($bucketUrl->getPathSegments()));
171
+            $params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
+        } else {
173
+            $this->bucket = $params['bucket'];
174
+        }
175
+
176
+        if (empty($params['url'])) {
177
+            $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
+        }
179
+
180
+        if (empty($params['service_name'])) {
181
+            $params['service_name'] = 'cloudFiles';
182
+        }
183
+
184
+        $this->params = $params;
185
+        // FIXME: private class...
186
+        $this->objectCache = new \OC\Cache\CappedMemoryCache();
187
+    }
188
+
189
+    public function mkdir($path) {
190
+        $path = $this->normalizePath($path);
191
+
192
+        if ($this->is_dir($path)) {
193
+            return false;
194
+        }
195
+
196
+        if ($path !== '.') {
197
+            $path .= '/';
198
+        }
199
+
200
+        try {
201
+            $customHeaders = array('content-type' => 'httpd/unix-directory');
202
+            $metadataHeaders = DataObject::stockHeaders(array());
203
+            $allHeaders = $customHeaders + $metadataHeaders;
204
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
205
+            // invalidate so that the next access gets the real object
206
+            // with all properties
207
+            $this->objectCache->remove($path);
208
+        } catch (Exceptions\CreateUpdateError $e) {
209
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
+            return false;
211
+        }
212
+
213
+        return true;
214
+    }
215
+
216
+    public function file_exists($path) {
217
+        $path = $this->normalizePath($path);
218
+
219
+        if ($path !== '.' && $this->is_dir($path)) {
220
+            $path .= '/';
221
+        }
222
+
223
+        return $this->doesObjectExist($path);
224
+    }
225
+
226
+    public function rmdir($path) {
227
+        $path = $this->normalizePath($path);
228
+
229
+        if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
+            return false;
231
+        }
232
+
233
+        $dh = $this->opendir($path);
234
+        while ($file = readdir($dh)) {
235
+            if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
+                continue;
237
+            }
238
+
239
+            if ($this->is_dir($path . '/' . $file)) {
240
+                $this->rmdir($path . '/' . $file);
241
+            } else {
242
+                $this->unlink($path . '/' . $file);
243
+            }
244
+        }
245
+
246
+        try {
247
+            $this->getContainer()->dataObject()->setName($path . '/')->delete();
248
+            $this->objectCache->remove($path . '/');
249
+        } catch (Exceptions\DeleteError $e) {
250
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
+            return false;
252
+        }
253
+
254
+        return true;
255
+    }
256
+
257
+    public function opendir($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        if ($path === '.') {
261
+            $path = '';
262
+        } else {
263
+            $path .= '/';
264
+        }
265
+
266
+        $path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
+
268
+        try {
269
+            $files = array();
270
+            /** @var OpenCloud\Common\Collection $objects */
271
+            $objects = $this->getContainer()->objectList(array(
272
+                'prefix' => $path,
273
+                'delimiter' => '/'
274
+            ));
275
+
276
+            /** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
+            foreach ($objects as $object) {
278
+                $file = basename($object->getName());
279
+                if ($file !== basename($path)) {
280
+                    $files[] = $file;
281
+                }
282
+            }
283
+
284
+            return IteratorDirectory::wrap($files);
285
+        } catch (\Exception $e) {
286
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
+            return false;
288
+        }
289
+
290
+    }
291
+
292
+    public function stat($path) {
293
+        $path = $this->normalizePath($path);
294
+
295
+        if ($path === '.') {
296
+            $path = '';
297
+        } else if ($this->is_dir($path)) {
298
+            $path .= '/';
299
+        }
300
+
301
+        try {
302
+            /** @var DataObject $object */
303
+            $object = $this->fetchObject($path);
304
+            if (!$object) {
305
+                return false;
306
+            }
307
+        } catch (ClientErrorResponseException $e) {
308
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
+            return false;
310
+        }
311
+
312
+        $dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
+        if ($dateTime !== false) {
314
+            $mtime = $dateTime->getTimestamp();
315
+        } else {
316
+            $mtime = null;
317
+        }
318
+        $objectMetadata = $object->getMetadata();
319
+        $metaTimestamp = $objectMetadata->getProperty('timestamp');
320
+        if (isset($metaTimestamp)) {
321
+            $mtime = $metaTimestamp;
322
+        }
323
+
324
+        if (!empty($mtime)) {
325
+            $mtime = floor($mtime);
326
+        }
327
+
328
+        $stat = array();
329
+        $stat['size'] = (int)$object->getContentLength();
330
+        $stat['mtime'] = $mtime;
331
+        $stat['atime'] = time();
332
+        return $stat;
333
+    }
334
+
335
+    public function filetype($path) {
336
+        $path = $this->normalizePath($path);
337
+
338
+        if ($path !== '.' && $this->doesObjectExist($path)) {
339
+            return 'file';
340
+        }
341
+
342
+        if ($path !== '.') {
343
+            $path .= '/';
344
+        }
345
+
346
+        if ($this->doesObjectExist($path)) {
347
+            return 'dir';
348
+        }
349
+    }
350
+
351
+    public function unlink($path) {
352
+        $path = $this->normalizePath($path);
353
+
354
+        if ($this->is_dir($path)) {
355
+            return $this->rmdir($path);
356
+        }
357
+
358
+        try {
359
+            $this->getContainer()->dataObject()->setName($path)->delete();
360
+            $this->objectCache->remove($path);
361
+            $this->objectCache->remove($path . '/');
362
+        } catch (ClientErrorResponseException $e) {
363
+            if ($e->getResponse()->getStatusCode() !== 404) {
364
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
+            }
366
+            return false;
367
+        }
368
+
369
+        return true;
370
+    }
371
+
372
+    public function fopen($path, $mode) {
373
+        $path = $this->normalizePath($path);
374
+
375
+        switch ($mode) {
376
+            case 'r':
377
+            case 'rb':
378
+                try {
379
+                    $c = $this->getContainer();
380
+                    $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
381
+                    $streamInterface = $streamFactory->fromRequest(
382
+                        $c->getClient()
383
+                            ->get($c->getUrl($path)));
384
+                    $streamInterface->rewind();
385
+                    $stream = $streamInterface->getStream();
386
+                    stream_context_set_option($stream, 'swift','content', $streamInterface);
387
+                    if(!strrpos($streamInterface
388
+                        ->getMetaData('wrapper_data')[0], '404 Not Found')) {
389
+                        return $stream;
390
+                    }
391
+                    return false;
392
+                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
393
+                    \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
394
+                    return false;
395
+                }
396
+            case 'w':
397
+            case 'wb':
398
+            case 'a':
399
+            case 'ab':
400
+            case 'r+':
401
+            case 'w+':
402
+            case 'wb+':
403
+            case 'a+':
404
+            case 'x':
405
+            case 'x+':
406
+            case 'c':
407
+            case 'c+':
408
+                if (strrpos($path, '.') !== false) {
409
+                    $ext = substr($path, strrpos($path, '.'));
410
+                } else {
411
+                    $ext = '';
412
+                }
413
+                $tmpFile = \OCP\Files::tmpFile($ext);
414
+                // Fetch existing file if required
415
+                if ($mode[0] !== 'w' && $this->file_exists($path)) {
416
+                    if ($mode[0] === 'x') {
417
+                        // File cannot already exist
418
+                        return false;
419
+                    }
420
+                    $source = $this->fopen($path, 'r');
421
+                    file_put_contents($tmpFile, $source);
422
+                    // Seek to end if required
423
+                    if ($mode[0] === 'a') {
424
+                        fseek($tmpFile, 0, SEEK_END);
425
+                    }
426
+                }
427
+                $handle = fopen($tmpFile, $mode);
428
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
429
+                    $this->writeBack($tmpFile, $path);
430
+                });
431
+        }
432
+    }
433
+
434
+    public function touch($path, $mtime = null) {
435
+        $path = $this->normalizePath($path);
436
+        if (is_null($mtime)) {
437
+            $mtime = time();
438
+        }
439
+        $metadata = array('timestamp' => $mtime);
440
+        if ($this->file_exists($path)) {
441
+            if ($this->is_dir($path) && $path != '.') {
442
+                $path .= '/';
443
+            }
444
+
445
+            $object = $this->fetchObject($path);
446
+            if ($object->saveMetadata($metadata)) {
447
+                // invalidate target object to force repopulation on fetch
448
+                $this->objectCache->remove($path);
449
+            }
450
+            return true;
451
+        } else {
452
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
453
+            $customHeaders = array('content-type' => $mimeType);
454
+            $metadataHeaders = DataObject::stockHeaders($metadata);
455
+            $allHeaders = $customHeaders + $metadataHeaders;
456
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
457
+            // invalidate target object to force repopulation on fetch
458
+            $this->objectCache->remove($path);
459
+            return true;
460
+        }
461
+    }
462
+
463
+    public function copy($path1, $path2) {
464
+        $path1 = $this->normalizePath($path1);
465
+        $path2 = $this->normalizePath($path2);
466
+
467
+        $fileType = $this->filetype($path1);
468
+        if ($fileType === 'file') {
469
+
470
+            // make way
471
+            $this->unlink($path2);
472
+
473
+            try {
474
+                $source = $this->fetchObject($path1);
475
+                $source->copy($this->bucket . '/' . $path2);
476
+                // invalidate target object to force repopulation on fetch
477
+                $this->objectCache->remove($path2);
478
+                $this->objectCache->remove($path2 . '/');
479
+            } catch (ClientErrorResponseException $e) {
480
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481
+                return false;
482
+            }
483
+
484
+        } else if ($fileType === 'dir') {
485
+
486
+            // make way
487
+            $this->unlink($path2);
488
+
489
+            try {
490
+                $source = $this->fetchObject($path1 . '/');
491
+                $source->copy($this->bucket . '/' . $path2 . '/');
492
+                // invalidate target object to force repopulation on fetch
493
+                $this->objectCache->remove($path2);
494
+                $this->objectCache->remove($path2 . '/');
495
+            } catch (ClientErrorResponseException $e) {
496
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497
+                return false;
498
+            }
499
+
500
+            $dh = $this->opendir($path1);
501
+            while ($file = readdir($dh)) {
502
+                if (\OC\Files\Filesystem::isIgnoredDir($file)) {
503
+                    continue;
504
+                }
505
+
506
+                $source = $path1 . '/' . $file;
507
+                $target = $path2 . '/' . $file;
508
+                $this->copy($source, $target);
509
+            }
510
+
511
+        } else {
512
+            //file does not exist
513
+            return false;
514
+        }
515
+
516
+        return true;
517
+    }
518
+
519
+    public function rename($path1, $path2) {
520
+        $path1 = $this->normalizePath($path1);
521
+        $path2 = $this->normalizePath($path2);
522
+
523
+        $fileType = $this->filetype($path1);
524
+
525
+        if ($fileType === 'dir' || $fileType === 'file') {
526
+            // copy
527
+            if ($this->copy($path1, $path2) === false) {
528
+                return false;
529
+            }
530
+
531
+            // cleanup
532
+            if ($this->unlink($path1) === false) {
533
+                $this->unlink($path2);
534
+                return false;
535
+            }
536
+
537
+            return true;
538
+        }
539
+
540
+        return false;
541
+    }
542
+
543
+    public function getId() {
544
+        return $this->id;
545
+    }
546
+
547
+    /**
548
+     * Returns the connection
549
+     *
550
+     * @return OpenCloud\ObjectStore\Service connected client
551
+     * @throws \Exception if connection could not be made
552
+     */
553
+    public function getConnection() {
554
+        if (!is_null($this->connection)) {
555
+            return $this->connection;
556
+        }
557
+
558
+        $settings = array(
559
+            'username' => $this->params['user'],
560
+        );
561
+
562
+        if (!empty($this->params['password'])) {
563
+            $settings['password'] = $this->params['password'];
564
+        } else if (!empty($this->params['key'])) {
565
+            $settings['apiKey'] = $this->params['key'];
566
+        }
567
+
568
+        if (!empty($this->params['tenant'])) {
569
+            $settings['tenantName'] = $this->params['tenant'];
570
+        }
571
+
572
+        if (!empty($this->params['timeout'])) {
573
+            $settings['timeout'] = $this->params['timeout'];
574
+        }
575
+
576
+        if (isset($settings['apiKey'])) {
577
+            $this->anchor = new Rackspace($this->params['url'], $settings);
578
+        } else {
579
+            $this->anchor = new OpenStack($this->params['url'], $settings);
580
+        }
581
+
582
+        $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
583
+
584
+        if (!empty($this->params['endpoint_url'])) {
585
+            $endpoint = $connection->getEndpoint();
586
+            $endpoint->setPublicUrl($this->params['endpoint_url']);
587
+            $endpoint->setPrivateUrl($this->params['endpoint_url']);
588
+            $connection->setEndpoint($endpoint);
589
+        }
590
+
591
+        $this->connection = $connection;
592
+
593
+        return $this->connection;
594
+    }
595
+
596
+    /**
597
+     * Returns the initialized object store container.
598
+     *
599
+     * @return OpenCloud\ObjectStore\Resource\Container
600
+     */
601
+    public function getContainer() {
602
+        if (!is_null($this->container)) {
603
+            return $this->container;
604
+        }
605
+
606
+        try {
607
+            $this->container = $this->getConnection()->getContainer($this->bucket);
608
+        } catch (ClientErrorResponseException $e) {
609
+            $this->container = $this->getConnection()->createContainer($this->bucket);
610
+        }
611
+
612
+        if (!$this->file_exists('.')) {
613
+            $this->mkdir('.');
614
+        }
615
+
616
+        return $this->container;
617
+    }
618
+
619
+    public function writeBack($tmpFile, $path) {
620
+        $fileData = fopen($tmpFile, 'r');
621
+        $this->getContainer()->uploadObject($path, $fileData);
622
+        // invalidate target object to force repopulation on fetch
623
+        $this->objectCache->remove(self::$tmpFiles[$tmpFile]);
624
+        unlink($tmpFile);
625
+    }
626
+
627
+    public function hasUpdated($path, $time) {
628
+        if ($this->is_file($path)) {
629
+            return parent::hasUpdated($path, $time);
630
+        }
631
+        $path = $this->normalizePath($path);
632
+        $dh = $this->opendir($path);
633
+        $content = array();
634
+        while (($file = readdir($dh)) !== false) {
635
+            $content[] = $file;
636
+        }
637
+        if ($path === '.') {
638
+            $path = '';
639
+        }
640
+        $cachedContent = $this->getCache()->getFolderContents($path);
641
+        $cachedNames = array_map(function ($content) {
642
+            return $content['name'];
643
+        }, $cachedContent);
644
+        sort($cachedNames);
645
+        sort($content);
646
+        return $cachedNames != $content;
647
+    }
648
+
649
+    /**
650
+     * check if curl is installed
651
+     */
652
+    public static function checkDependencies() {
653
+        return true;
654
+    }
655 655
 
656 656
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/OwnCloud.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -32,44 +32,44 @@
 block discarded – undo
32 32
  *
33 33
  */
34 34
 class OwnCloud extends \OC\Files\Storage\DAV{
35
-	const OC_URL_SUFFIX = 'remote.php/webdav';
35
+    const OC_URL_SUFFIX = 'remote.php/webdav';
36 36
 
37
-	public function __construct($params) {
38
-		// extract context path from host if specified
39
-		// (owncloud install path on host)
40
-		$host = $params['host'];
41
-		// strip protocol
42
-		if (substr($host, 0, 8) == "https://") {
43
-			$host = substr($host, 8);
44
-			$params['secure'] = true;
45
-		} else if (substr($host, 0, 7) == "http://") {
46
-			$host = substr($host, 7);
47
-			$params['secure'] = false;
48
-		}
49
-		$contextPath = '';
50
-		$hostSlashPos = strpos($host, '/');
51
-		if ($hostSlashPos !== false){
52
-			$contextPath = substr($host, $hostSlashPos);
53
-			$host = substr($host, 0, $hostSlashPos);
54
-		}
37
+    public function __construct($params) {
38
+        // extract context path from host if specified
39
+        // (owncloud install path on host)
40
+        $host = $params['host'];
41
+        // strip protocol
42
+        if (substr($host, 0, 8) == "https://") {
43
+            $host = substr($host, 8);
44
+            $params['secure'] = true;
45
+        } else if (substr($host, 0, 7) == "http://") {
46
+            $host = substr($host, 7);
47
+            $params['secure'] = false;
48
+        }
49
+        $contextPath = '';
50
+        $hostSlashPos = strpos($host, '/');
51
+        if ($hostSlashPos !== false){
52
+            $contextPath = substr($host, $hostSlashPos);
53
+            $host = substr($host, 0, $hostSlashPos);
54
+        }
55 55
 
56
-		if (substr($contextPath, -1) !== '/'){
57
-			$contextPath .= '/';
58
-		}
56
+        if (substr($contextPath, -1) !== '/'){
57
+            $contextPath .= '/';
58
+        }
59 59
 
60
-		if (isset($params['root'])){
61
-			$root = $params['root'];
62
-			if (substr($root, 0, 1) !== '/'){
63
-				$root = '/' . $root;
64
-			}
65
-		}
66
-		else{
67
-			$root = '/';
68
-		}
60
+        if (isset($params['root'])){
61
+            $root = $params['root'];
62
+            if (substr($root, 0, 1) !== '/'){
63
+                $root = '/' . $root;
64
+            }
65
+        }
66
+        else{
67
+            $root = '/';
68
+        }
69 69
 
70
-		$params['host'] = $host;
71
-		$params['root'] = $contextPath . self::OC_URL_SUFFIX . $root;
70
+        $params['host'] = $host;
71
+        $params['root'] = $contextPath . self::OC_URL_SUFFIX . $root;
72 72
 
73
-		parent::__construct($params);
74
-	}
73
+        parent::__construct($params);
74
+    }
75 75
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/AmazonS3.php 1 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.
apps/files_external/lib/Lib/Storage/SMB.php 1 patch
Indentation   +450 added lines, -450 removed lines patch added patch discarded remove patch
@@ -53,454 +53,454 @@
 block discarded – undo
53 53
 use OCP\Files\StorageNotAvailableException;
54 54
 
55 55
 class SMB extends Common implements INotifyStorage {
56
-	/**
57
-	 * @var \Icewind\SMB\Server
58
-	 */
59
-	protected $server;
60
-
61
-	/**
62
-	 * @var \Icewind\SMB\Share
63
-	 */
64
-	protected $share;
65
-
66
-	/**
67
-	 * @var string
68
-	 */
69
-	protected $root;
70
-
71
-	/**
72
-	 * @var \Icewind\SMB\FileInfo[]
73
-	 */
74
-	protected $statCache;
75
-
76
-	public function __construct($params) {
77
-		if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
78
-			if (Server::NativeAvailable()) {
79
-				$this->server = new NativeServer($params['host'], $params['user'], $params['password']);
80
-			} else {
81
-				$this->server = new Server($params['host'], $params['user'], $params['password']);
82
-			}
83
-			$this->share = $this->server->getShare(trim($params['share'], '/'));
84
-
85
-			$this->root = isset($params['root']) ? $params['root'] : '/';
86
-			if (!$this->root || $this->root[0] != '/') {
87
-				$this->root = '/' . $this->root;
88
-			}
89
-			if (substr($this->root, -1, 1) != '/') {
90
-				$this->root .= '/';
91
-			}
92
-		} else {
93
-			throw new \Exception('Invalid configuration');
94
-		}
95
-		$this->statCache = new CappedMemoryCache();
96
-	}
97
-
98
-	/**
99
-	 * @return string
100
-	 */
101
-	public function getId() {
102
-		// FIXME: double slash to keep compatible with the old storage ids,
103
-		// failure to do so will lead to creation of a new storage id and
104
-		// loss of shares from the storage
105
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
106
-	}
107
-
108
-	/**
109
-	 * @param string $path
110
-	 * @return string
111
-	 */
112
-	protected function buildPath($path) {
113
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
114
-	}
115
-
116
-	protected function relativePath($fullPath) {
117
-		if ($fullPath === $this->root) {
118
-			return '';
119
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
120
-			return substr($fullPath, strlen($this->root));
121
-		} else {
122
-			return null;
123
-		}
124
-	}
125
-
126
-	/**
127
-	 * @param string $path
128
-	 * @return \Icewind\SMB\IFileInfo
129
-	 * @throws StorageNotAvailableException
130
-	 */
131
-	protected function getFileInfo($path) {
132
-		try {
133
-			$path = $this->buildPath($path);
134
-			if (!isset($this->statCache[$path])) {
135
-				$this->statCache[$path] = $this->share->stat($path);
136
-			}
137
-			return $this->statCache[$path];
138
-		} catch (ConnectException $e) {
139
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
140
-		}
141
-	}
142
-
143
-	/**
144
-	 * @param string $path
145
-	 * @return \Icewind\SMB\IFileInfo[]
146
-	 * @throws StorageNotAvailableException
147
-	 */
148
-	protected function getFolderContents($path) {
149
-		try {
150
-			$path = $this->buildPath($path);
151
-			$files = $this->share->dir($path);
152
-			foreach ($files as $file) {
153
-				$this->statCache[$path . '/' . $file->getName()] = $file;
154
-			}
155
-			return array_filter($files, function (IFileInfo $file) {
156
-				return !$file->isHidden();
157
-			});
158
-		} catch (ConnectException $e) {
159
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
160
-		}
161
-	}
162
-
163
-	/**
164
-	 * @param \Icewind\SMB\IFileInfo $info
165
-	 * @return array
166
-	 */
167
-	protected function formatInfo($info) {
168
-		return array(
169
-			'size' => $info->getSize(),
170
-			'mtime' => $info->getMTime()
171
-		);
172
-	}
173
-
174
-	/**
175
-	 * @param string $path
176
-	 * @return array
177
-	 */
178
-	public function stat($path) {
179
-		$result = $this->formatInfo($this->getFileInfo($path));
180
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
181
-			$result['mtime'] = $this->shareMTime();
182
-		}
183
-		return $result;
184
-	}
185
-
186
-	/**
187
-	 * get the best guess for the modification time of the share
188
-	 *
189
-	 * @return int
190
-	 */
191
-	private function shareMTime() {
192
-		$highestMTime = 0;
193
-		$files = $this->share->dir($this->root);
194
-		foreach ($files as $fileInfo) {
195
-			if ($fileInfo->getMTime() > $highestMTime) {
196
-				$highestMTime = $fileInfo->getMTime();
197
-			}
198
-		}
199
-		return $highestMTime;
200
-	}
201
-
202
-	/**
203
-	 * Check if the path is our root dir (not the smb one)
204
-	 *
205
-	 * @param string $path the path
206
-	 * @return bool
207
-	 */
208
-	private function isRootDir($path) {
209
-		return $path === '' || $path === '/' || $path === '.';
210
-	}
211
-
212
-	/**
213
-	 * Check if our root points to a smb share
214
-	 *
215
-	 * @return bool true if our root points to a share false otherwise
216
-	 */
217
-	private function remoteIsShare() {
218
-		return $this->share->getName() && (!$this->root || $this->root === '/');
219
-	}
220
-
221
-	/**
222
-	 * @param string $path
223
-	 * @return bool
224
-	 */
225
-	public function unlink($path) {
226
-		try {
227
-			if ($this->is_dir($path)) {
228
-				return $this->rmdir($path);
229
-			} else {
230
-				$path = $this->buildPath($path);
231
-				unset($this->statCache[$path]);
232
-				$this->share->del($path);
233
-				return true;
234
-			}
235
-		} catch (NotFoundException $e) {
236
-			return false;
237
-		} catch (ForbiddenException $e) {
238
-			return false;
239
-		} catch (ConnectException $e) {
240
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * @param string $path1 the old name
246
-	 * @param string $path2 the new name
247
-	 * @return bool
248
-	 */
249
-	public function rename($path1, $path2) {
250
-		try {
251
-			$this->remove($path2);
252
-			$path1 = $this->buildPath($path1);
253
-			$path2 = $this->buildPath($path2);
254
-			return $this->share->rename($path1, $path2);
255
-		} catch (NotFoundException $e) {
256
-			return false;
257
-		} catch (ForbiddenException $e) {
258
-			return false;
259
-		} catch (ConnectException $e) {
260
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
261
-		}
262
-	}
263
-
264
-	/**
265
-	 * check if a file or folder has been updated since $time
266
-	 *
267
-	 * @param string $path
268
-	 * @param int $time
269
-	 * @return bool
270
-	 */
271
-	public function hasUpdated($path, $time) {
272
-		if (!$path and $this->root == '/') {
273
-			// mtime doesn't work for shares, but giving the nature of the backend,
274
-			// doing a full update is still just fast enough
275
-			return true;
276
-		} else {
277
-			$actualTime = $this->filemtime($path);
278
-			return $actualTime > $time;
279
-		}
280
-	}
281
-
282
-	/**
283
-	 * @param string $path
284
-	 * @param string $mode
285
-	 * @return resource|false
286
-	 */
287
-	public function fopen($path, $mode) {
288
-		$fullPath = $this->buildPath($path);
289
-		try {
290
-			switch ($mode) {
291
-				case 'r':
292
-				case 'rb':
293
-					if (!$this->file_exists($path)) {
294
-						return false;
295
-					}
296
-					return $this->share->read($fullPath);
297
-				case 'w':
298
-				case 'wb':
299
-					$source = $this->share->write($fullPath);
300
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
301
-						unset($this->statCache[$fullPath]);
302
-					});
303
-				case 'a':
304
-				case 'ab':
305
-				case 'r+':
306
-				case 'w+':
307
-				case 'wb+':
308
-				case 'a+':
309
-				case 'x':
310
-				case 'x+':
311
-				case 'c':
312
-				case 'c+':
313
-					//emulate these
314
-					if (strrpos($path, '.') !== false) {
315
-						$ext = substr($path, strrpos($path, '.'));
316
-					} else {
317
-						$ext = '';
318
-					}
319
-					if ($this->file_exists($path)) {
320
-						if (!$this->isUpdatable($path)) {
321
-							return false;
322
-						}
323
-						$tmpFile = $this->getCachedFile($path);
324
-					} else {
325
-						if (!$this->isCreatable(dirname($path))) {
326
-							return false;
327
-						}
328
-						$tmpFile = \OCP\Files::tmpFile($ext);
329
-					}
330
-					$source = fopen($tmpFile, $mode);
331
-					$share = $this->share;
332
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
333
-						unset($this->statCache[$fullPath]);
334
-						$share->put($tmpFile, $fullPath);
335
-						unlink($tmpFile);
336
-					});
337
-			}
338
-			return false;
339
-		} catch (NotFoundException $e) {
340
-			return false;
341
-		} catch (ForbiddenException $e) {
342
-			return false;
343
-		} catch (ConnectException $e) {
344
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
345
-		}
346
-	}
347
-
348
-	public function rmdir($path) {
349
-		try {
350
-			$this->statCache = array();
351
-			$content = $this->share->dir($this->buildPath($path));
352
-			foreach ($content as $file) {
353
-				if ($file->isDirectory()) {
354
-					$this->rmdir($path . '/' . $file->getName());
355
-				} else {
356
-					$this->share->del($file->getPath());
357
-				}
358
-			}
359
-			$this->share->rmdir($this->buildPath($path));
360
-			return true;
361
-		} catch (NotFoundException $e) {
362
-			return false;
363
-		} catch (ForbiddenException $e) {
364
-			return false;
365
-		} catch (ConnectException $e) {
366
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
367
-		}
368
-	}
369
-
370
-	public function touch($path, $time = null) {
371
-		try {
372
-			if (!$this->file_exists($path)) {
373
-				$fh = $this->share->write($this->buildPath($path));
374
-				fclose($fh);
375
-				return true;
376
-			}
377
-			return false;
378
-		} catch (ConnectException $e) {
379
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
380
-		}
381
-	}
382
-
383
-	public function opendir($path) {
384
-		try {
385
-			$files = $this->getFolderContents($path);
386
-		} catch (NotFoundException $e) {
387
-			return false;
388
-		} catch (ForbiddenException $e) {
389
-			return false;
390
-		}
391
-		$names = array_map(function ($info) {
392
-			/** @var \Icewind\SMB\IFileInfo $info */
393
-			return $info->getName();
394
-		}, $files);
395
-		return IteratorDirectory::wrap($names);
396
-	}
397
-
398
-	public function filetype($path) {
399
-		try {
400
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
401
-		} catch (NotFoundException $e) {
402
-			return false;
403
-		} catch (ForbiddenException $e) {
404
-			return false;
405
-		}
406
-	}
407
-
408
-	public function mkdir($path) {
409
-		$path = $this->buildPath($path);
410
-		try {
411
-			$this->share->mkdir($path);
412
-			return true;
413
-		} catch (ConnectException $e) {
414
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
415
-		} catch (Exception $e) {
416
-			return false;
417
-		}
418
-	}
419
-
420
-	public function file_exists($path) {
421
-		try {
422
-			$this->getFileInfo($path);
423
-			return true;
424
-		} catch (NotFoundException $e) {
425
-			return false;
426
-		} catch (ForbiddenException $e) {
427
-			return false;
428
-		} catch (ConnectException $e) {
429
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
430
-		}
431
-	}
432
-
433
-	public function isReadable($path) {
434
-		try {
435
-			$info = $this->getFileInfo($path);
436
-			return !$info->isHidden();
437
-		} catch (NotFoundException $e) {
438
-			return false;
439
-		} catch (ForbiddenException $e) {
440
-			return false;
441
-		}
442
-	}
443
-
444
-	public function isUpdatable($path) {
445
-		try {
446
-			$info = $this->getFileInfo($path);
447
-			// following windows behaviour for read-only folders: they can be written into
448
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
449
-			return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
450
-		} catch (NotFoundException $e) {
451
-			return false;
452
-		} catch (ForbiddenException $e) {
453
-			return false;
454
-		}
455
-	}
456
-
457
-	public function isDeletable($path) {
458
-		try {
459
-			$info = $this->getFileInfo($path);
460
-			return !$info->isHidden() && !$info->isReadOnly();
461
-		} catch (NotFoundException $e) {
462
-			return false;
463
-		} catch (ForbiddenException $e) {
464
-			return false;
465
-		}
466
-	}
467
-
468
-	/**
469
-	 * check if smbclient is installed
470
-	 */
471
-	public static function checkDependencies() {
472
-		return (
473
-			(bool)\OC_Helper::findBinaryPath('smbclient')
474
-			|| Server::NativeAvailable()
475
-		) ? true : ['smbclient'];
476
-	}
477
-
478
-	/**
479
-	 * Test a storage for availability
480
-	 *
481
-	 * @return bool
482
-	 */
483
-	public function test() {
484
-		try {
485
-			return parent::test();
486
-		} catch (Exception $e) {
487
-			return false;
488
-		}
489
-	}
490
-
491
-	public function listen($path, callable $callback) {
492
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
493
-			if ($change instanceof IRenameChange) {
494
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
495
-			} else {
496
-				return $callback($change->getType(), $change->getPath());
497
-			}
498
-		});
499
-	}
500
-
501
-	public function notify($path) {
502
-		$path = '/' . ltrim($path, '/');
503
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
504
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
505
-	}
56
+    /**
57
+     * @var \Icewind\SMB\Server
58
+     */
59
+    protected $server;
60
+
61
+    /**
62
+     * @var \Icewind\SMB\Share
63
+     */
64
+    protected $share;
65
+
66
+    /**
67
+     * @var string
68
+     */
69
+    protected $root;
70
+
71
+    /**
72
+     * @var \Icewind\SMB\FileInfo[]
73
+     */
74
+    protected $statCache;
75
+
76
+    public function __construct($params) {
77
+        if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
78
+            if (Server::NativeAvailable()) {
79
+                $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
80
+            } else {
81
+                $this->server = new Server($params['host'], $params['user'], $params['password']);
82
+            }
83
+            $this->share = $this->server->getShare(trim($params['share'], '/'));
84
+
85
+            $this->root = isset($params['root']) ? $params['root'] : '/';
86
+            if (!$this->root || $this->root[0] != '/') {
87
+                $this->root = '/' . $this->root;
88
+            }
89
+            if (substr($this->root, -1, 1) != '/') {
90
+                $this->root .= '/';
91
+            }
92
+        } else {
93
+            throw new \Exception('Invalid configuration');
94
+        }
95
+        $this->statCache = new CappedMemoryCache();
96
+    }
97
+
98
+    /**
99
+     * @return string
100
+     */
101
+    public function getId() {
102
+        // FIXME: double slash to keep compatible with the old storage ids,
103
+        // failure to do so will lead to creation of a new storage id and
104
+        // loss of shares from the storage
105
+        return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
106
+    }
107
+
108
+    /**
109
+     * @param string $path
110
+     * @return string
111
+     */
112
+    protected function buildPath($path) {
113
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
114
+    }
115
+
116
+    protected function relativePath($fullPath) {
117
+        if ($fullPath === $this->root) {
118
+            return '';
119
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
120
+            return substr($fullPath, strlen($this->root));
121
+        } else {
122
+            return null;
123
+        }
124
+    }
125
+
126
+    /**
127
+     * @param string $path
128
+     * @return \Icewind\SMB\IFileInfo
129
+     * @throws StorageNotAvailableException
130
+     */
131
+    protected function getFileInfo($path) {
132
+        try {
133
+            $path = $this->buildPath($path);
134
+            if (!isset($this->statCache[$path])) {
135
+                $this->statCache[$path] = $this->share->stat($path);
136
+            }
137
+            return $this->statCache[$path];
138
+        } catch (ConnectException $e) {
139
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * @param string $path
145
+     * @return \Icewind\SMB\IFileInfo[]
146
+     * @throws StorageNotAvailableException
147
+     */
148
+    protected function getFolderContents($path) {
149
+        try {
150
+            $path = $this->buildPath($path);
151
+            $files = $this->share->dir($path);
152
+            foreach ($files as $file) {
153
+                $this->statCache[$path . '/' . $file->getName()] = $file;
154
+            }
155
+            return array_filter($files, function (IFileInfo $file) {
156
+                return !$file->isHidden();
157
+            });
158
+        } catch (ConnectException $e) {
159
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
160
+        }
161
+    }
162
+
163
+    /**
164
+     * @param \Icewind\SMB\IFileInfo $info
165
+     * @return array
166
+     */
167
+    protected function formatInfo($info) {
168
+        return array(
169
+            'size' => $info->getSize(),
170
+            'mtime' => $info->getMTime()
171
+        );
172
+    }
173
+
174
+    /**
175
+     * @param string $path
176
+     * @return array
177
+     */
178
+    public function stat($path) {
179
+        $result = $this->formatInfo($this->getFileInfo($path));
180
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
181
+            $result['mtime'] = $this->shareMTime();
182
+        }
183
+        return $result;
184
+    }
185
+
186
+    /**
187
+     * get the best guess for the modification time of the share
188
+     *
189
+     * @return int
190
+     */
191
+    private function shareMTime() {
192
+        $highestMTime = 0;
193
+        $files = $this->share->dir($this->root);
194
+        foreach ($files as $fileInfo) {
195
+            if ($fileInfo->getMTime() > $highestMTime) {
196
+                $highestMTime = $fileInfo->getMTime();
197
+            }
198
+        }
199
+        return $highestMTime;
200
+    }
201
+
202
+    /**
203
+     * Check if the path is our root dir (not the smb one)
204
+     *
205
+     * @param string $path the path
206
+     * @return bool
207
+     */
208
+    private function isRootDir($path) {
209
+        return $path === '' || $path === '/' || $path === '.';
210
+    }
211
+
212
+    /**
213
+     * Check if our root points to a smb share
214
+     *
215
+     * @return bool true if our root points to a share false otherwise
216
+     */
217
+    private function remoteIsShare() {
218
+        return $this->share->getName() && (!$this->root || $this->root === '/');
219
+    }
220
+
221
+    /**
222
+     * @param string $path
223
+     * @return bool
224
+     */
225
+    public function unlink($path) {
226
+        try {
227
+            if ($this->is_dir($path)) {
228
+                return $this->rmdir($path);
229
+            } else {
230
+                $path = $this->buildPath($path);
231
+                unset($this->statCache[$path]);
232
+                $this->share->del($path);
233
+                return true;
234
+            }
235
+        } catch (NotFoundException $e) {
236
+            return false;
237
+        } catch (ForbiddenException $e) {
238
+            return false;
239
+        } catch (ConnectException $e) {
240
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
241
+        }
242
+    }
243
+
244
+    /**
245
+     * @param string $path1 the old name
246
+     * @param string $path2 the new name
247
+     * @return bool
248
+     */
249
+    public function rename($path1, $path2) {
250
+        try {
251
+            $this->remove($path2);
252
+            $path1 = $this->buildPath($path1);
253
+            $path2 = $this->buildPath($path2);
254
+            return $this->share->rename($path1, $path2);
255
+        } catch (NotFoundException $e) {
256
+            return false;
257
+        } catch (ForbiddenException $e) {
258
+            return false;
259
+        } catch (ConnectException $e) {
260
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
261
+        }
262
+    }
263
+
264
+    /**
265
+     * check if a file or folder has been updated since $time
266
+     *
267
+     * @param string $path
268
+     * @param int $time
269
+     * @return bool
270
+     */
271
+    public function hasUpdated($path, $time) {
272
+        if (!$path and $this->root == '/') {
273
+            // mtime doesn't work for shares, but giving the nature of the backend,
274
+            // doing a full update is still just fast enough
275
+            return true;
276
+        } else {
277
+            $actualTime = $this->filemtime($path);
278
+            return $actualTime > $time;
279
+        }
280
+    }
281
+
282
+    /**
283
+     * @param string $path
284
+     * @param string $mode
285
+     * @return resource|false
286
+     */
287
+    public function fopen($path, $mode) {
288
+        $fullPath = $this->buildPath($path);
289
+        try {
290
+            switch ($mode) {
291
+                case 'r':
292
+                case 'rb':
293
+                    if (!$this->file_exists($path)) {
294
+                        return false;
295
+                    }
296
+                    return $this->share->read($fullPath);
297
+                case 'w':
298
+                case 'wb':
299
+                    $source = $this->share->write($fullPath);
300
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
301
+                        unset($this->statCache[$fullPath]);
302
+                    });
303
+                case 'a':
304
+                case 'ab':
305
+                case 'r+':
306
+                case 'w+':
307
+                case 'wb+':
308
+                case 'a+':
309
+                case 'x':
310
+                case 'x+':
311
+                case 'c':
312
+                case 'c+':
313
+                    //emulate these
314
+                    if (strrpos($path, '.') !== false) {
315
+                        $ext = substr($path, strrpos($path, '.'));
316
+                    } else {
317
+                        $ext = '';
318
+                    }
319
+                    if ($this->file_exists($path)) {
320
+                        if (!$this->isUpdatable($path)) {
321
+                            return false;
322
+                        }
323
+                        $tmpFile = $this->getCachedFile($path);
324
+                    } else {
325
+                        if (!$this->isCreatable(dirname($path))) {
326
+                            return false;
327
+                        }
328
+                        $tmpFile = \OCP\Files::tmpFile($ext);
329
+                    }
330
+                    $source = fopen($tmpFile, $mode);
331
+                    $share = $this->share;
332
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
333
+                        unset($this->statCache[$fullPath]);
334
+                        $share->put($tmpFile, $fullPath);
335
+                        unlink($tmpFile);
336
+                    });
337
+            }
338
+            return false;
339
+        } catch (NotFoundException $e) {
340
+            return false;
341
+        } catch (ForbiddenException $e) {
342
+            return false;
343
+        } catch (ConnectException $e) {
344
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
345
+        }
346
+    }
347
+
348
+    public function rmdir($path) {
349
+        try {
350
+            $this->statCache = array();
351
+            $content = $this->share->dir($this->buildPath($path));
352
+            foreach ($content as $file) {
353
+                if ($file->isDirectory()) {
354
+                    $this->rmdir($path . '/' . $file->getName());
355
+                } else {
356
+                    $this->share->del($file->getPath());
357
+                }
358
+            }
359
+            $this->share->rmdir($this->buildPath($path));
360
+            return true;
361
+        } catch (NotFoundException $e) {
362
+            return false;
363
+        } catch (ForbiddenException $e) {
364
+            return false;
365
+        } catch (ConnectException $e) {
366
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
367
+        }
368
+    }
369
+
370
+    public function touch($path, $time = null) {
371
+        try {
372
+            if (!$this->file_exists($path)) {
373
+                $fh = $this->share->write($this->buildPath($path));
374
+                fclose($fh);
375
+                return true;
376
+            }
377
+            return false;
378
+        } catch (ConnectException $e) {
379
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
380
+        }
381
+    }
382
+
383
+    public function opendir($path) {
384
+        try {
385
+            $files = $this->getFolderContents($path);
386
+        } catch (NotFoundException $e) {
387
+            return false;
388
+        } catch (ForbiddenException $e) {
389
+            return false;
390
+        }
391
+        $names = array_map(function ($info) {
392
+            /** @var \Icewind\SMB\IFileInfo $info */
393
+            return $info->getName();
394
+        }, $files);
395
+        return IteratorDirectory::wrap($names);
396
+    }
397
+
398
+    public function filetype($path) {
399
+        try {
400
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
401
+        } catch (NotFoundException $e) {
402
+            return false;
403
+        } catch (ForbiddenException $e) {
404
+            return false;
405
+        }
406
+    }
407
+
408
+    public function mkdir($path) {
409
+        $path = $this->buildPath($path);
410
+        try {
411
+            $this->share->mkdir($path);
412
+            return true;
413
+        } catch (ConnectException $e) {
414
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
415
+        } catch (Exception $e) {
416
+            return false;
417
+        }
418
+    }
419
+
420
+    public function file_exists($path) {
421
+        try {
422
+            $this->getFileInfo($path);
423
+            return true;
424
+        } catch (NotFoundException $e) {
425
+            return false;
426
+        } catch (ForbiddenException $e) {
427
+            return false;
428
+        } catch (ConnectException $e) {
429
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
430
+        }
431
+    }
432
+
433
+    public function isReadable($path) {
434
+        try {
435
+            $info = $this->getFileInfo($path);
436
+            return !$info->isHidden();
437
+        } catch (NotFoundException $e) {
438
+            return false;
439
+        } catch (ForbiddenException $e) {
440
+            return false;
441
+        }
442
+    }
443
+
444
+    public function isUpdatable($path) {
445
+        try {
446
+            $info = $this->getFileInfo($path);
447
+            // following windows behaviour for read-only folders: they can be written into
448
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
449
+            return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
450
+        } catch (NotFoundException $e) {
451
+            return false;
452
+        } catch (ForbiddenException $e) {
453
+            return false;
454
+        }
455
+    }
456
+
457
+    public function isDeletable($path) {
458
+        try {
459
+            $info = $this->getFileInfo($path);
460
+            return !$info->isHidden() && !$info->isReadOnly();
461
+        } catch (NotFoundException $e) {
462
+            return false;
463
+        } catch (ForbiddenException $e) {
464
+            return false;
465
+        }
466
+    }
467
+
468
+    /**
469
+     * check if smbclient is installed
470
+     */
471
+    public static function checkDependencies() {
472
+        return (
473
+            (bool)\OC_Helper::findBinaryPath('smbclient')
474
+            || Server::NativeAvailable()
475
+        ) ? true : ['smbclient'];
476
+    }
477
+
478
+    /**
479
+     * Test a storage for availability
480
+     *
481
+     * @return bool
482
+     */
483
+    public function test() {
484
+        try {
485
+            return parent::test();
486
+        } catch (Exception $e) {
487
+            return false;
488
+        }
489
+    }
490
+
491
+    public function listen($path, callable $callback) {
492
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
493
+            if ($change instanceof IRenameChange) {
494
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
495
+            } else {
496
+                return $callback($change->getType(), $change->getPath());
497
+            }
498
+        });
499
+    }
500
+
501
+    public function notify($path) {
502
+        $path = '/' . ltrim($path, '/');
503
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
504
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
505
+    }
506 506
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Dropbox.php 1 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.
apps/files_external/lib/Lib/StorageModifierTrait.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -43,28 +43,28 @@
 block discarded – undo
43 43
  */
44 44
 trait StorageModifierTrait {
45 45
 
46
-	/**
47
-	 * Modify a StorageConfig parameters
48
-	 *
49
-	 * @param StorageConfig $storage
50
-	 * @param IUser $user User the storage is being used as
51
-	 * @throws InsufficientDataForMeaningfulAnswerException
52
-	 * @throws StorageNotAvailableException
53
-	 */
54
-	public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) {
55
-	}
46
+    /**
47
+     * Modify a StorageConfig parameters
48
+     *
49
+     * @param StorageConfig $storage
50
+     * @param IUser $user User the storage is being used as
51
+     * @throws InsufficientDataForMeaningfulAnswerException
52
+     * @throws StorageNotAvailableException
53
+     */
54
+    public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null) {
55
+    }
56 56
 
57
-	/**
58
-	 * Wrap a Storage if necessary
59
-	 *
60
-	 * @param Storage $storage
61
-	 * @return Storage
62
-	 * @throws InsufficientDataForMeaningfulAnswerException
63
-	 * @throws StorageNotAvailableException
64
-	 */
65
-	public function wrapStorage(Storage $storage) {
66
-		return $storage;
67
-	}
57
+    /**
58
+     * Wrap a Storage if necessary
59
+     *
60
+     * @param Storage $storage
61
+     * @return Storage
62
+     * @throws InsufficientDataForMeaningfulAnswerException
63
+     * @throws StorageNotAvailableException
64
+     */
65
+    public function wrapStorage(Storage $storage) {
66
+        return $storage;
67
+    }
68 68
 
69 69
 }
70 70
 
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/PersonalMount.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -32,58 +32,58 @@
 block discarded – undo
32 32
  * Person mount points can be moved by the user
33 33
  */
34 34
 class PersonalMount extends MountPoint implements MoveableMount {
35
-	/** @var UserStoragesService */
36
-	protected $storagesService;
35
+    /** @var UserStoragesService */
36
+    protected $storagesService;
37 37
 
38
-	/** @var int */
39
-	protected $numericStorageId;
38
+    /** @var int */
39
+    protected $numericStorageId;
40 40
 
41
-	/**
42
-	 * @param UserStoragesService $storagesService
43
-	 * @param int $storageId
44
-	 * @param \OCP\Files\Storage $storage
45
-	 * @param string $mountpoint
46
-	 * @param array $arguments (optional) configuration for the storage backend
47
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
48
-	 * @param array $mountOptions mount specific options
49
-	 */
50
-	public function __construct(
51
-		UserStoragesService $storagesService,
52
-		$storageId,
53
-		$storage,
54
-		$mountpoint,
55
-		$arguments = null,
56
-		$loader = null,
57
-		$mountOptions = null
58
-	) {
59
-		parent::__construct($storage, $mountpoint, $arguments, $loader, $mountOptions);
60
-		$this->storagesService = $storagesService;
61
-		$this->numericStorageId = $storageId;
62
-	}
41
+    /**
42
+     * @param UserStoragesService $storagesService
43
+     * @param int $storageId
44
+     * @param \OCP\Files\Storage $storage
45
+     * @param string $mountpoint
46
+     * @param array $arguments (optional) configuration for the storage backend
47
+     * @param \OCP\Files\Storage\IStorageFactory $loader
48
+     * @param array $mountOptions mount specific options
49
+     */
50
+    public function __construct(
51
+        UserStoragesService $storagesService,
52
+        $storageId,
53
+        $storage,
54
+        $mountpoint,
55
+        $arguments = null,
56
+        $loader = null,
57
+        $mountOptions = null
58
+    ) {
59
+        parent::__construct($storage, $mountpoint, $arguments, $loader, $mountOptions);
60
+        $this->storagesService = $storagesService;
61
+        $this->numericStorageId = $storageId;
62
+    }
63 63
 
64
-	/**
65
-	 * Move the mount point to $target
66
-	 *
67
-	 * @param string $target the target mount point
68
-	 * @return bool
69
-	 */
70
-	public function moveMount($target) {
71
-		$storage = $this->storagesService->getStorage($this->numericStorageId);
72
-		// remove "/$user/files" prefix
73
-		$targetParts = explode('/', trim($target, '/'), 3);
74
-		$storage->setMountPoint($targetParts[2]);
75
-		$this->storagesService->updateStorage($storage);
76
-		$this->setMountPoint($target);
77
-		return true;
78
-	}
64
+    /**
65
+     * Move the mount point to $target
66
+     *
67
+     * @param string $target the target mount point
68
+     * @return bool
69
+     */
70
+    public function moveMount($target) {
71
+        $storage = $this->storagesService->getStorage($this->numericStorageId);
72
+        // remove "/$user/files" prefix
73
+        $targetParts = explode('/', trim($target, '/'), 3);
74
+        $storage->setMountPoint($targetParts[2]);
75
+        $this->storagesService->updateStorage($storage);
76
+        $this->setMountPoint($target);
77
+        return true;
78
+    }
79 79
 
80
-	/**
81
-	 * Remove the mount points
82
-	 *
83
-	 * @return bool
84
-	 */
85
-	public function removeMount() {
86
-		$this->storagesService->removeStorage($this->numericStorageId);
87
-		return true;
88
-	}
80
+    /**
81
+     * Remove the mount points
82
+     *
83
+     * @return bool
84
+     */
85
+    public function removeMount() {
86
+        $this->storagesService->removeStorage($this->numericStorageId);
87
+        return true;
88
+    }
89 89
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Notify/SMBNotifyHandler.php 1 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.
apps/files_external/lib/Lib/StorageConfig.php 1 patch
Indentation   +394 added lines, -394 removed lines patch added patch discarded remove patch
@@ -35,398 +35,398 @@
 block discarded – undo
35 35
  * External storage configuration
36 36
  */
37 37
 class StorageConfig implements \JsonSerializable {
38
-	const MOUNT_TYPE_ADMIN = 1;
39
-	const MOUNT_TYPE_PERSONAl = 2;
40
-
41
-	/**
42
-	 * Storage config id
43
-	 *
44
-	 * @var int
45
-	 */
46
-	private $id;
47
-
48
-	/**
49
-	 * Backend
50
-	 *
51
-	 * @var Backend
52
-	 */
53
-	private $backend;
54
-
55
-	/**
56
-	 * Authentication mechanism
57
-	 *
58
-	 * @var AuthMechanism
59
-	 */
60
-	private $authMechanism;
61
-
62
-	/**
63
-	 * Backend options
64
-	 *
65
-	 * @var array
66
-	 */
67
-	private $backendOptions = [];
68
-
69
-	/**
70
-	 * Mount point path, relative to the user's "files" folder
71
-	 *
72
-	 * @var string
73
-	 */
74
-	private $mountPoint;
75
-
76
-	/**
77
-	 * Storage status
78
-	 *
79
-	 * @var int
80
-	 */
81
-	private $status;
82
-
83
-	/**
84
-	 * Status message
85
-	 *
86
-	 * @var string
87
-	 */
88
-	private $statusMessage;
89
-
90
-	/**
91
-	 * Priority
92
-	 *
93
-	 * @var int
94
-	 */
95
-	private $priority;
96
-
97
-	/**
98
-	 * List of users who have access to this storage
99
-	 *
100
-	 * @var array
101
-	 */
102
-	private $applicableUsers = [];
103
-
104
-	/**
105
-	 * List of groups that have access to this storage
106
-	 *
107
-	 * @var array
108
-	 */
109
-	private $applicableGroups = [];
110
-
111
-	/**
112
-	 * Mount-specific options
113
-	 *
114
-	 * @var array
115
-	 */
116
-	private $mountOptions = [];
117
-
118
-	/**
119
-	 * Whether it's a personal or admin mount
120
-	 *
121
-	 * @var int
122
-	 */
123
-	private $type;
124
-
125
-	/**
126
-	 * Creates a storage config
127
-	 *
128
-	 * @param int|null $id config id or null for a new config
129
-	 */
130
-	public function __construct($id = null) {
131
-		$this->id = $id;
132
-		$this->mountOptions['enable_sharing'] = false;
133
-	}
134
-
135
-	/**
136
-	 * Returns the configuration id
137
-	 *
138
-	 * @return int
139
-	 */
140
-	public function getId() {
141
-		return $this->id;
142
-	}
143
-
144
-	/**
145
-	 * Sets the configuration id
146
-	 *
147
-	 * @param int $id configuration id
148
-	 */
149
-	public function setId($id) {
150
-		$this->id = $id;
151
-	}
152
-
153
-	/**
154
-	 * Returns mount point path relative to the user's
155
-	 * "files" folder.
156
-	 *
157
-	 * @return string path
158
-	 */
159
-	public function getMountPoint() {
160
-		return $this->mountPoint;
161
-	}
162
-
163
-	/**
164
-	 * Sets mount point path relative to the user's
165
-	 * "files" folder.
166
-	 * The path will be normalized.
167
-	 *
168
-	 * @param string $mountPoint path
169
-	 */
170
-	public function setMountPoint($mountPoint) {
171
-		$this->mountPoint = \OC\Files\Filesystem::normalizePath($mountPoint);
172
-	}
173
-
174
-	/**
175
-	 * @return Backend
176
-	 */
177
-	public function getBackend() {
178
-		return $this->backend;
179
-	}
180
-
181
-	/**
182
-	 * @param Backend $backend
183
-	 */
184
-	public function setBackend(Backend $backend) {
185
-		$this->backend= $backend;
186
-	}
187
-
188
-	/**
189
-	 * @return AuthMechanism
190
-	 */
191
-	public function getAuthMechanism() {
192
-		return $this->authMechanism;
193
-	}
194
-
195
-	/**
196
-	 * @param AuthMechanism $authMechanism
197
-	 */
198
-	public function setAuthMechanism(AuthMechanism $authMechanism) {
199
-		$this->authMechanism = $authMechanism;
200
-	}
201
-
202
-	/**
203
-	 * Returns the external storage backend-specific options
204
-	 *
205
-	 * @return array backend options
206
-	 */
207
-	public function getBackendOptions() {
208
-		return $this->backendOptions;
209
-	}
210
-
211
-	/**
212
-	 * Sets the external storage backend-specific options
213
-	 *
214
-	 * @param array $backendOptions backend options
215
-	 */
216
-	public function setBackendOptions($backendOptions) {
217
-		if($this->getBackend() instanceof  Backend) {
218
-			$parameters = $this->getBackend()->getParameters();
219
-			foreach($backendOptions as $key => $value) {
220
-				if(isset($parameters[$key])) {
221
-					switch ($parameters[$key]->getType()) {
222
-						case \OCA\Files_External\Lib\DefinitionParameter::VALUE_BOOLEAN:
223
-							$value = (bool)$value;
224
-							break;
225
-					}
226
-					$backendOptions[$key] = $value;
227
-				}
228
-			}
229
-		}
230
-
231
-		$this->backendOptions = $backendOptions;
232
-	}
233
-
234
-	/**
235
-	 * @param string $key
236
-	 * @return mixed
237
-	 */
238
-	public function getBackendOption($key) {
239
-		if (isset($this->backendOptions[$key])) {
240
-			return $this->backendOptions[$key];
241
-		}
242
-		return null;
243
-	}
244
-
245
-	/**
246
-	 * @param string $key
247
-	 * @param mixed $value
248
-	 */
249
-	public function setBackendOption($key, $value) {
250
-		$this->backendOptions[$key] = $value;
251
-	}
252
-
253
-	/**
254
-	 * Returns the mount priority
255
-	 *
256
-	 * @return int priority
257
-	 */
258
-	public function getPriority() {
259
-		return $this->priority;
260
-	}
261
-
262
-	/**
263
-	 * Sets the mount priotity
264
-	 *
265
-	 * @param int $priority priority
266
-	 */
267
-	public function setPriority($priority) {
268
-		$this->priority = $priority;
269
-	}
270
-
271
-	/**
272
-	 * Returns the users for which to mount this storage
273
-	 *
274
-	 * @return array applicable users
275
-	 */
276
-	public function getApplicableUsers() {
277
-		return $this->applicableUsers;
278
-	}
279
-
280
-	/**
281
-	 * Sets the users for which to mount this storage
282
-	 *
283
-	 * @param array|null $applicableUsers applicable users
284
-	 */
285
-	public function setApplicableUsers($applicableUsers) {
286
-		if (is_null($applicableUsers)) {
287
-			$applicableUsers = [];
288
-		}
289
-		$this->applicableUsers = $applicableUsers;
290
-	}
291
-
292
-	/**
293
-	 * Returns the groups for which to mount this storage
294
-	 *
295
-	 * @return array applicable groups
296
-	 */
297
-	public function getApplicableGroups() {
298
-		return $this->applicableGroups;
299
-	}
300
-
301
-	/**
302
-	 * Sets the groups for which to mount this storage
303
-	 *
304
-	 * @param array|null $applicableGroups applicable groups
305
-	 */
306
-	public function setApplicableGroups($applicableGroups) {
307
-		if (is_null($applicableGroups)) {
308
-			$applicableGroups = [];
309
-		}
310
-		$this->applicableGroups = $applicableGroups;
311
-	}
312
-
313
-	/**
314
-	 * Returns the mount-specific options
315
-	 *
316
-	 * @return array mount specific options
317
-	 */
318
-	public function getMountOptions() {
319
-		return $this->mountOptions;
320
-	}
321
-
322
-	/**
323
-	 * Sets the mount-specific options
324
-	 *
325
-	 * @param array $mountOptions applicable groups
326
-	 */
327
-	public function setMountOptions($mountOptions) {
328
-		if (is_null($mountOptions)) {
329
-			$mountOptions = [];
330
-		}
331
-		$this->mountOptions = $mountOptions;
332
-	}
333
-
334
-	/**
335
-	 * @param string $key
336
-	 * @return mixed
337
-	 */
338
-	public function getMountOption($key) {
339
-		if (isset($this->mountOptions[$key])) {
340
-			return $this->mountOptions[$key];
341
-		}
342
-		return null;
343
-	}
344
-
345
-	/**
346
-	 * @param string $key
347
-	 * @param mixed $value
348
-	 */
349
-	public function setMountOption($key, $value) {
350
-		$this->mountOptions[$key] = $value;
351
-	}
352
-
353
-	/**
354
-	 * Gets the storage status, whether the config worked last time
355
-	 *
356
-	 * @return int $status status
357
-	 */
358
-	public function getStatus() {
359
-		return $this->status;
360
-	}
361
-
362
-	/**
363
-	 * Gets the message describing the storage status
364
-	 *
365
-	 * @return string|null
366
-	 */
367
-	public function getStatusMessage() {
368
-		return $this->statusMessage;
369
-	}
370
-
371
-	/**
372
-	 * Sets the storage status, whether the config worked last time
373
-	 *
374
-	 * @param int $status status
375
-	 * @param string|null $message optional message
376
-	 */
377
-	public function setStatus($status, $message = null) {
378
-		$this->status = $status;
379
-		$this->statusMessage = $message;
380
-	}
381
-
382
-	/**
383
-	 * @return int self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAl
384
-	 */
385
-	public function getType() {
386
-		return $this->type;
387
-	}
388
-
389
-	/**
390
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAl
391
-	 */
392
-	public function setType($type) {
393
-		$this->type = $type;
394
-	}
395
-
396
-	/**
397
-	 * Serialize config to JSON
398
-	 *
399
-	 * @return array
400
-	 */
401
-	public function jsonSerialize() {
402
-		$result = [];
403
-		if (!is_null($this->id)) {
404
-			$result['id'] = $this->id;
405
-		}
406
-		$result['mountPoint'] = $this->mountPoint;
407
-		$result['backend'] = $this->backend->getIdentifier();
408
-		$result['authMechanism'] = $this->authMechanism->getIdentifier();
409
-		$result['backendOptions'] = $this->backendOptions;
410
-		if (!is_null($this->priority)) {
411
-			$result['priority'] = $this->priority;
412
-		}
413
-		if (!empty($this->applicableUsers)) {
414
-			$result['applicableUsers'] = $this->applicableUsers;
415
-		}
416
-		if (!empty($this->applicableGroups)) {
417
-			$result['applicableGroups'] = $this->applicableGroups;
418
-		}
419
-		if (!empty($this->mountOptions)) {
420
-			$result['mountOptions'] = $this->mountOptions;
421
-		}
422
-		if (!is_null($this->status)) {
423
-			$result['status'] = $this->status;
424
-		}
425
-		if (!is_null($this->statusMessage)) {
426
-			$result['statusMessage'] = $this->statusMessage;
427
-		}
428
-		$result['userProvided'] = $this->authMechanism instanceof IUserProvided;
429
-		$result['type'] = ($this->getType() === self::MOUNT_TYPE_PERSONAl) ? 'personal': 'system';
430
-		return $result;
431
-	}
38
+    const MOUNT_TYPE_ADMIN = 1;
39
+    const MOUNT_TYPE_PERSONAl = 2;
40
+
41
+    /**
42
+     * Storage config id
43
+     *
44
+     * @var int
45
+     */
46
+    private $id;
47
+
48
+    /**
49
+     * Backend
50
+     *
51
+     * @var Backend
52
+     */
53
+    private $backend;
54
+
55
+    /**
56
+     * Authentication mechanism
57
+     *
58
+     * @var AuthMechanism
59
+     */
60
+    private $authMechanism;
61
+
62
+    /**
63
+     * Backend options
64
+     *
65
+     * @var array
66
+     */
67
+    private $backendOptions = [];
68
+
69
+    /**
70
+     * Mount point path, relative to the user's "files" folder
71
+     *
72
+     * @var string
73
+     */
74
+    private $mountPoint;
75
+
76
+    /**
77
+     * Storage status
78
+     *
79
+     * @var int
80
+     */
81
+    private $status;
82
+
83
+    /**
84
+     * Status message
85
+     *
86
+     * @var string
87
+     */
88
+    private $statusMessage;
89
+
90
+    /**
91
+     * Priority
92
+     *
93
+     * @var int
94
+     */
95
+    private $priority;
96
+
97
+    /**
98
+     * List of users who have access to this storage
99
+     *
100
+     * @var array
101
+     */
102
+    private $applicableUsers = [];
103
+
104
+    /**
105
+     * List of groups that have access to this storage
106
+     *
107
+     * @var array
108
+     */
109
+    private $applicableGroups = [];
110
+
111
+    /**
112
+     * Mount-specific options
113
+     *
114
+     * @var array
115
+     */
116
+    private $mountOptions = [];
117
+
118
+    /**
119
+     * Whether it's a personal or admin mount
120
+     *
121
+     * @var int
122
+     */
123
+    private $type;
124
+
125
+    /**
126
+     * Creates a storage config
127
+     *
128
+     * @param int|null $id config id or null for a new config
129
+     */
130
+    public function __construct($id = null) {
131
+        $this->id = $id;
132
+        $this->mountOptions['enable_sharing'] = false;
133
+    }
134
+
135
+    /**
136
+     * Returns the configuration id
137
+     *
138
+     * @return int
139
+     */
140
+    public function getId() {
141
+        return $this->id;
142
+    }
143
+
144
+    /**
145
+     * Sets the configuration id
146
+     *
147
+     * @param int $id configuration id
148
+     */
149
+    public function setId($id) {
150
+        $this->id = $id;
151
+    }
152
+
153
+    /**
154
+     * Returns mount point path relative to the user's
155
+     * "files" folder.
156
+     *
157
+     * @return string path
158
+     */
159
+    public function getMountPoint() {
160
+        return $this->mountPoint;
161
+    }
162
+
163
+    /**
164
+     * Sets mount point path relative to the user's
165
+     * "files" folder.
166
+     * The path will be normalized.
167
+     *
168
+     * @param string $mountPoint path
169
+     */
170
+    public function setMountPoint($mountPoint) {
171
+        $this->mountPoint = \OC\Files\Filesystem::normalizePath($mountPoint);
172
+    }
173
+
174
+    /**
175
+     * @return Backend
176
+     */
177
+    public function getBackend() {
178
+        return $this->backend;
179
+    }
180
+
181
+    /**
182
+     * @param Backend $backend
183
+     */
184
+    public function setBackend(Backend $backend) {
185
+        $this->backend= $backend;
186
+    }
187
+
188
+    /**
189
+     * @return AuthMechanism
190
+     */
191
+    public function getAuthMechanism() {
192
+        return $this->authMechanism;
193
+    }
194
+
195
+    /**
196
+     * @param AuthMechanism $authMechanism
197
+     */
198
+    public function setAuthMechanism(AuthMechanism $authMechanism) {
199
+        $this->authMechanism = $authMechanism;
200
+    }
201
+
202
+    /**
203
+     * Returns the external storage backend-specific options
204
+     *
205
+     * @return array backend options
206
+     */
207
+    public function getBackendOptions() {
208
+        return $this->backendOptions;
209
+    }
210
+
211
+    /**
212
+     * Sets the external storage backend-specific options
213
+     *
214
+     * @param array $backendOptions backend options
215
+     */
216
+    public function setBackendOptions($backendOptions) {
217
+        if($this->getBackend() instanceof  Backend) {
218
+            $parameters = $this->getBackend()->getParameters();
219
+            foreach($backendOptions as $key => $value) {
220
+                if(isset($parameters[$key])) {
221
+                    switch ($parameters[$key]->getType()) {
222
+                        case \OCA\Files_External\Lib\DefinitionParameter::VALUE_BOOLEAN:
223
+                            $value = (bool)$value;
224
+                            break;
225
+                    }
226
+                    $backendOptions[$key] = $value;
227
+                }
228
+            }
229
+        }
230
+
231
+        $this->backendOptions = $backendOptions;
232
+    }
233
+
234
+    /**
235
+     * @param string $key
236
+     * @return mixed
237
+     */
238
+    public function getBackendOption($key) {
239
+        if (isset($this->backendOptions[$key])) {
240
+            return $this->backendOptions[$key];
241
+        }
242
+        return null;
243
+    }
244
+
245
+    /**
246
+     * @param string $key
247
+     * @param mixed $value
248
+     */
249
+    public function setBackendOption($key, $value) {
250
+        $this->backendOptions[$key] = $value;
251
+    }
252
+
253
+    /**
254
+     * Returns the mount priority
255
+     *
256
+     * @return int priority
257
+     */
258
+    public function getPriority() {
259
+        return $this->priority;
260
+    }
261
+
262
+    /**
263
+     * Sets the mount priotity
264
+     *
265
+     * @param int $priority priority
266
+     */
267
+    public function setPriority($priority) {
268
+        $this->priority = $priority;
269
+    }
270
+
271
+    /**
272
+     * Returns the users for which to mount this storage
273
+     *
274
+     * @return array applicable users
275
+     */
276
+    public function getApplicableUsers() {
277
+        return $this->applicableUsers;
278
+    }
279
+
280
+    /**
281
+     * Sets the users for which to mount this storage
282
+     *
283
+     * @param array|null $applicableUsers applicable users
284
+     */
285
+    public function setApplicableUsers($applicableUsers) {
286
+        if (is_null($applicableUsers)) {
287
+            $applicableUsers = [];
288
+        }
289
+        $this->applicableUsers = $applicableUsers;
290
+    }
291
+
292
+    /**
293
+     * Returns the groups for which to mount this storage
294
+     *
295
+     * @return array applicable groups
296
+     */
297
+    public function getApplicableGroups() {
298
+        return $this->applicableGroups;
299
+    }
300
+
301
+    /**
302
+     * Sets the groups for which to mount this storage
303
+     *
304
+     * @param array|null $applicableGroups applicable groups
305
+     */
306
+    public function setApplicableGroups($applicableGroups) {
307
+        if (is_null($applicableGroups)) {
308
+            $applicableGroups = [];
309
+        }
310
+        $this->applicableGroups = $applicableGroups;
311
+    }
312
+
313
+    /**
314
+     * Returns the mount-specific options
315
+     *
316
+     * @return array mount specific options
317
+     */
318
+    public function getMountOptions() {
319
+        return $this->mountOptions;
320
+    }
321
+
322
+    /**
323
+     * Sets the mount-specific options
324
+     *
325
+     * @param array $mountOptions applicable groups
326
+     */
327
+    public function setMountOptions($mountOptions) {
328
+        if (is_null($mountOptions)) {
329
+            $mountOptions = [];
330
+        }
331
+        $this->mountOptions = $mountOptions;
332
+    }
333
+
334
+    /**
335
+     * @param string $key
336
+     * @return mixed
337
+     */
338
+    public function getMountOption($key) {
339
+        if (isset($this->mountOptions[$key])) {
340
+            return $this->mountOptions[$key];
341
+        }
342
+        return null;
343
+    }
344
+
345
+    /**
346
+     * @param string $key
347
+     * @param mixed $value
348
+     */
349
+    public function setMountOption($key, $value) {
350
+        $this->mountOptions[$key] = $value;
351
+    }
352
+
353
+    /**
354
+     * Gets the storage status, whether the config worked last time
355
+     *
356
+     * @return int $status status
357
+     */
358
+    public function getStatus() {
359
+        return $this->status;
360
+    }
361
+
362
+    /**
363
+     * Gets the message describing the storage status
364
+     *
365
+     * @return string|null
366
+     */
367
+    public function getStatusMessage() {
368
+        return $this->statusMessage;
369
+    }
370
+
371
+    /**
372
+     * Sets the storage status, whether the config worked last time
373
+     *
374
+     * @param int $status status
375
+     * @param string|null $message optional message
376
+     */
377
+    public function setStatus($status, $message = null) {
378
+        $this->status = $status;
379
+        $this->statusMessage = $message;
380
+    }
381
+
382
+    /**
383
+     * @return int self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAl
384
+     */
385
+    public function getType() {
386
+        return $this->type;
387
+    }
388
+
389
+    /**
390
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAl
391
+     */
392
+    public function setType($type) {
393
+        $this->type = $type;
394
+    }
395
+
396
+    /**
397
+     * Serialize config to JSON
398
+     *
399
+     * @return array
400
+     */
401
+    public function jsonSerialize() {
402
+        $result = [];
403
+        if (!is_null($this->id)) {
404
+            $result['id'] = $this->id;
405
+        }
406
+        $result['mountPoint'] = $this->mountPoint;
407
+        $result['backend'] = $this->backend->getIdentifier();
408
+        $result['authMechanism'] = $this->authMechanism->getIdentifier();
409
+        $result['backendOptions'] = $this->backendOptions;
410
+        if (!is_null($this->priority)) {
411
+            $result['priority'] = $this->priority;
412
+        }
413
+        if (!empty($this->applicableUsers)) {
414
+            $result['applicableUsers'] = $this->applicableUsers;
415
+        }
416
+        if (!empty($this->applicableGroups)) {
417
+            $result['applicableGroups'] = $this->applicableGroups;
418
+        }
419
+        if (!empty($this->mountOptions)) {
420
+            $result['mountOptions'] = $this->mountOptions;
421
+        }
422
+        if (!is_null($this->status)) {
423
+            $result['status'] = $this->status;
424
+        }
425
+        if (!is_null($this->statusMessage)) {
426
+            $result['statusMessage'] = $this->statusMessage;
427
+        }
428
+        $result['userProvided'] = $this->authMechanism instanceof IUserProvided;
429
+        $result['type'] = ($this->getType() === self::MOUNT_TYPE_PERSONAl) ? 'personal': 'system';
430
+        return $result;
431
+    }
432 432
 }
Please login to merge, or discard this patch.