Completed
Pull Request — master (#3770)
by Thomas
38:05 queued 14:21
created
apps/files_sharing/lib/External/Scanner.php 1 patch
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -32,97 +32,97 @@
 block discarded – undo
32 32
 use OCP\Files\StorageNotAvailableException;
33 33
 
34 34
 class Scanner extends \OC\Files\Cache\Scanner {
35
-	/** @var \OCA\Files_Sharing\External\Storage */
36
-	protected $storage;
35
+    /** @var \OCA\Files_Sharing\External\Storage */
36
+    protected $storage;
37 37
 
38
-	/** {@inheritDoc} */
39
-	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
40
-		if(!$this->storage->remoteIsOwnCloud()) {
41
-			return parent::scan($path, $recursive, $recursive, $lock);
42
-		}
38
+    /** {@inheritDoc} */
39
+    public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
40
+        if(!$this->storage->remoteIsOwnCloud()) {
41
+            return parent::scan($path, $recursive, $recursive, $lock);
42
+        }
43 43
 
44
-		$this->scanAll();
45
-	}
44
+        $this->scanAll();
45
+    }
46 46
 
47
-	/**
48
-	 * Scan a single file and store it in the cache.
49
-	 * If an exception happened while accessing the external storage,
50
-	 * the storage will be checked for availability and removed
51
-	 * if it is not available any more.
52
-	 *
53
-	 * @param string $file file to scan
54
-	 * @param int $reuseExisting
55
-	 * @param int $parentId
56
-	 * @param array | null $cacheData existing data in the cache for the file to be scanned
57
-	 * @param bool $lock set to false to disable getting an additional read lock during scanning
58
-	 * @return array an array of metadata of the scanned file
59
-	 */
60
-	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
61
-		try {
62
-			return parent::scanFile($file, $reuseExisting);
63
-		} catch (ForbiddenException $e) {
64
-			$this->storage->checkStorageAvailability();
65
-		} catch (NotFoundException $e) {
66
-			// if the storage isn't found, the call to
67
-			// checkStorageAvailable() will verify it and remove it
68
-			// if appropriate
69
-			$this->storage->checkStorageAvailability();
70
-		} catch (StorageInvalidException $e) {
71
-			$this->storage->checkStorageAvailability();
72
-		} catch (StorageNotAvailableException $e) {
73
-			$this->storage->checkStorageAvailability();
74
-		}
75
-	}
47
+    /**
48
+     * Scan a single file and store it in the cache.
49
+     * If an exception happened while accessing the external storage,
50
+     * the storage will be checked for availability and removed
51
+     * if it is not available any more.
52
+     *
53
+     * @param string $file file to scan
54
+     * @param int $reuseExisting
55
+     * @param int $parentId
56
+     * @param array | null $cacheData existing data in the cache for the file to be scanned
57
+     * @param bool $lock set to false to disable getting an additional read lock during scanning
58
+     * @return array an array of metadata of the scanned file
59
+     */
60
+    public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
61
+        try {
62
+            return parent::scanFile($file, $reuseExisting);
63
+        } catch (ForbiddenException $e) {
64
+            $this->storage->checkStorageAvailability();
65
+        } catch (NotFoundException $e) {
66
+            // if the storage isn't found, the call to
67
+            // checkStorageAvailable() will verify it and remove it
68
+            // if appropriate
69
+            $this->storage->checkStorageAvailability();
70
+        } catch (StorageInvalidException $e) {
71
+            $this->storage->checkStorageAvailability();
72
+        } catch (StorageNotAvailableException $e) {
73
+            $this->storage->checkStorageAvailability();
74
+        }
75
+    }
76 76
 
77
-	/**
78
-	 * Checks the remote share for changes.
79
-	 * If changes are available, scan them and update
80
-	 * the cache.
81
-	 * @throws NotFoundException
82
-	 * @throws StorageInvalidException
83
-	 * @throws \Exception
84
-	 */
85
-	public function scanAll() {
86
-		try {
87
-			$data = $this->storage->getShareInfo();
88
-		} catch (\Exception $e) {
89
-			$this->storage->checkStorageAvailability();
90
-			throw new \Exception(
91
-				'Error while scanning remote share: "' .
92
-				$this->storage->getRemote() . '" ' .
93
-				$e->getMessage()
94
-			);
95
-		}
96
-		if ($data['status'] === 'success') {
97
-			$this->addResult($data['data'], '');
98
-		} else {
99
-			throw new \Exception(
100
-				'Error while scanning remote share: "' .
101
-				$this->storage->getRemote() . '"'
102
-			);
103
-		}
104
-	}
77
+    /**
78
+     * Checks the remote share for changes.
79
+     * If changes are available, scan them and update
80
+     * the cache.
81
+     * @throws NotFoundException
82
+     * @throws StorageInvalidException
83
+     * @throws \Exception
84
+     */
85
+    public function scanAll() {
86
+        try {
87
+            $data = $this->storage->getShareInfo();
88
+        } catch (\Exception $e) {
89
+            $this->storage->checkStorageAvailability();
90
+            throw new \Exception(
91
+                'Error while scanning remote share: "' .
92
+                $this->storage->getRemote() . '" ' .
93
+                $e->getMessage()
94
+            );
95
+        }
96
+        if ($data['status'] === 'success') {
97
+            $this->addResult($data['data'], '');
98
+        } else {
99
+            throw new \Exception(
100
+                'Error while scanning remote share: "' .
101
+                $this->storage->getRemote() . '"'
102
+            );
103
+        }
104
+    }
105 105
 
106
-	/**
107
-	 * @param array $data
108
-	 * @param string $path
109
-	 */
110
-	private function addResult($data, $path) {
111
-		$id = $this->cache->put($path, $data);
112
-		if (isset($data['children'])) {
113
-			$children = [];
114
-			foreach ($data['children'] as $child) {
115
-				$children[$child['name']] = true;
116
-				$this->addResult($child, ltrim($path . '/' . $child['name'], '/'));
117
-			}
106
+    /**
107
+     * @param array $data
108
+     * @param string $path
109
+     */
110
+    private function addResult($data, $path) {
111
+        $id = $this->cache->put($path, $data);
112
+        if (isset($data['children'])) {
113
+            $children = [];
114
+            foreach ($data['children'] as $child) {
115
+                $children[$child['name']] = true;
116
+                $this->addResult($child, ltrim($path . '/' . $child['name'], '/'));
117
+            }
118 118
 
119
-			$existingCache = $this->cache->getFolderContentsById($id);
120
-			foreach ($existingCache as $existingChild) {
121
-				// if an existing child is not in the new data, remove it
122
-				if (!isset($children[$existingChild['name']])) {
123
-					$this->cache->remove(ltrim($path . '/' . $existingChild['name'], '/'));
124
-				}
125
-			}
126
-		}
127
-	}
119
+            $existingCache = $this->cache->getFolderContentsById($id);
120
+            foreach ($existingCache as $existingChild) {
121
+                // if an existing child is not in the new data, remove it
122
+                if (!isset($children[$existingChild['name']])) {
123
+                    $this->cache->remove(ltrim($path . '/' . $existingChild['name'], '/'));
124
+                }
125
+            }
126
+        }
127
+    }
128 128
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Cache.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -27,44 +27,44 @@
 block discarded – undo
27 27
 use OCP\Federation\ICloudId;
28 28
 
29 29
 class Cache extends \OC\Files\Cache\Cache {
30
-	/** @var ICloudId */
31
-	private $cloudId;
32
-	private $remote;
33
-	private $remoteUser;
34
-	private $storage;
30
+    /** @var ICloudId */
31
+    private $cloudId;
32
+    private $remote;
33
+    private $remoteUser;
34
+    private $storage;
35 35
 
36
-	/**
37
-	 * @param \OCA\Files_Sharing\External\Storage $storage
38
-	 * @param ICloudId $cloudId
39
-	 */
40
-	public function __construct($storage, ICloudId $cloudId) {
41
-		$this->cloudId = $cloudId;
42
-		$this->storage = $storage;
43
-		list(, $remote) = explode('://', $cloudId->getRemote(), 2);
44
-		$this->remote = $remote;
45
-		$this->remoteUser = $cloudId->getUser();
46
-		parent::__construct($storage);
47
-	}
36
+    /**
37
+     * @param \OCA\Files_Sharing\External\Storage $storage
38
+     * @param ICloudId $cloudId
39
+     */
40
+    public function __construct($storage, ICloudId $cloudId) {
41
+        $this->cloudId = $cloudId;
42
+        $this->storage = $storage;
43
+        list(, $remote) = explode('://', $cloudId->getRemote(), 2);
44
+        $this->remote = $remote;
45
+        $this->remoteUser = $cloudId->getUser();
46
+        parent::__construct($storage);
47
+    }
48 48
 
49
-	public function get($file) {
50
-		$result = parent::get($file);
51
-		if (!$result) {
52
-			return false;
53
-		}
54
-		$result['displayname_owner'] = $this->cloudId->getDisplayId();
55
-		if (!$file || $file === '') {
56
-			$result['is_share_mount_point'] = true;
57
-			$mountPoint = rtrim($this->storage->getMountPoint());
58
-			$result['name'] = basename($mountPoint);
59
-		}
60
-		return $result;
61
-	}
49
+    public function get($file) {
50
+        $result = parent::get($file);
51
+        if (!$result) {
52
+            return false;
53
+        }
54
+        $result['displayname_owner'] = $this->cloudId->getDisplayId();
55
+        if (!$file || $file === '') {
56
+            $result['is_share_mount_point'] = true;
57
+            $mountPoint = rtrim($this->storage->getMountPoint());
58
+            $result['name'] = basename($mountPoint);
59
+        }
60
+        return $result;
61
+    }
62 62
 
63
-	public function getFolderContentsById($id) {
64
-		$results = parent::getFolderContentsById($id);
65
-		foreach ($results as &$file) {
66
-			$file['displayname_owner'] = $this->cloudId->getDisplayId();
67
-		}
68
-		return $results;
69
-	}
63
+    public function getFolderContentsById($id) {
64
+        $results = parent::getFolderContentsById($id);
65
+        foreach ($results as &$file) {
66
+            $file['displayname_owner'] = $this->cloudId->getDisplayId();
67
+        }
68
+        return $results;
69
+    }
70 70
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Storage.php 1 patch
Indentation   +324 added lines, -324 removed lines patch added patch discarded remove patch
@@ -41,330 +41,330 @@
 block discarded – undo
41 41
 use OCP\Files\StorageNotAvailableException;
42 42
 
43 43
 class Storage extends DAV implements ISharedStorage {
44
-	/** @var ICloudId */
45
-	private $cloudId;
46
-	/** @var string */
47
-	private $mountPoint;
48
-	/** @var string */
49
-	private $token;
50
-	/** @var \OCP\ICacheFactory */
51
-	private $memcacheFactory;
52
-	/** @var \OCP\Http\Client\IClientService */
53
-	private $httpClient;
54
-	/** @var \OCP\ICertificateManager */
55
-	private $certificateManager;
56
-	/** @var bool */
57
-	private $updateChecked = false;
58
-
59
-	/**
60
-	 * @var \OCA\Files_Sharing\External\Manager
61
-	 */
62
-	private $manager;
63
-
64
-	public function __construct($options) {
65
-		$this->memcacheFactory = \OC::$server->getMemCacheFactory();
66
-		$this->httpClient = $options['HttpClientService'];
67
-		$discoveryManager = new DiscoveryManager(
68
-			$this->memcacheFactory,
69
-			$this->httpClient
70
-		);
71
-
72
-		$this->manager = $options['manager'];
73
-		$this->certificateManager = $options['certificateManager'];
74
-		$this->cloudId = $options['cloudId'];
75
-		list($protocol, $remote) = explode('://', $this->cloudId->getRemote());
76
-		if (strpos($remote, '/')) {
77
-			list($host, $root) = explode('/', $remote, 2);
78
-		} else {
79
-			$host = $remote;
80
-			$root = '';
81
-		}
82
-		$secure = $protocol === 'https';
83
-		$root = rtrim($root, '/') . $discoveryManager->getWebDavEndpoint($this->cloudId->getRemote());
84
-		$this->mountPoint = $options['mountpoint'];
85
-		$this->token = $options['token'];
86
-		parent::__construct(array(
87
-			'secure' => $secure,
88
-			'host' => $host,
89
-			'root' => $root,
90
-			'user' => $options['token'],
91
-			'password' => (string)$options['password']
92
-		));
93
-	}
94
-
95
-	public function getWatcher($path = '', $storage = null) {
96
-		if (!$storage) {
97
-			$storage = $this;
98
-		}
99
-		if (!isset($this->watcher)) {
100
-			$this->watcher = new Watcher($storage);
101
-			$this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
102
-		}
103
-		return $this->watcher;
104
-	}
105
-
106
-	public function getRemoteUser() {
107
-		return $this->cloudId->getUser();
108
-	}
109
-
110
-	public function getRemote() {
111
-		return $this->cloudId->getRemote();
112
-	}
113
-
114
-	public function getMountPoint() {
115
-		return $this->mountPoint;
116
-	}
117
-
118
-	public function getToken() {
119
-		return $this->token;
120
-	}
121
-
122
-	public function getPassword() {
123
-		return $this->password;
124
-	}
125
-
126
-	/**
127
-	 * @brief get id of the mount point
128
-	 * @return string
129
-	 */
130
-	public function getId() {
131
-		return 'shared::' . md5($this->token . '@' . $this->getRemote());
132
-	}
133
-
134
-	public function getCache($path = '', $storage = null) {
135
-		if (is_null($this->cache)) {
136
-			$this->cache = new Cache($this, $this->cloudId);
137
-		}
138
-		return $this->cache;
139
-	}
140
-
141
-	/**
142
-	 * @param string $path
143
-	 * @param \OC\Files\Storage\Storage $storage
144
-	 * @return \OCA\Files_Sharing\External\Scanner
145
-	 */
146
-	public function getScanner($path = '', $storage = null) {
147
-		if (!$storage) {
148
-			$storage = $this;
149
-		}
150
-		if (!isset($this->scanner)) {
151
-			$this->scanner = new Scanner($storage);
152
-		}
153
-		return $this->scanner;
154
-	}
155
-
156
-	/**
157
-	 * check if a file or folder has been updated since $time
158
-	 *
159
-	 * @param string $path
160
-	 * @param int $time
161
-	 * @throws \OCP\Files\StorageNotAvailableException
162
-	 * @throws \OCP\Files\StorageInvalidException
163
-	 * @return bool
164
-	 */
165
-	public function hasUpdated($path, $time) {
166
-		// since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
167
-		// because of that we only do one check for the entire storage per request
168
-		if ($this->updateChecked) {
169
-			return false;
170
-		}
171
-		$this->updateChecked = true;
172
-		try {
173
-			return parent::hasUpdated('', $time);
174
-		} catch (StorageInvalidException $e) {
175
-			// check if it needs to be removed
176
-			$this->checkStorageAvailability();
177
-			throw $e;
178
-		} catch (StorageNotAvailableException $e) {
179
-			// check if it needs to be removed or just temp unavailable
180
-			$this->checkStorageAvailability();
181
-			throw $e;
182
-		}
183
-	}
184
-
185
-	public function test() {
186
-		try {
187
-			return parent::test();
188
-		} catch (StorageInvalidException $e) {
189
-			// check if it needs to be removed
190
-			$this->checkStorageAvailability();
191
-			throw $e;
192
-		} catch (StorageNotAvailableException $e) {
193
-			// check if it needs to be removed or just temp unavailable
194
-			$this->checkStorageAvailability();
195
-			throw $e;
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * Check whether this storage is permanently or temporarily
201
-	 * unavailable
202
-	 *
203
-	 * @throws \OCP\Files\StorageNotAvailableException
204
-	 * @throws \OCP\Files\StorageInvalidException
205
-	 */
206
-	public function checkStorageAvailability() {
207
-		// see if we can find out why the share is unavailable
208
-		try {
209
-			$this->getShareInfo();
210
-		} catch (NotFoundException $e) {
211
-			// a 404 can either mean that the share no longer exists or there is no ownCloud on the remote
212
-			if ($this->testRemote()) {
213
-				// valid ownCloud instance means that the public share no longer exists
214
-				// since this is permanent (re-sharing the file will create a new token)
215
-				// we remove the invalid storage
216
-				$this->manager->removeShare($this->mountPoint);
217
-				$this->manager->getMountManager()->removeMount($this->mountPoint);
218
-				throw new StorageInvalidException();
219
-			} else {
220
-				// ownCloud instance is gone, likely to be a temporary server configuration error
221
-				throw new StorageNotAvailableException();
222
-			}
223
-		} catch (ForbiddenException $e) {
224
-			// auth error, remove share for now (provide a dialog in the future)
225
-			$this->manager->removeShare($this->mountPoint);
226
-			$this->manager->getMountManager()->removeMount($this->mountPoint);
227
-			throw new StorageInvalidException();
228
-		} catch (\GuzzleHttp\Exception\ConnectException $e) {
229
-			throw new StorageNotAvailableException();
230
-		} catch (\GuzzleHttp\Exception\RequestException $e) {
231
-			throw new StorageNotAvailableException();
232
-		} catch (\Exception $e) {
233
-			throw $e;
234
-		}
235
-	}
236
-
237
-	public function file_exists($path) {
238
-		if ($path === '') {
239
-			return true;
240
-		} else {
241
-			return parent::file_exists($path);
242
-		}
243
-	}
244
-
245
-	/**
246
-	 * check if the configured remote is a valid federated share provider
247
-	 *
248
-	 * @return bool
249
-	 */
250
-	protected function testRemote() {
251
-		try {
252
-			return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
253
-				|| $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
254
-				|| $this->testRemoteUrl($this->getRemote() . '/status.php');
255
-		} catch (\Exception $e) {
256
-			return false;
257
-		}
258
-	}
259
-
260
-	/**
261
-	 * @param string $url
262
-	 * @return bool
263
-	 */
264
-	private function testRemoteUrl($url) {
265
-		$cache = $this->memcacheFactory->create('files_sharing_remote_url');
266
-		if($cache->hasKey($url)) {
267
-			return (bool)$cache->get($url);
268
-		}
269
-
270
-		$client = $this->httpClient->newClient();
271
-		try {
272
-			$result = $client->get($url, [
273
-				'timeout' => 10,
274
-				'connect_timeout' => 10,
275
-			])->getBody();
276
-			$data = json_decode($result);
277
-			$returnValue = (is_object($data) && !empty($data->version));
278
-		} catch (ConnectException $e) {
279
-			$returnValue = false;
280
-		} catch (ClientException $e) {
281
-			$returnValue = false;
282
-		}
283
-
284
-		$cache->set($url, $returnValue);
285
-		return $returnValue;
286
-	}
287
-
288
-	/**
289
-	 * Whether the remote is an ownCloud, used since some sharing features are not
290
-	 * standardized. Let's use this to detect whether to use it.
291
-	 *
292
-	 * @return bool
293
-	 */
294
-	public function remoteIsOwnCloud() {
295
-		if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
296
-			return false;
297
-		}
298
-		return true;
299
-	}
300
-
301
-	/**
302
-	 * @return mixed
303
-	 * @throws ForbiddenException
304
-	 * @throws NotFoundException
305
-	 * @throws \Exception
306
-	 */
307
-	public function getShareInfo() {
308
-		$remote = $this->getRemote();
309
-		$token = $this->getToken();
310
-		$password = $this->getPassword();
311
-
312
-		// If remote is not an ownCloud do not try to get any share info
313
-		if(!$this->remoteIsOwnCloud()) {
314
-			return ['status' => 'unsupported'];
315
-		}
316
-
317
-		$url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
318
-
319
-		// TODO: DI
320
-		$client = \OC::$server->getHTTPClientService()->newClient();
321
-		try {
322
-			$response = $client->post($url, [
323
-				'body' => ['password' => $password],
324
-				'timeout' => 10,
325
-				'connect_timeout' => 10,
326
-			]);
327
-		} catch (\GuzzleHttp\Exception\RequestException $e) {
328
-			if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
329
-				throw new ForbiddenException();
330
-			}
331
-			if ($e->getCode() === Http::STATUS_NOT_FOUND) {
332
-				throw new NotFoundException();
333
-			}
334
-			// throw this to be on the safe side: the share will still be visible
335
-			// in the UI in case the failure is intermittent, and the user will
336
-			// be able to decide whether to remove it if it's really gone
337
-			throw new StorageNotAvailableException();
338
-		}
339
-
340
-		return json_decode($response->getBody(), true);
341
-	}
342
-
343
-	public function getOwner($path) {
344
-		return $this->cloudId->getDisplayId();
345
-	}
346
-
347
-	public function isSharable($path) {
348
-		if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
349
-			return false;
350
-		}
351
-		return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
352
-	}
44
+    /** @var ICloudId */
45
+    private $cloudId;
46
+    /** @var string */
47
+    private $mountPoint;
48
+    /** @var string */
49
+    private $token;
50
+    /** @var \OCP\ICacheFactory */
51
+    private $memcacheFactory;
52
+    /** @var \OCP\Http\Client\IClientService */
53
+    private $httpClient;
54
+    /** @var \OCP\ICertificateManager */
55
+    private $certificateManager;
56
+    /** @var bool */
57
+    private $updateChecked = false;
58
+
59
+    /**
60
+     * @var \OCA\Files_Sharing\External\Manager
61
+     */
62
+    private $manager;
63
+
64
+    public function __construct($options) {
65
+        $this->memcacheFactory = \OC::$server->getMemCacheFactory();
66
+        $this->httpClient = $options['HttpClientService'];
67
+        $discoveryManager = new DiscoveryManager(
68
+            $this->memcacheFactory,
69
+            $this->httpClient
70
+        );
71
+
72
+        $this->manager = $options['manager'];
73
+        $this->certificateManager = $options['certificateManager'];
74
+        $this->cloudId = $options['cloudId'];
75
+        list($protocol, $remote) = explode('://', $this->cloudId->getRemote());
76
+        if (strpos($remote, '/')) {
77
+            list($host, $root) = explode('/', $remote, 2);
78
+        } else {
79
+            $host = $remote;
80
+            $root = '';
81
+        }
82
+        $secure = $protocol === 'https';
83
+        $root = rtrim($root, '/') . $discoveryManager->getWebDavEndpoint($this->cloudId->getRemote());
84
+        $this->mountPoint = $options['mountpoint'];
85
+        $this->token = $options['token'];
86
+        parent::__construct(array(
87
+            'secure' => $secure,
88
+            'host' => $host,
89
+            'root' => $root,
90
+            'user' => $options['token'],
91
+            'password' => (string)$options['password']
92
+        ));
93
+    }
94
+
95
+    public function getWatcher($path = '', $storage = null) {
96
+        if (!$storage) {
97
+            $storage = $this;
98
+        }
99
+        if (!isset($this->watcher)) {
100
+            $this->watcher = new Watcher($storage);
101
+            $this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
102
+        }
103
+        return $this->watcher;
104
+    }
105
+
106
+    public function getRemoteUser() {
107
+        return $this->cloudId->getUser();
108
+    }
109
+
110
+    public function getRemote() {
111
+        return $this->cloudId->getRemote();
112
+    }
113
+
114
+    public function getMountPoint() {
115
+        return $this->mountPoint;
116
+    }
117
+
118
+    public function getToken() {
119
+        return $this->token;
120
+    }
121
+
122
+    public function getPassword() {
123
+        return $this->password;
124
+    }
125
+
126
+    /**
127
+     * @brief get id of the mount point
128
+     * @return string
129
+     */
130
+    public function getId() {
131
+        return 'shared::' . md5($this->token . '@' . $this->getRemote());
132
+    }
133
+
134
+    public function getCache($path = '', $storage = null) {
135
+        if (is_null($this->cache)) {
136
+            $this->cache = new Cache($this, $this->cloudId);
137
+        }
138
+        return $this->cache;
139
+    }
140
+
141
+    /**
142
+     * @param string $path
143
+     * @param \OC\Files\Storage\Storage $storage
144
+     * @return \OCA\Files_Sharing\External\Scanner
145
+     */
146
+    public function getScanner($path = '', $storage = null) {
147
+        if (!$storage) {
148
+            $storage = $this;
149
+        }
150
+        if (!isset($this->scanner)) {
151
+            $this->scanner = new Scanner($storage);
152
+        }
153
+        return $this->scanner;
154
+    }
155
+
156
+    /**
157
+     * check if a file or folder has been updated since $time
158
+     *
159
+     * @param string $path
160
+     * @param int $time
161
+     * @throws \OCP\Files\StorageNotAvailableException
162
+     * @throws \OCP\Files\StorageInvalidException
163
+     * @return bool
164
+     */
165
+    public function hasUpdated($path, $time) {
166
+        // since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
167
+        // because of that we only do one check for the entire storage per request
168
+        if ($this->updateChecked) {
169
+            return false;
170
+        }
171
+        $this->updateChecked = true;
172
+        try {
173
+            return parent::hasUpdated('', $time);
174
+        } catch (StorageInvalidException $e) {
175
+            // check if it needs to be removed
176
+            $this->checkStorageAvailability();
177
+            throw $e;
178
+        } catch (StorageNotAvailableException $e) {
179
+            // check if it needs to be removed or just temp unavailable
180
+            $this->checkStorageAvailability();
181
+            throw $e;
182
+        }
183
+    }
184
+
185
+    public function test() {
186
+        try {
187
+            return parent::test();
188
+        } catch (StorageInvalidException $e) {
189
+            // check if it needs to be removed
190
+            $this->checkStorageAvailability();
191
+            throw $e;
192
+        } catch (StorageNotAvailableException $e) {
193
+            // check if it needs to be removed or just temp unavailable
194
+            $this->checkStorageAvailability();
195
+            throw $e;
196
+        }
197
+    }
198
+
199
+    /**
200
+     * Check whether this storage is permanently or temporarily
201
+     * unavailable
202
+     *
203
+     * @throws \OCP\Files\StorageNotAvailableException
204
+     * @throws \OCP\Files\StorageInvalidException
205
+     */
206
+    public function checkStorageAvailability() {
207
+        // see if we can find out why the share is unavailable
208
+        try {
209
+            $this->getShareInfo();
210
+        } catch (NotFoundException $e) {
211
+            // a 404 can either mean that the share no longer exists or there is no ownCloud on the remote
212
+            if ($this->testRemote()) {
213
+                // valid ownCloud instance means that the public share no longer exists
214
+                // since this is permanent (re-sharing the file will create a new token)
215
+                // we remove the invalid storage
216
+                $this->manager->removeShare($this->mountPoint);
217
+                $this->manager->getMountManager()->removeMount($this->mountPoint);
218
+                throw new StorageInvalidException();
219
+            } else {
220
+                // ownCloud instance is gone, likely to be a temporary server configuration error
221
+                throw new StorageNotAvailableException();
222
+            }
223
+        } catch (ForbiddenException $e) {
224
+            // auth error, remove share for now (provide a dialog in the future)
225
+            $this->manager->removeShare($this->mountPoint);
226
+            $this->manager->getMountManager()->removeMount($this->mountPoint);
227
+            throw new StorageInvalidException();
228
+        } catch (\GuzzleHttp\Exception\ConnectException $e) {
229
+            throw new StorageNotAvailableException();
230
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
231
+            throw new StorageNotAvailableException();
232
+        } catch (\Exception $e) {
233
+            throw $e;
234
+        }
235
+    }
236
+
237
+    public function file_exists($path) {
238
+        if ($path === '') {
239
+            return true;
240
+        } else {
241
+            return parent::file_exists($path);
242
+        }
243
+    }
244
+
245
+    /**
246
+     * check if the configured remote is a valid federated share provider
247
+     *
248
+     * @return bool
249
+     */
250
+    protected function testRemote() {
251
+        try {
252
+            return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
253
+                || $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
254
+                || $this->testRemoteUrl($this->getRemote() . '/status.php');
255
+        } catch (\Exception $e) {
256
+            return false;
257
+        }
258
+    }
259
+
260
+    /**
261
+     * @param string $url
262
+     * @return bool
263
+     */
264
+    private function testRemoteUrl($url) {
265
+        $cache = $this->memcacheFactory->create('files_sharing_remote_url');
266
+        if($cache->hasKey($url)) {
267
+            return (bool)$cache->get($url);
268
+        }
269
+
270
+        $client = $this->httpClient->newClient();
271
+        try {
272
+            $result = $client->get($url, [
273
+                'timeout' => 10,
274
+                'connect_timeout' => 10,
275
+            ])->getBody();
276
+            $data = json_decode($result);
277
+            $returnValue = (is_object($data) && !empty($data->version));
278
+        } catch (ConnectException $e) {
279
+            $returnValue = false;
280
+        } catch (ClientException $e) {
281
+            $returnValue = false;
282
+        }
283
+
284
+        $cache->set($url, $returnValue);
285
+        return $returnValue;
286
+    }
287
+
288
+    /**
289
+     * Whether the remote is an ownCloud, used since some sharing features are not
290
+     * standardized. Let's use this to detect whether to use it.
291
+     *
292
+     * @return bool
293
+     */
294
+    public function remoteIsOwnCloud() {
295
+        if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
296
+            return false;
297
+        }
298
+        return true;
299
+    }
300
+
301
+    /**
302
+     * @return mixed
303
+     * @throws ForbiddenException
304
+     * @throws NotFoundException
305
+     * @throws \Exception
306
+     */
307
+    public function getShareInfo() {
308
+        $remote = $this->getRemote();
309
+        $token = $this->getToken();
310
+        $password = $this->getPassword();
311
+
312
+        // If remote is not an ownCloud do not try to get any share info
313
+        if(!$this->remoteIsOwnCloud()) {
314
+            return ['status' => 'unsupported'];
315
+        }
316
+
317
+        $url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
318
+
319
+        // TODO: DI
320
+        $client = \OC::$server->getHTTPClientService()->newClient();
321
+        try {
322
+            $response = $client->post($url, [
323
+                'body' => ['password' => $password],
324
+                'timeout' => 10,
325
+                'connect_timeout' => 10,
326
+            ]);
327
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
328
+            if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
329
+                throw new ForbiddenException();
330
+            }
331
+            if ($e->getCode() === Http::STATUS_NOT_FOUND) {
332
+                throw new NotFoundException();
333
+            }
334
+            // throw this to be on the safe side: the share will still be visible
335
+            // in the UI in case the failure is intermittent, and the user will
336
+            // be able to decide whether to remove it if it's really gone
337
+            throw new StorageNotAvailableException();
338
+        }
339
+
340
+        return json_decode($response->getBody(), true);
341
+    }
342
+
343
+    public function getOwner($path) {
344
+        return $this->cloudId->getDisplayId();
345
+    }
346
+
347
+    public function isSharable($path) {
348
+        if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
349
+            return false;
350
+        }
351
+        return ($this->getPermissions($path) & \OCP\Constants::PERMISSION_SHARE);
352
+    }
353 353
 	
354
-	public function getPermissions($path) {
355
-		$response = $this->propfind($path);
356
-		if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
357
-			$permissions = $response['{http://open-collaboration-services.org/ns}share-permissions'];
358
-		} else {
359
-			// use default permission if remote server doesn't provide the share permissions
360
-			if ($this->is_dir($path)) {
361
-				$permissions = \OCP\Constants::PERMISSION_ALL;
362
-			} else {
363
-				$permissions = \OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_CREATE;
364
-			}
365
-		}
366
-
367
-		return $permissions;
368
-	}
354
+    public function getPermissions($path) {
355
+        $response = $this->propfind($path);
356
+        if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
357
+            $permissions = $response['{http://open-collaboration-services.org/ns}share-permissions'];
358
+        } else {
359
+            // use default permission if remote server doesn't provide the share permissions
360
+            if ($this->is_dir($path)) {
361
+                $permissions = \OCP\Constants::PERMISSION_ALL;
362
+            } else {
363
+                $permissions = \OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_CREATE;
364
+            }
365
+        }
366
+
367
+        return $permissions;
368
+    }
369 369
 
370 370
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/MountProvider.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -29,59 +29,59 @@
 block discarded – undo
29 29
 use OCP\IUser;
30 30
 
31 31
 class MountProvider implements IMountProvider {
32
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
32
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
33 33
 
34
-	/**
35
-	 * @var \OCP\IDBConnection
36
-	 */
37
-	private $connection;
34
+    /**
35
+     * @var \OCP\IDBConnection
36
+     */
37
+    private $connection;
38 38
 
39
-	/**
40
-	 * @var callable
41
-	 */
42
-	private $managerProvider;
39
+    /**
40
+     * @var callable
41
+     */
42
+    private $managerProvider;
43 43
 
44
-	/**
45
-	 * @var ICloudIdManager
46
-	 */
47
-	private $cloudIdManager;
44
+    /**
45
+     * @var ICloudIdManager
46
+     */
47
+    private $cloudIdManager;
48 48
 
49
-	/**
50
-	 * @param \OCP\IDBConnection $connection
51
-	 * @param callable $managerProvider due to setup order we need a callable that return the manager instead of the manager itself
52
-	 * @param ICloudIdManager $cloudIdManager
53
-	 */
54
-	public function __construct(IDBConnection $connection, callable $managerProvider, ICloudIdManager $cloudIdManager) {
55
-		$this->connection = $connection;
56
-		$this->managerProvider = $managerProvider;
57
-		$this->cloudIdManager = $cloudIdManager;
58
-	}
49
+    /**
50
+     * @param \OCP\IDBConnection $connection
51
+     * @param callable $managerProvider due to setup order we need a callable that return the manager instead of the manager itself
52
+     * @param ICloudIdManager $cloudIdManager
53
+     */
54
+    public function __construct(IDBConnection $connection, callable $managerProvider, ICloudIdManager $cloudIdManager) {
55
+        $this->connection = $connection;
56
+        $this->managerProvider = $managerProvider;
57
+        $this->cloudIdManager = $cloudIdManager;
58
+    }
59 59
 
60
-	public function getMount(IUser $user, $data, IStorageFactory $storageFactory) {
61
-		$managerProvider = $this->managerProvider;
62
-		$manager = $managerProvider();
63
-		$data['manager'] = $manager;
64
-		$mountPoint = '/' . $user->getUID() . '/files/' . ltrim($data['mountpoint'], '/');
65
-		$data['mountpoint'] = $mountPoint;
66
-		$data['cloudId'] = $this->cloudIdManager->getCloudId($data['owner'], $data['remote']);
67
-		$data['certificateManager'] = \OC::$server->getCertificateManager($user->getUID());
68
-		$data['HttpClientService'] = \OC::$server->getHTTPClientService();
69
-		return new Mount(self::STORAGE, $mountPoint, $data, $manager, $storageFactory);
70
-	}
60
+    public function getMount(IUser $user, $data, IStorageFactory $storageFactory) {
61
+        $managerProvider = $this->managerProvider;
62
+        $manager = $managerProvider();
63
+        $data['manager'] = $manager;
64
+        $mountPoint = '/' . $user->getUID() . '/files/' . ltrim($data['mountpoint'], '/');
65
+        $data['mountpoint'] = $mountPoint;
66
+        $data['cloudId'] = $this->cloudIdManager->getCloudId($data['owner'], $data['remote']);
67
+        $data['certificateManager'] = \OC::$server->getCertificateManager($user->getUID());
68
+        $data['HttpClientService'] = \OC::$server->getHTTPClientService();
69
+        return new Mount(self::STORAGE, $mountPoint, $data, $manager, $storageFactory);
70
+    }
71 71
 
72
-	public function getMountsForUser(IUser $user, IStorageFactory $loader) {
73
-		$query = $this->connection->prepare('
72
+    public function getMountsForUser(IUser $user, IStorageFactory $loader) {
73
+        $query = $this->connection->prepare('
74 74
 				SELECT `remote`, `share_token`, `password`, `mountpoint`, `owner`
75 75
 				FROM `*PREFIX*share_external`
76 76
 				WHERE `user` = ? AND `accepted` = ?
77 77
 			');
78
-		$query->execute([$user->getUID(), 1]);
79
-		$mounts = [];
80
-		while ($row = $query->fetch()) {
81
-			$row['manager'] = $this;
82
-			$row['token'] = $row['share_token'];
83
-			$mounts[] = $this->getMount($user, $row, $loader);
84
-		}
85
-		return $mounts;
86
-	}
78
+        $query->execute([$user->getUID(), 1]);
79
+        $mounts = [];
80
+        while ($row = $query->fetch()) {
81
+            $row['manager'] = $this;
82
+            $row['token'] = $row['share_token'];
83
+            $mounts[] = $this->getMount($user, $row, $loader);
84
+        }
85
+        return $mounts;
86
+    }
87 87
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Watcher.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -23,12 +23,12 @@
 block discarded – undo
23 23
 namespace OCA\Files_Sharing\External;
24 24
 
25 25
 class Watcher extends \OC\Files\Cache\Watcher {
26
-	/**
27
-	 * remove deleted files in $path from the cache
28
-	 *
29
-	 * @param string $path
30
-	 */
31
-	public function cleanFolder($path) {
32
-		// not needed, the scanner takes care of this
33
-	}
26
+    /**
27
+     * remove deleted files in $path from the cache
28
+     *
29
+     * @param string $path
30
+     */
31
+    public function cleanFolder($path) {
32
+        // not needed, the scanner takes care of this
33
+    }
34 34
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -36,434 +36,434 @@
 block discarded – undo
36 36
 use OCP\Notification\IManager;
37 37
 
38 38
 class Manager {
39
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
40
-
41
-	/**
42
-	 * @var string
43
-	 */
44
-	private $uid;
45
-
46
-	/**
47
-	 * @var \OCP\IDBConnection
48
-	 */
49
-	private $connection;
50
-
51
-	/**
52
-	 * @var \OC\Files\Mount\Manager
53
-	 */
54
-	private $mountManager;
55
-
56
-	/**
57
-	 * @var \OCP\Files\Storage\IStorageFactory
58
-	 */
59
-	private $storageLoader;
60
-
61
-	/**
62
-	 * @var IClientService
63
-	 */
64
-	private $clientService;
65
-
66
-	/**
67
-	 * @var IManager
68
-	 */
69
-	private $notificationManager;
70
-	/** @var DiscoveryManager */
71
-	private $discoveryManager;
72
-
73
-	/**
74
-	 * @param \OCP\IDBConnection $connection
75
-	 * @param \OC\Files\Mount\Manager $mountManager
76
-	 * @param \OCP\Files\Storage\IStorageFactory $storageLoader
77
-	 * @param IClientService $clientService
78
-	 * @param IManager $notificationManager
79
-	 * @param DiscoveryManager $discoveryManager
80
-	 * @param string $uid
81
-	 */
82
-	public function __construct(\OCP\IDBConnection $connection,
83
-								\OC\Files\Mount\Manager $mountManager,
84
-								\OCP\Files\Storage\IStorageFactory $storageLoader,
85
-								IClientService $clientService,
86
-								IManager $notificationManager,
87
-								DiscoveryManager $discoveryManager,
88
-								$uid) {
89
-		$this->connection = $connection;
90
-		$this->mountManager = $mountManager;
91
-		$this->storageLoader = $storageLoader;
92
-		$this->clientService = $clientService;
93
-		$this->uid = $uid;
94
-		$this->notificationManager = $notificationManager;
95
-		$this->discoveryManager = $discoveryManager;
96
-	}
97
-
98
-	/**
99
-	 * add new server-to-server share
100
-	 *
101
-	 * @param string $remote
102
-	 * @param string $token
103
-	 * @param string $password
104
-	 * @param string $name
105
-	 * @param string $owner
106
-	 * @param boolean $accepted
107
-	 * @param string $user
108
-	 * @param int $remoteId
109
-	 * @return Mount|null
110
-	 */
111
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
112
-
113
-		$user = $user ? $user : $this->uid;
114
-		$accepted = $accepted ? 1 : 0;
115
-		$name = Filesystem::normalizePath('/' . $name);
116
-
117
-		if (!$accepted) {
118
-			// To avoid conflicts with the mount point generation later,
119
-			// we only use a temporary mount point name here. The real
120
-			// mount point name will be generated when accepting the share,
121
-			// using the original share item name.
122
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
123
-			$mountPoint = $tmpMountPointName;
124
-			$hash = md5($tmpMountPointName);
125
-			$data = [
126
-				'remote'		=> $remote,
127
-				'share_token'	=> $token,
128
-				'password'		=> $password,
129
-				'name'			=> $name,
130
-				'owner'			=> $owner,
131
-				'user'			=> $user,
132
-				'mountpoint'	=> $mountPoint,
133
-				'mountpoint_hash'	=> $hash,
134
-				'accepted'		=> $accepted,
135
-				'remote_id'		=> $remoteId,
136
-			];
137
-
138
-			$i = 1;
139
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
140
-				// The external share already exists for the user
141
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
142
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
143
-				$i++;
144
-			}
145
-			return null;
146
-		}
147
-
148
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
149
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
150
-		$hash = md5($mountPoint);
151
-
152
-		$query = $this->connection->prepare('
39
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
40
+
41
+    /**
42
+     * @var string
43
+     */
44
+    private $uid;
45
+
46
+    /**
47
+     * @var \OCP\IDBConnection
48
+     */
49
+    private $connection;
50
+
51
+    /**
52
+     * @var \OC\Files\Mount\Manager
53
+     */
54
+    private $mountManager;
55
+
56
+    /**
57
+     * @var \OCP\Files\Storage\IStorageFactory
58
+     */
59
+    private $storageLoader;
60
+
61
+    /**
62
+     * @var IClientService
63
+     */
64
+    private $clientService;
65
+
66
+    /**
67
+     * @var IManager
68
+     */
69
+    private $notificationManager;
70
+    /** @var DiscoveryManager */
71
+    private $discoveryManager;
72
+
73
+    /**
74
+     * @param \OCP\IDBConnection $connection
75
+     * @param \OC\Files\Mount\Manager $mountManager
76
+     * @param \OCP\Files\Storage\IStorageFactory $storageLoader
77
+     * @param IClientService $clientService
78
+     * @param IManager $notificationManager
79
+     * @param DiscoveryManager $discoveryManager
80
+     * @param string $uid
81
+     */
82
+    public function __construct(\OCP\IDBConnection $connection,
83
+                                \OC\Files\Mount\Manager $mountManager,
84
+                                \OCP\Files\Storage\IStorageFactory $storageLoader,
85
+                                IClientService $clientService,
86
+                                IManager $notificationManager,
87
+                                DiscoveryManager $discoveryManager,
88
+                                $uid) {
89
+        $this->connection = $connection;
90
+        $this->mountManager = $mountManager;
91
+        $this->storageLoader = $storageLoader;
92
+        $this->clientService = $clientService;
93
+        $this->uid = $uid;
94
+        $this->notificationManager = $notificationManager;
95
+        $this->discoveryManager = $discoveryManager;
96
+    }
97
+
98
+    /**
99
+     * add new server-to-server share
100
+     *
101
+     * @param string $remote
102
+     * @param string $token
103
+     * @param string $password
104
+     * @param string $name
105
+     * @param string $owner
106
+     * @param boolean $accepted
107
+     * @param string $user
108
+     * @param int $remoteId
109
+     * @return Mount|null
110
+     */
111
+    public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
112
+
113
+        $user = $user ? $user : $this->uid;
114
+        $accepted = $accepted ? 1 : 0;
115
+        $name = Filesystem::normalizePath('/' . $name);
116
+
117
+        if (!$accepted) {
118
+            // To avoid conflicts with the mount point generation later,
119
+            // we only use a temporary mount point name here. The real
120
+            // mount point name will be generated when accepting the share,
121
+            // using the original share item name.
122
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
123
+            $mountPoint = $tmpMountPointName;
124
+            $hash = md5($tmpMountPointName);
125
+            $data = [
126
+                'remote'		=> $remote,
127
+                'share_token'	=> $token,
128
+                'password'		=> $password,
129
+                'name'			=> $name,
130
+                'owner'			=> $owner,
131
+                'user'			=> $user,
132
+                'mountpoint'	=> $mountPoint,
133
+                'mountpoint_hash'	=> $hash,
134
+                'accepted'		=> $accepted,
135
+                'remote_id'		=> $remoteId,
136
+            ];
137
+
138
+            $i = 1;
139
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
140
+                // The external share already exists for the user
141
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
142
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
143
+                $i++;
144
+            }
145
+            return null;
146
+        }
147
+
148
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
149
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
150
+        $hash = md5($mountPoint);
151
+
152
+        $query = $this->connection->prepare('
153 153
 				INSERT INTO `*PREFIX*share_external`
154 154
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`)
155 155
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
156 156
 			');
157
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
158
-
159
-		$options = array(
160
-			'remote'	=> $remote,
161
-			'token'		=> $token,
162
-			'password'	=> $password,
163
-			'mountpoint'	=> $mountPoint,
164
-			'owner'		=> $owner
165
-		);
166
-		return $this->mountShare($options);
167
-	}
168
-
169
-	/**
170
-	 * get share
171
-	 *
172
-	 * @param int $id share id
173
-	 * @return mixed share of false
174
-	 */
175
-	public function getShare($id) {
176
-		$getShare = $this->connection->prepare('
157
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
158
+
159
+        $options = array(
160
+            'remote'	=> $remote,
161
+            'token'		=> $token,
162
+            'password'	=> $password,
163
+            'mountpoint'	=> $mountPoint,
164
+            'owner'		=> $owner
165
+        );
166
+        return $this->mountShare($options);
167
+    }
168
+
169
+    /**
170
+     * get share
171
+     *
172
+     * @param int $id share id
173
+     * @return mixed share of false
174
+     */
175
+    public function getShare($id) {
176
+        $getShare = $this->connection->prepare('
177 177
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
178 178
 			FROM  `*PREFIX*share_external`
179 179
 			WHERE `id` = ? AND `user` = ?');
180
-		$result = $getShare->execute(array($id, $this->uid));
180
+        $result = $getShare->execute(array($id, $this->uid));
181 181
 
182
-		return $result ? $getShare->fetch() : false;
183
-	}
182
+        return $result ? $getShare->fetch() : false;
183
+    }
184 184
 
185
-	/**
186
-	 * accept server-to-server share
187
-	 *
188
-	 * @param int $id
189
-	 * @return bool True if the share could be accepted, false otherwise
190
-	 */
191
-	public function acceptShare($id) {
185
+    /**
186
+     * accept server-to-server share
187
+     *
188
+     * @param int $id
189
+     * @return bool True if the share could be accepted, false otherwise
190
+     */
191
+    public function acceptShare($id) {
192 192
 
193
-		$share = $this->getShare($id);
193
+        $share = $this->getShare($id);
194 194
 
195
-		if ($share) {
196
-			$mountPoint = Files::buildNotExistingFileName('/', $share['name']);
197
-			$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
198
-			$hash = md5($mountPoint);
195
+        if ($share) {
196
+            $mountPoint = Files::buildNotExistingFileName('/', $share['name']);
197
+            $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
198
+            $hash = md5($mountPoint);
199 199
 
200
-			$acceptShare = $this->connection->prepare('
200
+            $acceptShare = $this->connection->prepare('
201 201
 				UPDATE `*PREFIX*share_external`
202 202
 				SET `accepted` = ?,
203 203
 					`mountpoint` = ?,
204 204
 					`mountpoint_hash` = ?
205 205
 				WHERE `id` = ? AND `user` = ?');
206
-			$acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
207
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
206
+            $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
207
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
208 208
 
209
-			\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]);
209
+            \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]);
210 210
 
211
-			$this->processNotification($id);
212
-			return true;
213
-		}
211
+            $this->processNotification($id);
212
+            return true;
213
+        }
214 214
 
215
-		return false;
216
-	}
215
+        return false;
216
+    }
217 217
 
218
-	/**
219
-	 * decline server-to-server share
220
-	 *
221
-	 * @param int $id
222
-	 * @return bool True if the share could be declined, false otherwise
223
-	 */
224
-	public function declineShare($id) {
218
+    /**
219
+     * decline server-to-server share
220
+     *
221
+     * @param int $id
222
+     * @return bool True if the share could be declined, false otherwise
223
+     */
224
+    public function declineShare($id) {
225 225
 
226
-		$share = $this->getShare($id);
226
+        $share = $this->getShare($id);
227 227
 
228
-		if ($share) {
229
-			$removeShare = $this->connection->prepare('
228
+        if ($share) {
229
+            $removeShare = $this->connection->prepare('
230 230
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
231
-			$removeShare->execute(array($id, $this->uid));
232
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
233
-
234
-			$this->processNotification($id);
235
-			return true;
236
-		}
237
-
238
-		return false;
239
-	}
240
-
241
-	/**
242
-	 * @param int $remoteShare
243
-	 */
244
-	public function processNotification($remoteShare) {
245
-		$filter = $this->notificationManager->createNotification();
246
-		$filter->setApp('files_sharing')
247
-			->setUser($this->uid)
248
-			->setObject('remote_share', (int) $remoteShare);
249
-		$this->notificationManager->markProcessed($filter);
250
-	}
251
-
252
-	/**
253
-	 * inform remote server whether server-to-server share was accepted/declined
254
-	 *
255
-	 * @param string $remote
256
-	 * @param string $token
257
-	 * @param int $remoteId Share id on the remote host
258
-	 * @param string $feedback
259
-	 * @return boolean
260
-	 */
261
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
262
-
263
-		$url = rtrim($remote, '/') . $this->discoveryManager->getShareEndpoint($remote) . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
264
-		$fields = array('token' => $token);
265
-
266
-		$client = $this->clientService->newClient();
267
-
268
-		try {
269
-			$response = $client->post(
270
-				$url,
271
-				[
272
-					'body' => $fields,
273
-					'connect_timeout' => 10,
274
-				]
275
-			);
276
-		} catch (\Exception $e) {
277
-			return false;
278
-		}
279
-
280
-		$status = json_decode($response->getBody(), true);
281
-
282
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
283
-	}
284
-
285
-	/**
286
-	 * remove '/user/files' from the path and trailing slashes
287
-	 *
288
-	 * @param string $path
289
-	 * @return string
290
-	 */
291
-	protected function stripPath($path) {
292
-		$prefix = '/' . $this->uid . '/files';
293
-		return rtrim(substr($path, strlen($prefix)), '/');
294
-	}
295
-
296
-	public function getMount($data) {
297
-		$data['manager'] = $this;
298
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
299
-		$data['mountpoint'] = $mountPoint;
300
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
301
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
302
-	}
303
-
304
-	/**
305
-	 * @param array $data
306
-	 * @return Mount
307
-	 */
308
-	protected function mountShare($data) {
309
-		$mount = $this->getMount($data);
310
-		$this->mountManager->addMount($mount);
311
-		return $mount;
312
-	}
313
-
314
-	/**
315
-	 * @return \OC\Files\Mount\Manager
316
-	 */
317
-	public function getMountManager() {
318
-		return $this->mountManager;
319
-	}
320
-
321
-	/**
322
-	 * @param string $source
323
-	 * @param string $target
324
-	 * @return bool
325
-	 */
326
-	public function setMountPoint($source, $target) {
327
-		$source = $this->stripPath($source);
328
-		$target = $this->stripPath($target);
329
-		$sourceHash = md5($source);
330
-		$targetHash = md5($target);
331
-
332
-		$query = $this->connection->prepare('
231
+            $removeShare->execute(array($id, $this->uid));
232
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
233
+
234
+            $this->processNotification($id);
235
+            return true;
236
+        }
237
+
238
+        return false;
239
+    }
240
+
241
+    /**
242
+     * @param int $remoteShare
243
+     */
244
+    public function processNotification($remoteShare) {
245
+        $filter = $this->notificationManager->createNotification();
246
+        $filter->setApp('files_sharing')
247
+            ->setUser($this->uid)
248
+            ->setObject('remote_share', (int) $remoteShare);
249
+        $this->notificationManager->markProcessed($filter);
250
+    }
251
+
252
+    /**
253
+     * inform remote server whether server-to-server share was accepted/declined
254
+     *
255
+     * @param string $remote
256
+     * @param string $token
257
+     * @param int $remoteId Share id on the remote host
258
+     * @param string $feedback
259
+     * @return boolean
260
+     */
261
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
262
+
263
+        $url = rtrim($remote, '/') . $this->discoveryManager->getShareEndpoint($remote) . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
264
+        $fields = array('token' => $token);
265
+
266
+        $client = $this->clientService->newClient();
267
+
268
+        try {
269
+            $response = $client->post(
270
+                $url,
271
+                [
272
+                    'body' => $fields,
273
+                    'connect_timeout' => 10,
274
+                ]
275
+            );
276
+        } catch (\Exception $e) {
277
+            return false;
278
+        }
279
+
280
+        $status = json_decode($response->getBody(), true);
281
+
282
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
283
+    }
284
+
285
+    /**
286
+     * remove '/user/files' from the path and trailing slashes
287
+     *
288
+     * @param string $path
289
+     * @return string
290
+     */
291
+    protected function stripPath($path) {
292
+        $prefix = '/' . $this->uid . '/files';
293
+        return rtrim(substr($path, strlen($prefix)), '/');
294
+    }
295
+
296
+    public function getMount($data) {
297
+        $data['manager'] = $this;
298
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
299
+        $data['mountpoint'] = $mountPoint;
300
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
301
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
302
+    }
303
+
304
+    /**
305
+     * @param array $data
306
+     * @return Mount
307
+     */
308
+    protected function mountShare($data) {
309
+        $mount = $this->getMount($data);
310
+        $this->mountManager->addMount($mount);
311
+        return $mount;
312
+    }
313
+
314
+    /**
315
+     * @return \OC\Files\Mount\Manager
316
+     */
317
+    public function getMountManager() {
318
+        return $this->mountManager;
319
+    }
320
+
321
+    /**
322
+     * @param string $source
323
+     * @param string $target
324
+     * @return bool
325
+     */
326
+    public function setMountPoint($source, $target) {
327
+        $source = $this->stripPath($source);
328
+        $target = $this->stripPath($target);
329
+        $sourceHash = md5($source);
330
+        $targetHash = md5($target);
331
+
332
+        $query = $this->connection->prepare('
333 333
 			UPDATE `*PREFIX*share_external`
334 334
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
335 335
 			WHERE `mountpoint_hash` = ?
336 336
 			AND `user` = ?
337 337
 		');
338
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
338
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
339 339
 
340
-		return $result;
341
-	}
340
+        return $result;
341
+    }
342 342
 
343
-	public function removeShare($mountPoint) {
343
+    public function removeShare($mountPoint) {
344 344
 
345
-		$mountPointObj = $this->mountManager->find($mountPoint);
346
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
345
+        $mountPointObj = $this->mountManager->find($mountPoint);
346
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
347 347
 
348
-		$mountPoint = $this->stripPath($mountPoint);
349
-		$hash = md5($mountPoint);
348
+        $mountPoint = $this->stripPath($mountPoint);
349
+        $hash = md5($mountPoint);
350 350
 
351
-		$getShare = $this->connection->prepare('
351
+        $getShare = $this->connection->prepare('
352 352
 			SELECT `remote`, `share_token`, `remote_id`
353 353
 			FROM  `*PREFIX*share_external`
354 354
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
355
-		$result = $getShare->execute(array($hash, $this->uid));
355
+        $result = $getShare->execute(array($hash, $this->uid));
356 356
 
357
-		if ($result) {
358
-			$share = $getShare->fetch();
359
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
360
-		}
361
-		$getShare->closeCursor();
357
+        if ($result) {
358
+            $share = $getShare->fetch();
359
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
360
+        }
361
+        $getShare->closeCursor();
362 362
 
363
-		$query = $this->connection->prepare('
363
+        $query = $this->connection->prepare('
364 364
 			DELETE FROM `*PREFIX*share_external`
365 365
 			WHERE `mountpoint_hash` = ?
366 366
 			AND `user` = ?
367 367
 		');
368
-		$result = (bool)$query->execute(array($hash, $this->uid));
369
-
370
-		if($result) {
371
-			$this->removeReShares($id);
372
-		}
373
-
374
-		return $result;
375
-	}
376
-
377
-	/**
378
-	 * remove re-shares from share table and mapping in the federated_reshares table
379
-	 * 
380
-	 * @param $mountPointId
381
-	 */
382
-	protected function removeReShares($mountPointId) {
383
-		$selectQuery = $this->connection->getQueryBuilder();
384
-		$query = $this->connection->getQueryBuilder();
385
-		$selectQuery->select('id')->from('share')
386
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
387
-		$select = $selectQuery->getSQL();
388
-
389
-
390
-		$query->delete('federated_reshares')
391
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
392
-		$query->execute();
393
-
394
-		$deleteReShares = $this->connection->getQueryBuilder();
395
-		$deleteReShares->delete('share')
396
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
397
-		$deleteReShares->execute();
398
-	}
399
-
400
-	/**
401
-	 * remove all shares for user $uid if the user was deleted
402
-	 *
403
-	 * @param string $uid
404
-	 * @return bool
405
-	 */
406
-	public function removeUserShares($uid) {
407
-		$getShare = $this->connection->prepare('
368
+        $result = (bool)$query->execute(array($hash, $this->uid));
369
+
370
+        if($result) {
371
+            $this->removeReShares($id);
372
+        }
373
+
374
+        return $result;
375
+    }
376
+
377
+    /**
378
+     * remove re-shares from share table and mapping in the federated_reshares table
379
+     * 
380
+     * @param $mountPointId
381
+     */
382
+    protected function removeReShares($mountPointId) {
383
+        $selectQuery = $this->connection->getQueryBuilder();
384
+        $query = $this->connection->getQueryBuilder();
385
+        $selectQuery->select('id')->from('share')
386
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
387
+        $select = $selectQuery->getSQL();
388
+
389
+
390
+        $query->delete('federated_reshares')
391
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
392
+        $query->execute();
393
+
394
+        $deleteReShares = $this->connection->getQueryBuilder();
395
+        $deleteReShares->delete('share')
396
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
397
+        $deleteReShares->execute();
398
+    }
399
+
400
+    /**
401
+     * remove all shares for user $uid if the user was deleted
402
+     *
403
+     * @param string $uid
404
+     * @return bool
405
+     */
406
+    public function removeUserShares($uid) {
407
+        $getShare = $this->connection->prepare('
408 408
 			SELECT `remote`, `share_token`, `remote_id`
409 409
 			FROM  `*PREFIX*share_external`
410 410
 			WHERE `user` = ?');
411
-		$result = $getShare->execute(array($uid));
411
+        $result = $getShare->execute(array($uid));
412 412
 
413
-		if ($result) {
414
-			$shares = $getShare->fetchAll();
415
-			foreach($shares as $share) {
416
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
417
-			}
418
-		}
413
+        if ($result) {
414
+            $shares = $getShare->fetchAll();
415
+            foreach($shares as $share) {
416
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
417
+            }
418
+        }
419 419
 
420
-		$query = $this->connection->prepare('
420
+        $query = $this->connection->prepare('
421 421
 			DELETE FROM `*PREFIX*share_external`
422 422
 			WHERE `user` = ?
423 423
 		');
424
-		return (bool)$query->execute(array($uid));
425
-	}
426
-
427
-	/**
428
-	 * return a list of shares which are not yet accepted by the user
429
-	 *
430
-	 * @return array list of open server-to-server shares
431
-	 */
432
-	public function getOpenShares() {
433
-		return $this->getShares(false);
434
-	}
435
-
436
-	/**
437
-	 * return a list of shares which are accepted by the user
438
-	 *
439
-	 * @return array list of accepted server-to-server shares
440
-	 */
441
-	public function getAcceptedShares() {
442
-		return $this->getShares(true);
443
-	}
444
-
445
-	/**
446
-	 * return a list of shares for the user
447
-	 *
448
-	 * @param bool|null $accepted True for accepted only,
449
-	 *                            false for not accepted,
450
-	 *                            null for all shares of the user
451
-	 * @return array list of open server-to-server shares
452
-	 */
453
-	private function getShares($accepted) {
454
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
424
+        return (bool)$query->execute(array($uid));
425
+    }
426
+
427
+    /**
428
+     * return a list of shares which are not yet accepted by the user
429
+     *
430
+     * @return array list of open server-to-server shares
431
+     */
432
+    public function getOpenShares() {
433
+        return $this->getShares(false);
434
+    }
435
+
436
+    /**
437
+     * return a list of shares which are accepted by the user
438
+     *
439
+     * @return array list of accepted server-to-server shares
440
+     */
441
+    public function getAcceptedShares() {
442
+        return $this->getShares(true);
443
+    }
444
+
445
+    /**
446
+     * return a list of shares for the user
447
+     *
448
+     * @param bool|null $accepted True for accepted only,
449
+     *                            false for not accepted,
450
+     *                            null for all shares of the user
451
+     * @return array list of open server-to-server shares
452
+     */
453
+    private function getShares($accepted) {
454
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
455 455
 		          FROM `*PREFIX*share_external` 
456 456
 				  WHERE `user` = ?';
457
-		$parameters = [$this->uid];
458
-		if (!is_null($accepted)) {
459
-			$query .= ' AND `accepted` = ?';
460
-			$parameters[] = (int) $accepted;
461
-		}
462
-		$query .= ' ORDER BY `id` ASC';
463
-
464
-		$shares = $this->connection->prepare($query);
465
-		$result = $shares->execute($parameters);
466
-
467
-		return $result ? $shares->fetchAll() : [];
468
-	}
457
+        $parameters = [$this->uid];
458
+        if (!is_null($accepted)) {
459
+            $query .= ' AND `accepted` = ?';
460
+            $parameters[] = (int) $accepted;
461
+        }
462
+        $query .= ' ORDER BY `id` ASC';
463
+
464
+        $shares = $this->connection->prepare($query);
465
+        $result = $shares->execute($parameters);
466
+
467
+        return $result ? $shares->fetchAll() : [];
468
+    }
469 469
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Mount.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -29,43 +29,43 @@
 block discarded – undo
29 29
 
30 30
 class Mount extends MountPoint implements MoveableMount {
31 31
 
32
-	/**
33
-	 * @var \OCA\Files_Sharing\External\Manager
34
-	 */
35
-	protected $manager;
32
+    /**
33
+     * @var \OCA\Files_Sharing\External\Manager
34
+     */
35
+    protected $manager;
36 36
 
37
-	/**
38
-	 * @param string|\OC\Files\Storage\Storage $storage
39
-	 * @param string $mountpoint
40
-	 * @param array $options
41
-	 * @param \OCA\Files_Sharing\External\Manager $manager
42
-	 * @param \OC\Files\Storage\StorageFactory $loader
43
-	 */
44
-	public function __construct($storage, $mountpoint, $options, $manager, $loader = null) {
45
-		parent::__construct($storage, $mountpoint, $options, $loader);
46
-		$this->manager = $manager;
47
-	}
37
+    /**
38
+     * @param string|\OC\Files\Storage\Storage $storage
39
+     * @param string $mountpoint
40
+     * @param array $options
41
+     * @param \OCA\Files_Sharing\External\Manager $manager
42
+     * @param \OC\Files\Storage\StorageFactory $loader
43
+     */
44
+    public function __construct($storage, $mountpoint, $options, $manager, $loader = null) {
45
+        parent::__construct($storage, $mountpoint, $options, $loader);
46
+        $this->manager = $manager;
47
+    }
48 48
 
49
-	/**
50
-	 * Move the mount point to $target
51
-	 *
52
-	 * @param string $target the target mount point
53
-	 * @return bool
54
-	 */
55
-	public function moveMount($target) {
56
-		$result = $this->manager->setMountPoint($this->mountPoint, $target);
57
-		$this->setMountPoint($target);
49
+    /**
50
+     * Move the mount point to $target
51
+     *
52
+     * @param string $target the target mount point
53
+     * @return bool
54
+     */
55
+    public function moveMount($target) {
56
+        $result = $this->manager->setMountPoint($this->mountPoint, $target);
57
+        $this->setMountPoint($target);
58 58
 
59
-		return $result;
60
-	}
59
+        return $result;
60
+    }
61 61
 
62
-	/**
63
-	 * Remove the mount points
64
-	 *
65
-	 * @return mixed
66
-	 * @return bool
67
-	 */
68
-	public function removeMount() {
69
-		return $this->manager->removeShare($this->mountPoint);
70
-	}
62
+    /**
63
+     * Remove the mount points
64
+     *
65
+     * @return mixed
66
+     * @return bool
67
+     */
68
+    public function removeMount() {
69
+        return $this->manager->removeShare($this->mountPoint);
70
+    }
71 71
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Updater.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -27,81 +27,81 @@
 block discarded – undo
27 27
 
28 28
 class Updater {
29 29
 
30
-	/**
31
-	 * @param array $params
32
-	 */
33
-	static public function renameHook($params) {
34
-		self::renameChildren($params['oldpath'], $params['newpath']);
35
-		self::moveShareToShare($params['newpath']);
36
-	}
37
-
38
-	/**
39
-	 * Fix for https://github.com/owncloud/core/issues/20769
40
-	 *
41
-	 * The owner is allowed to move their files (if they are shared) into a receiving folder
42
-	 * In this case we need to update the parent of the moved share. Since they are
43
-	 * effectively handing over ownership of the file the rest of the code needs to know
44
-	 * they need to build up the reshare tree.
45
-	 *
46
-	 * @param string $path
47
-	 */
48
-	static private function moveShareToShare($path) {
49
-		$userFolder = \OC::$server->getUserFolder();
50
-
51
-		// If the user folder can't be constructed (e.g. link share) just return.
52
-		if ($userFolder === null) {
53
-			return;
54
-		}
55
-
56
-		$src = $userFolder->get($path);
57
-
58
-		$shareManager = \OC::$server->getShareManager();
59
-
60
-		$shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_USER, $src, false, -1);
61
-		$shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_GROUP, $src, false, -1));
62
-
63
-		// If the path we move is not a share we don't care
64
-		if (empty($shares)) {
65
-			return;
66
-		}
67
-
68
-		// Check if the destination is inside a share
69
-		$mountManager = \OC::$server->getMountManager();
70
-		$dstMount = $mountManager->find($src->getPath());
71
-		if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
72
-			return;
73
-		}
74
-
75
-		$newOwner = $dstMount->getShare()->getShareOwner();
76
-
77
-		//Ownership is moved over
78
-		foreach ($shares as $share) {
79
-			/** @var \OCP\Share\IShare $share */
80
-			$share->setShareOwner($newOwner);
81
-			$shareManager->updateShare($share);
82
-		}
83
-	}
84
-
85
-	/**
86
-	 * rename mount point from the children if the parent was renamed
87
-	 *
88
-	 * @param string $oldPath old path relative to data/user/files
89
-	 * @param string $newPath new path relative to data/user/files
90
-	 */
91
-	static private function renameChildren($oldPath, $newPath) {
92
-
93
-		$absNewPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath);
94
-		$absOldPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath);
95
-
96
-		$mountManager = \OC\Files\Filesystem::getMountManager();
97
-		$mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath);
98
-		foreach ($mountedShares as $mount) {
99
-			if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
100
-				$mountPoint = $mount->getMountPoint();
101
-				$target = str_replace($absOldPath, $absNewPath, $mountPoint);
102
-				$mount->moveMount($target);
103
-			}
104
-		}
105
-	}
30
+    /**
31
+     * @param array $params
32
+     */
33
+    static public function renameHook($params) {
34
+        self::renameChildren($params['oldpath'], $params['newpath']);
35
+        self::moveShareToShare($params['newpath']);
36
+    }
37
+
38
+    /**
39
+     * Fix for https://github.com/owncloud/core/issues/20769
40
+     *
41
+     * The owner is allowed to move their files (if they are shared) into a receiving folder
42
+     * In this case we need to update the parent of the moved share. Since they are
43
+     * effectively handing over ownership of the file the rest of the code needs to know
44
+     * they need to build up the reshare tree.
45
+     *
46
+     * @param string $path
47
+     */
48
+    static private function moveShareToShare($path) {
49
+        $userFolder = \OC::$server->getUserFolder();
50
+
51
+        // If the user folder can't be constructed (e.g. link share) just return.
52
+        if ($userFolder === null) {
53
+            return;
54
+        }
55
+
56
+        $src = $userFolder->get($path);
57
+
58
+        $shareManager = \OC::$server->getShareManager();
59
+
60
+        $shares = $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_USER, $src, false, -1);
61
+        $shares = array_merge($shares, $shareManager->getSharesBy($userFolder->getOwner()->getUID(), \OCP\Share::SHARE_TYPE_GROUP, $src, false, -1));
62
+
63
+        // If the path we move is not a share we don't care
64
+        if (empty($shares)) {
65
+            return;
66
+        }
67
+
68
+        // Check if the destination is inside a share
69
+        $mountManager = \OC::$server->getMountManager();
70
+        $dstMount = $mountManager->find($src->getPath());
71
+        if (!($dstMount instanceof \OCA\Files_Sharing\SharedMount)) {
72
+            return;
73
+        }
74
+
75
+        $newOwner = $dstMount->getShare()->getShareOwner();
76
+
77
+        //Ownership is moved over
78
+        foreach ($shares as $share) {
79
+            /** @var \OCP\Share\IShare $share */
80
+            $share->setShareOwner($newOwner);
81
+            $shareManager->updateShare($share);
82
+        }
83
+    }
84
+
85
+    /**
86
+     * rename mount point from the children if the parent was renamed
87
+     *
88
+     * @param string $oldPath old path relative to data/user/files
89
+     * @param string $newPath new path relative to data/user/files
90
+     */
91
+    static private function renameChildren($oldPath, $newPath) {
92
+
93
+        $absNewPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $newPath);
94
+        $absOldPath =  \OC\Files\Filesystem::normalizePath('/' . \OCP\User::getUser() . '/files/' . $oldPath);
95
+
96
+        $mountManager = \OC\Files\Filesystem::getMountManager();
97
+        $mountedShares = $mountManager->findIn('/' . \OCP\User::getUser() . '/files/' . $oldPath);
98
+        foreach ($mountedShares as $mount) {
99
+            if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
100
+                $mountPoint = $mount->getMountPoint();
101
+                $target = str_replace($absOldPath, $absNewPath, $mountPoint);
102
+                $mount->moveMount($target);
103
+            }
104
+        }
105
+    }
106 106
 
107 107
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Helper.php 1 patch
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
 
37 37
 class Helper {
38 38
 
39
-	public static function registerHooks() {
40
-		\OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
-		\OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
-
43
-		\OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
-	}
45
-
46
-	/**
47
-	 * Sets up the filesystem and user for public sharing
48
-	 * @param string $token string share token
49
-	 * @param string $relativePath optional path relative to the share
50
-	 * @param string $password optional password
51
-	 * @return array
52
-	 */
53
-	public static function setupFromToken($token, $relativePath = null, $password = null) {
54
-		\OC_User::setIncognitoMode(true);
55
-
56
-		$shareManager = \OC::$server->getShareManager();
57
-
58
-		try {
59
-			$share = $shareManager->getShareByToken($token);
60
-		} catch (ShareNotFound $e) {
61
-			\OC_Response::setStatus(404);
62
-			\OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
-			exit;
64
-		}
65
-
66
-		\OCP\JSON::checkUserExists($share->getShareOwner());
67
-		\OC_Util::tearDownFS();
68
-		\OC_Util::setupFS($share->getShareOwner());
69
-
70
-
71
-		try {
72
-			$path = Filesystem::getPath($share->getNodeId());
73
-		} catch (NotFoundException $e) {
74
-			\OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
-			\OC_Response::setStatus(404);
76
-			\OCP\JSON::error(array('success' => false));
77
-			exit();
78
-		}
79
-
80
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
-			if (!self::authenticate($share, $password)) {
82
-				\OC_Response::setStatus(403);
83
-				\OCP\JSON::error(array('success' => false));
84
-				exit();
85
-			}
86
-		}
87
-
88
-		$basePath = $path;
89
-
90
-		if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
-			$path .= Filesystem::normalizePath($relativePath);
92
-		}
93
-
94
-		return array(
95
-			'share' => $share,
96
-			'basePath' => $basePath,
97
-			'realPath' => $path
98
-		);
99
-	}
100
-
101
-	/**
102
-	 * Authenticate link item with the given password
103
-	 * or with the session if no password was given.
104
-	 * @param \OCP\Share\IShare $share
105
-	 * @param string $password optional password
106
-	 *
107
-	 * @return boolean true if authorized, false otherwise
108
-	 */
109
-	public static function authenticate($share, $password = null) {
110
-		$shareManager = \OC::$server->getShareManager();
111
-
112
-		if ($password !== null) {
113
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-				if ($shareManager->checkPassword($share, $password)) {
115
-					\OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
-					return true;
117
-				}
118
-			}
119
-		} else {
120
-			// not authenticated ?
121
-			if (\OC::$server->getSession()->exists('public_link_authenticated')
122
-				&& \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
-				return true;
124
-			}
125
-		}
126
-		return false;
127
-	}
128
-
129
-	public static function getSharesFromItem($target) {
130
-		$result = array();
131
-		$owner = Filesystem::getOwner($target);
132
-		Filesystem::initMountPoints($owner);
133
-		$info = Filesystem::getFileInfo($target);
134
-		$ownerView = new View('/'.$owner.'/files');
135
-		if ( $owner != User::getUser() ) {
136
-			$path = $ownerView->getPath($info['fileid']);
137
-		} else {
138
-			$path = $target;
139
-		}
140
-
141
-
142
-		$ids = array();
143
-		while ($path !== dirname($path)) {
144
-			$info = $ownerView->getFileInfo($path);
145
-			if ($info instanceof \OC\Files\FileInfo) {
146
-				$ids[] = $info['fileid'];
147
-			} else {
148
-				\OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
-			}
150
-			$path = dirname($path);
151
-		}
152
-
153
-		if (!empty($ids)) {
154
-
155
-			$idList = array_chunk($ids, 99, true);
156
-
157
-			foreach ($idList as $subList) {
158
-				$statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
-				$query = \OCP\DB::prepare($statement);
160
-				$r = $query->execute();
161
-				$result = array_merge($result, $r->fetchAll());
162
-			}
163
-		}
164
-
165
-		return $result;
166
-	}
167
-
168
-	/**
169
-	 * get the UID of the owner of the file and the path to the file relative to
170
-	 * owners files folder
171
-	 *
172
-	 * @param $filename
173
-	 * @return array
174
-	 * @throws \OC\User\NoUserException
175
-	 */
176
-	public static function getUidAndFilename($filename) {
177
-		$uid = Filesystem::getOwner($filename);
178
-		$userManager = \OC::$server->getUserManager();
179
-		// if the user with the UID doesn't exists, e.g. because the UID points
180
-		// to a remote user with a federated cloud ID we use the current logged-in
181
-		// user. We need a valid local user to create the share
182
-		if (!$userManager->userExists($uid)) {
183
-			$uid = User::getUser();
184
-		}
185
-		Filesystem::initMountPoints($uid);
186
-		if ( $uid != User::getUser() ) {
187
-			$info = Filesystem::getFileInfo($filename);
188
-			$ownerView = new View('/'.$uid.'/files');
189
-			try {
190
-				$filename = $ownerView->getPath($info['fileid']);
191
-			} catch (NotFoundException $e) {
192
-				$filename = null;
193
-			}
194
-		}
195
-		return [$uid, $filename];
196
-	}
197
-
198
-	/**
199
-	 * Format a path to be relative to the /user/files/ directory
200
-	 * @param string $path the absolute path
201
-	 * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
-	 */
203
-	public static function stripUserFilesPath($path) {
204
-		$trimmed = ltrim($path, '/');
205
-		$split = explode('/', $trimmed);
206
-
207
-		// it is not a file relative to data/user/files
208
-		if (count($split) < 3 || $split[1] !== 'files') {
209
-			return false;
210
-		}
211
-
212
-		$sliced = array_slice($split, 2);
213
-		$relPath = implode('/', $sliced);
214
-
215
-		return $relPath;
216
-	}
217
-
218
-	/**
219
-	 * check if file name already exists and generate unique target
220
-	 *
221
-	 * @param string $path
222
-	 * @param array $excludeList
223
-	 * @param View $view
224
-	 * @return string $path
225
-	 */
226
-	public static function generateUniqueTarget($path, $excludeList, $view) {
227
-		$pathinfo = pathinfo($path);
228
-		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
-		$name = $pathinfo['filename'];
230
-		$dir = $pathinfo['dirname'];
231
-		$i = 2;
232
-		while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
-			$i++;
235
-		}
236
-
237
-		return $path;
238
-	}
239
-
240
-	/**
241
-	 * get default share folder
242
-	 *
243
-	 * @param \OC\Files\View
244
-	 * @return string
245
-	 */
246
-	public static function getShareFolder($view = null) {
247
-		if ($view === null) {
248
-			$view = Filesystem::getView();
249
-		}
250
-		$shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
-		$shareFolder = Filesystem::normalizePath($shareFolder);
252
-
253
-		if (!$view->file_exists($shareFolder)) {
254
-			$dir = '';
255
-			$subdirs = explode('/', $shareFolder);
256
-			foreach ($subdirs as $subdir) {
257
-				$dir = $dir . '/' . $subdir;
258
-				if (!$view->is_dir($dir)) {
259
-					$view->mkdir($dir);
260
-				}
261
-			}
262
-		}
263
-
264
-		return $shareFolder;
265
-
266
-	}
267
-
268
-	/**
269
-	 * set default share folder
270
-	 *
271
-	 * @param string $shareFolder
272
-	 */
273
-	public static function setShareFolder($shareFolder) {
274
-		\OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
-	}
39
+    public static function registerHooks() {
40
+        \OCP\Util::connectHook('OC_Filesystem', 'post_rename', '\OCA\Files_Sharing\Updater', 'renameHook');
41
+        \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
42
+
43
+        \OCP\Util::connectHook('OC_User', 'post_deleteUser', '\OCA\Files_Sharing\Hooks', 'deleteUser');
44
+    }
45
+
46
+    /**
47
+     * Sets up the filesystem and user for public sharing
48
+     * @param string $token string share token
49
+     * @param string $relativePath optional path relative to the share
50
+     * @param string $password optional password
51
+     * @return array
52
+     */
53
+    public static function setupFromToken($token, $relativePath = null, $password = null) {
54
+        \OC_User::setIncognitoMode(true);
55
+
56
+        $shareManager = \OC::$server->getShareManager();
57
+
58
+        try {
59
+            $share = $shareManager->getShareByToken($token);
60
+        } catch (ShareNotFound $e) {
61
+            \OC_Response::setStatus(404);
62
+            \OCP\Util::writeLog('core-preview', 'Passed token parameter is not valid', \OCP\Util::DEBUG);
63
+            exit;
64
+        }
65
+
66
+        \OCP\JSON::checkUserExists($share->getShareOwner());
67
+        \OC_Util::tearDownFS();
68
+        \OC_Util::setupFS($share->getShareOwner());
69
+
70
+
71
+        try {
72
+            $path = Filesystem::getPath($share->getNodeId());
73
+        } catch (NotFoundException $e) {
74
+            \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
75
+            \OC_Response::setStatus(404);
76
+            \OCP\JSON::error(array('success' => false));
77
+            exit();
78
+        }
79
+
80
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && $share->getPassword() !== null) {
81
+            if (!self::authenticate($share, $password)) {
82
+                \OC_Response::setStatus(403);
83
+                \OCP\JSON::error(array('success' => false));
84
+                exit();
85
+            }
86
+        }
87
+
88
+        $basePath = $path;
89
+
90
+        if ($relativePath !== null && Filesystem::isReadable($basePath . $relativePath)) {
91
+            $path .= Filesystem::normalizePath($relativePath);
92
+        }
93
+
94
+        return array(
95
+            'share' => $share,
96
+            'basePath' => $basePath,
97
+            'realPath' => $path
98
+        );
99
+    }
100
+
101
+    /**
102
+     * Authenticate link item with the given password
103
+     * or with the session if no password was given.
104
+     * @param \OCP\Share\IShare $share
105
+     * @param string $password optional password
106
+     *
107
+     * @return boolean true if authorized, false otherwise
108
+     */
109
+    public static function authenticate($share, $password = null) {
110
+        $shareManager = \OC::$server->getShareManager();
111
+
112
+        if ($password !== null) {
113
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+                if ($shareManager->checkPassword($share, $password)) {
115
+                    \OC::$server->getSession()->set('public_link_authenticated', (string)$share->getId());
116
+                    return true;
117
+                }
118
+            }
119
+        } else {
120
+            // not authenticated ?
121
+            if (\OC::$server->getSession()->exists('public_link_authenticated')
122
+                && \OC::$server->getSession()->get('public_link_authenticated') !== (string)$share->getId()) {
123
+                return true;
124
+            }
125
+        }
126
+        return false;
127
+    }
128
+
129
+    public static function getSharesFromItem($target) {
130
+        $result = array();
131
+        $owner = Filesystem::getOwner($target);
132
+        Filesystem::initMountPoints($owner);
133
+        $info = Filesystem::getFileInfo($target);
134
+        $ownerView = new View('/'.$owner.'/files');
135
+        if ( $owner != User::getUser() ) {
136
+            $path = $ownerView->getPath($info['fileid']);
137
+        } else {
138
+            $path = $target;
139
+        }
140
+
141
+
142
+        $ids = array();
143
+        while ($path !== dirname($path)) {
144
+            $info = $ownerView->getFileInfo($path);
145
+            if ($info instanceof \OC\Files\FileInfo) {
146
+                $ids[] = $info['fileid'];
147
+            } else {
148
+                \OCP\Util::writeLog('sharing', 'No fileinfo available for: ' . $path, \OCP\Util::WARN);
149
+            }
150
+            $path = dirname($path);
151
+        }
152
+
153
+        if (!empty($ids)) {
154
+
155
+            $idList = array_chunk($ids, 99, true);
156
+
157
+            foreach ($idList as $subList) {
158
+                $statement = "SELECT `share_with`, `share_type`, `file_target` FROM `*PREFIX*share` WHERE `file_source` IN (" . implode(',', $subList) . ") AND `share_type` IN (0, 1, 2)";
159
+                $query = \OCP\DB::prepare($statement);
160
+                $r = $query->execute();
161
+                $result = array_merge($result, $r->fetchAll());
162
+            }
163
+        }
164
+
165
+        return $result;
166
+    }
167
+
168
+    /**
169
+     * get the UID of the owner of the file and the path to the file relative to
170
+     * owners files folder
171
+     *
172
+     * @param $filename
173
+     * @return array
174
+     * @throws \OC\User\NoUserException
175
+     */
176
+    public static function getUidAndFilename($filename) {
177
+        $uid = Filesystem::getOwner($filename);
178
+        $userManager = \OC::$server->getUserManager();
179
+        // if the user with the UID doesn't exists, e.g. because the UID points
180
+        // to a remote user with a federated cloud ID we use the current logged-in
181
+        // user. We need a valid local user to create the share
182
+        if (!$userManager->userExists($uid)) {
183
+            $uid = User::getUser();
184
+        }
185
+        Filesystem::initMountPoints($uid);
186
+        if ( $uid != User::getUser() ) {
187
+            $info = Filesystem::getFileInfo($filename);
188
+            $ownerView = new View('/'.$uid.'/files');
189
+            try {
190
+                $filename = $ownerView->getPath($info['fileid']);
191
+            } catch (NotFoundException $e) {
192
+                $filename = null;
193
+            }
194
+        }
195
+        return [$uid, $filename];
196
+    }
197
+
198
+    /**
199
+     * Format a path to be relative to the /user/files/ directory
200
+     * @param string $path the absolute path
201
+     * @return string e.g. turns '/admin/files/test.txt' into 'test.txt'
202
+     */
203
+    public static function stripUserFilesPath($path) {
204
+        $trimmed = ltrim($path, '/');
205
+        $split = explode('/', $trimmed);
206
+
207
+        // it is not a file relative to data/user/files
208
+        if (count($split) < 3 || $split[1] !== 'files') {
209
+            return false;
210
+        }
211
+
212
+        $sliced = array_slice($split, 2);
213
+        $relPath = implode('/', $sliced);
214
+
215
+        return $relPath;
216
+    }
217
+
218
+    /**
219
+     * check if file name already exists and generate unique target
220
+     *
221
+     * @param string $path
222
+     * @param array $excludeList
223
+     * @param View $view
224
+     * @return string $path
225
+     */
226
+    public static function generateUniqueTarget($path, $excludeList, $view) {
227
+        $pathinfo = pathinfo($path);
228
+        $ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
229
+        $name = $pathinfo['filename'];
230
+        $dir = $pathinfo['dirname'];
231
+        $i = 2;
232
+        while ($view->file_exists($path) || in_array($path, $excludeList)) {
233
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' ('.$i.')' . $ext);
234
+            $i++;
235
+        }
236
+
237
+        return $path;
238
+    }
239
+
240
+    /**
241
+     * get default share folder
242
+     *
243
+     * @param \OC\Files\View
244
+     * @return string
245
+     */
246
+    public static function getShareFolder($view = null) {
247
+        if ($view === null) {
248
+            $view = Filesystem::getView();
249
+        }
250
+        $shareFolder = \OC::$server->getConfig()->getSystemValue('share_folder', '/');
251
+        $shareFolder = Filesystem::normalizePath($shareFolder);
252
+
253
+        if (!$view->file_exists($shareFolder)) {
254
+            $dir = '';
255
+            $subdirs = explode('/', $shareFolder);
256
+            foreach ($subdirs as $subdir) {
257
+                $dir = $dir . '/' . $subdir;
258
+                if (!$view->is_dir($dir)) {
259
+                    $view->mkdir($dir);
260
+                }
261
+            }
262
+        }
263
+
264
+        return $shareFolder;
265
+
266
+    }
267
+
268
+    /**
269
+     * set default share folder
270
+     *
271
+     * @param string $shareFolder
272
+     */
273
+    public static function setShareFolder($shareFolder) {
274
+        \OC::$server->getConfig()->setSystemValue('share_folder', $shareFolder);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.