Completed
Pull Request — master (#9895)
by Björn
64:23 queued 40:48
created
apps/files_sharing/lib/AppInfo/Application.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -45,136 +45,136 @@
 block discarded – undo
45 45
 use OCA\Files_Sharing\External\Manager;
46 46
 
47 47
 class Application extends App {
48
-	public function __construct(array $urlParams = array()) {
49
-		parent::__construct('files_sharing', $urlParams);
48
+    public function __construct(array $urlParams = array()) {
49
+        parent::__construct('files_sharing', $urlParams);
50 50
 
51
-		$container = $this->getContainer();
52
-		/** @var IServerContainer $server */
53
-		$server = $container->getServer();
51
+        $container = $this->getContainer();
52
+        /** @var IServerContainer $server */
53
+        $server = $container->getServer();
54 54
 
55
-		/**
56
-		 * Controllers
57
-		 */
58
-		$container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
59
-			$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
60
-			return new ShareController(
61
-				$c->query('AppName'),
62
-				$c->query('Request'),
63
-				$server->getConfig(),
64
-				$server->getURLGenerator(),
65
-				$server->getUserManager(),
66
-				$server->getLogger(),
67
-				$server->getActivityManager(),
68
-				$server->getShareManager(),
69
-				$server->getSession(),
70
-				$server->getPreviewManager(),
71
-				$server->getRootFolder(),
72
-				$federatedSharingApp->getFederatedShareProvider(),
73
-				$server->getEventDispatcher(),
74
-				$server->getL10N($c->query('AppName')),
75
-				$server->query(Defaults::class)
76
-			);
77
-		});
78
-		$container->registerService('ExternalSharesController', function (SimpleContainer $c) {
79
-			return new ExternalSharesController(
80
-				$c->query('AppName'),
81
-				$c->query('Request'),
82
-				$c->query('ExternalManager'),
83
-				$c->query('HttpClientService')
84
-			);
85
-		});
55
+        /**
56
+         * Controllers
57
+         */
58
+        $container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
59
+            $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
60
+            return new ShareController(
61
+                $c->query('AppName'),
62
+                $c->query('Request'),
63
+                $server->getConfig(),
64
+                $server->getURLGenerator(),
65
+                $server->getUserManager(),
66
+                $server->getLogger(),
67
+                $server->getActivityManager(),
68
+                $server->getShareManager(),
69
+                $server->getSession(),
70
+                $server->getPreviewManager(),
71
+                $server->getRootFolder(),
72
+                $federatedSharingApp->getFederatedShareProvider(),
73
+                $server->getEventDispatcher(),
74
+                $server->getL10N($c->query('AppName')),
75
+                $server->query(Defaults::class)
76
+            );
77
+        });
78
+        $container->registerService('ExternalSharesController', function (SimpleContainer $c) {
79
+            return new ExternalSharesController(
80
+                $c->query('AppName'),
81
+                $c->query('Request'),
82
+                $c->query('ExternalManager'),
83
+                $c->query('HttpClientService')
84
+            );
85
+        });
86 86
 
87
-		/**
88
-		 * Core class wrappers
89
-		 */
90
-		$container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
91
-			return $server->getHTTPClientService();
92
-		});
93
-		$container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
94
-			return $server->getCloudIdManager();
95
-		});
96
-		$container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
97
-			$user = $server->getUserSession()->getUser();
98
-			$uid = $user ? $user->getUID() : null;
99
-			return new \OCA\Files_Sharing\External\Manager(
100
-				$server->getDatabaseConnection(),
101
-				\OC\Files\Filesystem::getMountManager(),
102
-				\OC\Files\Filesystem::getLoader(),
103
-				$server->getHTTPClientService(),
104
-				$server->getNotificationManager(),
105
-				$server->query(\OCP\OCS\IDiscoveryService::class),
106
-				$server->getCloudFederationProviderManager(),
107
-				$server->getCloudFederationFactory(),
108
-				$uid
109
-			);
110
-		});
111
-		$container->registerAlias(Manager::class, 'ExternalManager');
87
+        /**
88
+         * Core class wrappers
89
+         */
90
+        $container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
91
+            return $server->getHTTPClientService();
92
+        });
93
+        $container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
94
+            return $server->getCloudIdManager();
95
+        });
96
+        $container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
97
+            $user = $server->getUserSession()->getUser();
98
+            $uid = $user ? $user->getUID() : null;
99
+            return new \OCA\Files_Sharing\External\Manager(
100
+                $server->getDatabaseConnection(),
101
+                \OC\Files\Filesystem::getMountManager(),
102
+                \OC\Files\Filesystem::getLoader(),
103
+                $server->getHTTPClientService(),
104
+                $server->getNotificationManager(),
105
+                $server->query(\OCP\OCS\IDiscoveryService::class),
106
+                $server->getCloudFederationProviderManager(),
107
+                $server->getCloudFederationFactory(),
108
+                $uid
109
+            );
110
+        });
111
+        $container->registerAlias(Manager::class, 'ExternalManager');
112 112
 
113
-		/**
114
-		 * Middleware
115
-		 */
116
-		$container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
117
-			return new SharingCheckMiddleware(
118
-				$c->query('AppName'),
119
-				$server->getConfig(),
120
-				$server->getAppManager(),
121
-				$c['ControllerMethodReflector'],
122
-				$server->getShareManager(),
123
-				$server->getRequest()
124
-			);
125
-		});
113
+        /**
114
+         * Middleware
115
+         */
116
+        $container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
117
+            return new SharingCheckMiddleware(
118
+                $c->query('AppName'),
119
+                $server->getConfig(),
120
+                $server->getAppManager(),
121
+                $c['ControllerMethodReflector'],
122
+                $server->getShareManager(),
123
+                $server->getRequest()
124
+            );
125
+        });
126 126
 
127
-		$container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
128
-			return new OCSShareAPIMiddleware(
129
-				$server->getShareManager(),
130
-				$server->getL10N($c->query('AppName'))
131
-			);
132
-		});
127
+        $container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
128
+            return new OCSShareAPIMiddleware(
129
+                $server->getShareManager(),
130
+                $server->getL10N($c->query('AppName'))
131
+            );
132
+        });
133 133
 
134
-		$container->registerService(ShareInfoMiddleware::class, function () use ($server) {
135
-			return new ShareInfoMiddleware(
136
-				$server->getShareManager()
137
-			);
138
-		});
134
+        $container->registerService(ShareInfoMiddleware::class, function () use ($server) {
135
+            return new ShareInfoMiddleware(
136
+                $server->getShareManager()
137
+            );
138
+        });
139 139
 
140
-		// Execute middlewares
141
-		$container->registerMiddleWare('SharingCheckMiddleware');
142
-		$container->registerMiddleWare('OCSShareAPIMiddleware');
143
-		$container->registerMiddleWare(ShareInfoMiddleware::class);
140
+        // Execute middlewares
141
+        $container->registerMiddleWare('SharingCheckMiddleware');
142
+        $container->registerMiddleWare('OCSShareAPIMiddleware');
143
+        $container->registerMiddleWare(ShareInfoMiddleware::class);
144 144
 
145
-		$container->registerService('MountProvider', function (IContainer $c) {
146
-			/** @var \OCP\IServerContainer $server */
147
-			$server = $c->query('ServerContainer');
148
-			return new MountProvider(
149
-				$server->getConfig(),
150
-				$server->getShareManager(),
151
-				$server->getLogger()
152
-			);
153
-		});
145
+        $container->registerService('MountProvider', function (IContainer $c) {
146
+            /** @var \OCP\IServerContainer $server */
147
+            $server = $c->query('ServerContainer');
148
+            return new MountProvider(
149
+                $server->getConfig(),
150
+                $server->getShareManager(),
151
+                $server->getLogger()
152
+            );
153
+        });
154 154
 
155
-		$container->registerService('ExternalMountProvider', function (IContainer $c) {
156
-			/** @var \OCP\IServerContainer $server */
157
-			$server = $c->query('ServerContainer');
158
-			return new \OCA\Files_Sharing\External\MountProvider(
159
-				$server->getDatabaseConnection(),
160
-				function() use ($c) {
161
-					return $c->query('ExternalManager');
162
-				},
163
-				$server->getCloudIdManager()
164
-			);
165
-		});
155
+        $container->registerService('ExternalMountProvider', function (IContainer $c) {
156
+            /** @var \OCP\IServerContainer $server */
157
+            $server = $c->query('ServerContainer');
158
+            return new \OCA\Files_Sharing\External\MountProvider(
159
+                $server->getDatabaseConnection(),
160
+                function() use ($c) {
161
+                    return $c->query('ExternalManager');
162
+                },
163
+                $server->getCloudIdManager()
164
+            );
165
+        });
166 166
 
167
-		/*
167
+        /*
168 168
 		 * Register capabilities
169 169
 		 */
170
-		$container->registerCapability(Capabilities::class);
171
-	}
170
+        $container->registerCapability(Capabilities::class);
171
+    }
172 172
 
173
-	public function registerMountProviders() {
174
-		/** @var \OCP\IServerContainer $server */
175
-		$server = $this->getContainer()->query('ServerContainer');
176
-		$mountProviderCollection = $server->getMountProviderCollection();
177
-		$mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
178
-		$mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
179
-	}
173
+    public function registerMountProviders() {
174
+        /** @var \OCP\IServerContainer $server */
175
+        $server = $this->getContainer()->query('ServerContainer');
176
+        $mountProviderCollection = $server->getMountProviderCollection();
177
+        $mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
178
+        $mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
179
+    }
180 180
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Hooks.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -32,33 +32,33 @@
 block discarded – undo
32 32
 
33 33
 class Hooks {
34 34
 
35
-	public static function deleteUser($params) {
36
-		$manager = new External\Manager(
37
-			\OC::$server->getDatabaseConnection(),
38
-			\OC\Files\Filesystem::getMountManager(),
39
-			\OC\Files\Filesystem::getLoader(),
40
-			\OC::$server->getHTTPClientService(),
41
-			\OC::$server->getNotificationManager(),
42
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
43
-			\OC::$server->getCloudFederationProviderManager(),
44
-			\OC::$server->getCloudFederationFactory(),
45
-			$params['uid']);
35
+    public static function deleteUser($params) {
36
+        $manager = new External\Manager(
37
+            \OC::$server->getDatabaseConnection(),
38
+            \OC\Files\Filesystem::getMountManager(),
39
+            \OC\Files\Filesystem::getLoader(),
40
+            \OC::$server->getHTTPClientService(),
41
+            \OC::$server->getNotificationManager(),
42
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
43
+            \OC::$server->getCloudFederationProviderManager(),
44
+            \OC::$server->getCloudFederationFactory(),
45
+            $params['uid']);
46 46
 
47
-		$manager->removeUserShares($params['uid']);
48
-	}
47
+        $manager->removeUserShares($params['uid']);
48
+    }
49 49
 
50
-	public static function unshareChildren($params) {
51
-		$path = Filesystem::getView()->getAbsolutePath($params['path']);
52
-		$view = new \OC\Files\View('/');
50
+    public static function unshareChildren($params) {
51
+        $path = Filesystem::getView()->getAbsolutePath($params['path']);
52
+        $view = new \OC\Files\View('/');
53 53
 
54
-		// find share mount points within $path and unmount them
55
-		$mountManager = \OC\Files\Filesystem::getMountManager();
56
-		$mountedShares = $mountManager->findIn($path);
57
-		foreach ($mountedShares as $mount) {
58
-			if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
59
-				$mountPoint = $mount->getMountPoint();
60
-				$view->unlink($mountPoint);
61
-			}
62
-		}
63
-	}
54
+        // find share mount points within $path and unmount them
55
+        $mountManager = \OC\Files\Filesystem::getMountManager();
56
+        $mountedShares = $mountManager->findIn($path);
57
+        foreach ($mountedShares as $mount) {
58
+            if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
59
+                $mountPoint = $mount->getMountPoint();
60
+                $view->unlink($mountPoint);
61
+            }
62
+        }
63
+    }
64 64
 }
Please login to merge, or discard this patch.
lib/public/Federation/Exceptions/ActionNotSupportedException.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
 	 */
32 32
 	public function __construct($action) {
33 33
 		$l = \OC::$server->getL10N('federation');
34
-		$message = 'Action "' . $action . '" not supported or implemented.';
34
+		$message = 'Action "'.$action.'" not supported or implemented.';
35 35
 		$hint = $l->t('Action "%s" not supported or implemented.', [$action]);
36 36
 		parent::__construct($message, $hint);
37 37
 	}
Please login to merge, or discard this patch.
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -32,17 +32,17 @@
 block discarded – undo
32 32
  */
33 33
 class ActionNotSupportedException extends HintException {
34 34
 
35
-	/**
36
-	 * ActionNotSupportedException constructor.
37
-	 *
38
-	 * @since 14.0.0
39
-	 *
40
-	 */
41
-	public function __construct($action) {
42
-		$l = \OC::$server->getL10N('federation');
43
-		$message = 'Action "' . $action . '" not supported or implemented.';
44
-		$hint = $l->t('Action "%s" not supported or implemented.', [$action]);
45
-		parent::__construct($message, $hint);
46
-	}
35
+    /**
36
+     * ActionNotSupportedException constructor.
37
+     *
38
+     * @since 14.0.0
39
+     *
40
+     */
41
+    public function __construct($action) {
42
+        $l = \OC::$server->getL10N('federation');
43
+        $message = 'Action "' . $action . '" not supported or implemented.';
44
+        $hint = $l->t('Action "%s" not supported or implemented.', [$action]);
45
+        parent::__construct($message, $hint);
46
+    }
47 47
 
48 48
 }
Please login to merge, or discard this patch.
lib/private/Federation/CloudFederationProviderManager.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 								IClientService $httpClientService,
72 72
 								ICloudIdManager $cloudIdManager,
73 73
 								ILogger $logger) {
74
-		$this->cloudFederationProvider= [];
74
+		$this->cloudFederationProvider = [];
75 75
 		$this->appManager = $appManager;
76 76
 		$this->httpClientService = $httpClientService;
77 77
 		$this->cloudIdManager = $cloudIdManager;
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 
141 141
 		$client = $this->httpClientService->newClient();
142 142
 		try {
143
-			$response = $client->post($ocmEndPoint . '/shares', [
143
+			$response = $client->post($ocmEndPoint.'/shares', [
144 144
 				'body' => $share->getShare(),
145 145
 				'timeout' => 10,
146 146
 				'connect_timeout' => 10,
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 
178 178
 		$client = $this->httpClientService->newClient();
179 179
 		try {
180
-			$response = $client->post($ocmEndPoint . '/notifications', [
180
+			$response = $client->post($ocmEndPoint.'/notifications', [
181 181
 				'body' => $notification->getMessage(),
182 182
 				'timeout' => 10,
183 183
 				'connect_timeout' => 10,
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 			}
188 188
 		} catch (\Exception $e) {
189 189
 			// log the error and return false
190
-			$this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
190
+			$this->logger->error('error while sending notification for federated share: '.$e->getMessage());
191 191
 		}
192 192
 
193 193
 		return false;
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 	protected function getOCMEndPoint($url) {
211 211
 		$client = $this->httpClientService->newClient();
212 212
 		try {
213
-			$response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
213
+			$response = $client->get($url.'/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
214 214
 		} catch (\Exception $e) {
215 215
 			return '';
216 216
 		}
Please login to merge, or discard this patch.
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -42,189 +42,189 @@
 block discarded – undo
42 42
  */
43 43
 class CloudFederationProviderManager implements ICloudFederationProviderManager {
44 44
 
45
-	/** @var array list of available cloud federation providers */
46
-	private $cloudFederationProvider;
47
-
48
-	/** @var IAppManager */
49
-	private $appManager;
50
-
51
-	/** @var IClientService */
52
-	private $httpClientService;
53
-
54
-	/** @var ICloudIdManager */
55
-	private $cloudIdManager;
56
-
57
-	/** @var ILogger */
58
-	private $logger;
59
-
60
-	private $supportedAPIVersion = '1.0-proposal1';
61
-
62
-	/**
63
-	 * CloudFederationProviderManager constructor.
64
-	 *
65
-	 * @param IAppManager $appManager
66
-	 * @param IClientService $httpClientService
67
-	 * @param ICloudIdManager $cloudIdManager
68
-	 * @param ILogger $logger
69
-	 */
70
-	public function __construct(IAppManager $appManager,
71
-								IClientService $httpClientService,
72
-								ICloudIdManager $cloudIdManager,
73
-								ILogger $logger) {
74
-		$this->cloudFederationProvider= [];
75
-		$this->appManager = $appManager;
76
-		$this->httpClientService = $httpClientService;
77
-		$this->cloudIdManager = $cloudIdManager;
78
-		$this->logger = $logger;
79
-	}
80
-
81
-
82
-	/**
83
-	 * Registers an callback function which must return an cloud federation provider
84
-	 *
85
-	 * @param string $resourceType which resource type does the provider handles
86
-	 * @param string $displayName user facing name of the federated share provider
87
-	 * @param callable $callback
88
-	 */
89
-	public function addCloudFederationProvider($resourceType, $displayName, callable $callback) {
90
-		$this->cloudFederationProvider[$resourceType] = [
91
-			'resourceType' => $resourceType,
92
-			'displayName' => $displayName,
93
-			'callback' => $callback,
94
-		];
95
-
96
-	}
97
-
98
-	/**
99
-	 * remove cloud federation provider
100
-	 *
101
-	 * @param string $providerId
102
-	 */
103
-	public function removeCloudFederationProvider($providerId) {
104
-		unset($this->cloudFederationProvider[$providerId]);
105
-	}
106
-
107
-	/**
108
-	 * get a list of all cloudFederationProviders
109
-	 *
110
-	 * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
111
-	 */
112
-	public function getAllCloudFederationProviders() {
113
-		return $this->cloudFederationProvider;
114
-	}
115
-
116
-	/**
117
-	 * get a specific cloud federation provider
118
-	 *
119
-	 * @param string $resourceType
120
-	 * @return ICloudFederationProvider
121
-	 * @throws ProviderDoesNotExistsException
122
-	 */
123
-	public function getCloudFederationProvider($resourceType) {
124
-		if (isset($this->cloudFederationProvider[$resourceType])) {
125
-			return call_user_func($this->cloudFederationProvider[$resourceType]['callback']);
126
-		} else {
127
-			throw new ProviderDoesNotExistsException($resourceType);
128
-		}
129
-	}
130
-
131
-	public function sendShare(ICloudFederationShare $share) {
132
-		$cloudID = $this->cloudIdManager->resolveCloudId($share->getShareWith());
133
-		$ocmEndPoint = $this->getOCMEndPoint($cloudID->getRemote());
134
-
135
-		if (empty($ocmEndPoint)) {
136
-			return false;
137
-		}
138
-
139
-		$client = $this->httpClientService->newClient();
140
-		try {
141
-			$response = $client->post($ocmEndPoint . '/shares', [
142
-				'body' => $share->getShare(),
143
-				'timeout' => 10,
144
-				'connect_timeout' => 10,
145
-			]);
146
-
147
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
148
-				return true;
149
-			}
150
-
151
-		} catch (\Exception $e) {
152
-			// if flat re-sharing is not supported by the remote server
153
-			// we re-throw the exception and fall back to the old behaviour.
154
-			// (flat re-shares has been introduced in Nextcloud 9.1)
155
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
156
-				throw $e;
157
-			}
158
-		}
159
-
160
-		return false;
161
-
162
-	}
163
-
164
-	/**
165
-	 * @param string $url
166
-	 * @param ICloudFederationNotification $notification
167
-	 * @return mixed
168
-	 */
169
-	public function sendNotification($url, ICloudFederationNotification $notification) {
170
-		$ocmEndPoint = $this->getOCMEndPoint($url);
171
-
172
-		if (empty($ocmEndPoint)) {
173
-			return false;
174
-		}
175
-
176
-		$client = $this->httpClientService->newClient();
177
-		try {
178
-			$response = $client->post($ocmEndPoint . '/notifications', [
179
-				'body' => $notification->getMessage(),
180
-				'timeout' => 10,
181
-				'connect_timeout' => 10,
182
-			]);
183
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
184
-				$result = json_decode($response->getBody(), true);
185
-				return (is_array($result)) ? $result : [];
186
-			}
187
-		} catch (\Exception $e) {
188
-			// log the error and return false
189
-			$this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
190
-		}
191
-
192
-		return false;
193
-	}
194
-
195
-	/**
196
-	 * check if the new cloud federation API is ready to be used
197
-	 *
198
-	 * @return bool
199
-	 */
200
-	public function isReady() {
201
-		return $this->appManager->isEnabledForUser('cloud_federation_api');
202
-	}
203
-	/**
204
-	 * check if server supports the new OCM api and ask for the correct end-point
205
-	 *
206
-	 * @param string $url full base URL of the cloud server
207
-	 * @return string
208
-	 */
209
-	protected function getOCMEndPoint($url) {
210
-		$client = $this->httpClientService->newClient();
211
-		try {
212
-			$response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
213
-		} catch (\Exception $e) {
214
-			return '';
215
-		}
216
-
217
-		$result = $response->getBody();
218
-		$result = json_decode($result, true);
219
-
220
-		$supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
221
-
222
-		if (isset($result['endPoint']) && $supportedVersion) {
223
-			return $result['endPoint'];
224
-		}
225
-
226
-		return '';
227
-	}
45
+    /** @var array list of available cloud federation providers */
46
+    private $cloudFederationProvider;
47
+
48
+    /** @var IAppManager */
49
+    private $appManager;
50
+
51
+    /** @var IClientService */
52
+    private $httpClientService;
53
+
54
+    /** @var ICloudIdManager */
55
+    private $cloudIdManager;
56
+
57
+    /** @var ILogger */
58
+    private $logger;
59
+
60
+    private $supportedAPIVersion = '1.0-proposal1';
61
+
62
+    /**
63
+     * CloudFederationProviderManager constructor.
64
+     *
65
+     * @param IAppManager $appManager
66
+     * @param IClientService $httpClientService
67
+     * @param ICloudIdManager $cloudIdManager
68
+     * @param ILogger $logger
69
+     */
70
+    public function __construct(IAppManager $appManager,
71
+                                IClientService $httpClientService,
72
+                                ICloudIdManager $cloudIdManager,
73
+                                ILogger $logger) {
74
+        $this->cloudFederationProvider= [];
75
+        $this->appManager = $appManager;
76
+        $this->httpClientService = $httpClientService;
77
+        $this->cloudIdManager = $cloudIdManager;
78
+        $this->logger = $logger;
79
+    }
80
+
81
+
82
+    /**
83
+     * Registers an callback function which must return an cloud federation provider
84
+     *
85
+     * @param string $resourceType which resource type does the provider handles
86
+     * @param string $displayName user facing name of the federated share provider
87
+     * @param callable $callback
88
+     */
89
+    public function addCloudFederationProvider($resourceType, $displayName, callable $callback) {
90
+        $this->cloudFederationProvider[$resourceType] = [
91
+            'resourceType' => $resourceType,
92
+            'displayName' => $displayName,
93
+            'callback' => $callback,
94
+        ];
95
+
96
+    }
97
+
98
+    /**
99
+     * remove cloud federation provider
100
+     *
101
+     * @param string $providerId
102
+     */
103
+    public function removeCloudFederationProvider($providerId) {
104
+        unset($this->cloudFederationProvider[$providerId]);
105
+    }
106
+
107
+    /**
108
+     * get a list of all cloudFederationProviders
109
+     *
110
+     * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
111
+     */
112
+    public function getAllCloudFederationProviders() {
113
+        return $this->cloudFederationProvider;
114
+    }
115
+
116
+    /**
117
+     * get a specific cloud federation provider
118
+     *
119
+     * @param string $resourceType
120
+     * @return ICloudFederationProvider
121
+     * @throws ProviderDoesNotExistsException
122
+     */
123
+    public function getCloudFederationProvider($resourceType) {
124
+        if (isset($this->cloudFederationProvider[$resourceType])) {
125
+            return call_user_func($this->cloudFederationProvider[$resourceType]['callback']);
126
+        } else {
127
+            throw new ProviderDoesNotExistsException($resourceType);
128
+        }
129
+    }
130
+
131
+    public function sendShare(ICloudFederationShare $share) {
132
+        $cloudID = $this->cloudIdManager->resolveCloudId($share->getShareWith());
133
+        $ocmEndPoint = $this->getOCMEndPoint($cloudID->getRemote());
134
+
135
+        if (empty($ocmEndPoint)) {
136
+            return false;
137
+        }
138
+
139
+        $client = $this->httpClientService->newClient();
140
+        try {
141
+            $response = $client->post($ocmEndPoint . '/shares', [
142
+                'body' => $share->getShare(),
143
+                'timeout' => 10,
144
+                'connect_timeout' => 10,
145
+            ]);
146
+
147
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
148
+                return true;
149
+            }
150
+
151
+        } catch (\Exception $e) {
152
+            // if flat re-sharing is not supported by the remote server
153
+            // we re-throw the exception and fall back to the old behaviour.
154
+            // (flat re-shares has been introduced in Nextcloud 9.1)
155
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
156
+                throw $e;
157
+            }
158
+        }
159
+
160
+        return false;
161
+
162
+    }
163
+
164
+    /**
165
+     * @param string $url
166
+     * @param ICloudFederationNotification $notification
167
+     * @return mixed
168
+     */
169
+    public function sendNotification($url, ICloudFederationNotification $notification) {
170
+        $ocmEndPoint = $this->getOCMEndPoint($url);
171
+
172
+        if (empty($ocmEndPoint)) {
173
+            return false;
174
+        }
175
+
176
+        $client = $this->httpClientService->newClient();
177
+        try {
178
+            $response = $client->post($ocmEndPoint . '/notifications', [
179
+                'body' => $notification->getMessage(),
180
+                'timeout' => 10,
181
+                'connect_timeout' => 10,
182
+            ]);
183
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
184
+                $result = json_decode($response->getBody(), true);
185
+                return (is_array($result)) ? $result : [];
186
+            }
187
+        } catch (\Exception $e) {
188
+            // log the error and return false
189
+            $this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
190
+        }
191
+
192
+        return false;
193
+    }
194
+
195
+    /**
196
+     * check if the new cloud federation API is ready to be used
197
+     *
198
+     * @return bool
199
+     */
200
+    public function isReady() {
201
+        return $this->appManager->isEnabledForUser('cloud_federation_api');
202
+    }
203
+    /**
204
+     * check if server supports the new OCM api and ask for the correct end-point
205
+     *
206
+     * @param string $url full base URL of the cloud server
207
+     * @return string
208
+     */
209
+    protected function getOCMEndPoint($url) {
210
+        $client = $this->httpClientService->newClient();
211
+        try {
212
+            $response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
213
+        } catch (\Exception $e) {
214
+            return '';
215
+        }
216
+
217
+        $result = $response->getBody();
218
+        $result = json_decode($result, true);
219
+
220
+        $supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
221
+
222
+        if (isset($result['endPoint']) && $supportedVersion) {
223
+            return $result['endPoint'];
224
+        }
225
+
226
+        return '';
227
+    }
228 228
 
229 229
 
230 230
 }
Please login to merge, or discard this patch.
lib/private/Federation/CloudFederationFactory.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -27,37 +27,37 @@
 block discarded – undo
27 27
 
28 28
 class CloudFederationFactory implements ICloudFederationFactory {
29 29
 
30
-	/**
31
-	 * get a CloudFederationShare Object to prepare a share you want to send
32
-	 *
33
-	 * @param string $shareWith
34
-	 * @param string $name resource name (e.g. document.odt)
35
-	 * @param string $description share description (optional)
36
-	 * @param string $providerId resource UID on the provider side
37
-	 * @param string $owner provider specific UID of the user who owns the resource
38
-	 * @param string $ownerDisplayName display name of the user who shared the item
39
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
40
-	 * @param string $sharedByDisplayName display name of the user who shared the resource
41
-	 * @param string $sharedSecret used to authenticate requests across servers
42
-	 * @param string $shareType ('group' or 'user' share)
43
-	 * @param $resourceType ('file', 'calendar',...)
44
-	 * @return ICloudFederationShare
45
-	 *
46
-	 * @since 14.0.0
47
-	 */
48
-	public function getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $sharedSecret, $shareType, $resourceType) {
49
-		return new CloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $shareType, $resourceType, $sharedSecret);
50
-	}
30
+    /**
31
+     * get a CloudFederationShare Object to prepare a share you want to send
32
+     *
33
+     * @param string $shareWith
34
+     * @param string $name resource name (e.g. document.odt)
35
+     * @param string $description share description (optional)
36
+     * @param string $providerId resource UID on the provider side
37
+     * @param string $owner provider specific UID of the user who owns the resource
38
+     * @param string $ownerDisplayName display name of the user who shared the item
39
+     * @param string $sharedBy provider specific UID of the user who shared the resource
40
+     * @param string $sharedByDisplayName display name of the user who shared the resource
41
+     * @param string $sharedSecret used to authenticate requests across servers
42
+     * @param string $shareType ('group' or 'user' share)
43
+     * @param $resourceType ('file', 'calendar',...)
44
+     * @return ICloudFederationShare
45
+     *
46
+     * @since 14.0.0
47
+     */
48
+    public function getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $sharedSecret, $shareType, $resourceType) {
49
+        return new CloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $shareType, $resourceType, $sharedSecret);
50
+    }
51 51
 
52
-	/**
53
-	 * get a Cloud FederationNotification object to prepare a notification you
54
-	 * want to send
55
-	 *
56
-	 * @return ICloudFederationNotification
57
-	 *
58
-	 * @since 14.0.0
59
-	 */
60
-	public function getCloudFederationNotification() {
61
-		return new CloudFederationNotification();
62
-	}
52
+    /**
53
+     * get a Cloud FederationNotification object to prepare a notification you
54
+     * want to send
55
+     *
56
+     * @return ICloudFederationNotification
57
+     *
58
+     * @since 14.0.0
59
+     */
60
+    public function getCloudFederationNotification() {
61
+        return new CloudFederationNotification();
62
+    }
63 63
 }
Please login to merge, or discard this patch.
lib/public/Federation/Exceptions/BadRequestException.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@
 block discarded – undo
36 36
 		$l = \OC::$server->getL10N('federation');
37 37
 		$this->parameterList = $missingParameters;
38 38
 		$parameterList = implode(',', $missingParameters);
39
-		$message = 'Parameters missing in order to complete the request. Missing Parameters: ' . $parameterList;
39
+		$message = 'Parameters missing in order to complete the request. Missing Parameters: '.$parameterList;
40 40
 		$hint = $l->t('Parameters missing in order to complete the request. Missing Parameters: "%s"', [$parameterList]);
41 41
 		parent::__construct($message, $hint);
42 42
 	}
Please login to merge, or discard this patch.
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -32,46 +32,46 @@
 block discarded – undo
32 32
  */
33 33
 class BadRequestException extends HintException {
34 34
 
35
-	private $parameterList;
35
+    private $parameterList;
36 36
 
37
-	/**
38
-	 * BadRequestException constructor.
39
-	 *
40
-	 * @since 14.0.0
41
-	 *
42
-	 * @param array $missingParameters
43
-	 */
44
-	public function __construct(array $missingParameters) {
45
-		$l = \OC::$server->getL10N('federation');
46
-		$this->parameterList = $missingParameters;
47
-		$parameterList = implode(',', $missingParameters);
48
-		$message = 'Parameters missing in order to complete the request. Missing Parameters: ' . $parameterList;
49
-		$hint = $l->t('Parameters missing in order to complete the request. Missing Parameters: "%s"', [$parameterList]);
50
-		parent::__construct($message, $hint);
51
-	}
37
+    /**
38
+     * BadRequestException constructor.
39
+     *
40
+     * @since 14.0.0
41
+     *
42
+     * @param array $missingParameters
43
+     */
44
+    public function __construct(array $missingParameters) {
45
+        $l = \OC::$server->getL10N('federation');
46
+        $this->parameterList = $missingParameters;
47
+        $parameterList = implode(',', $missingParameters);
48
+        $message = 'Parameters missing in order to complete the request. Missing Parameters: ' . $parameterList;
49
+        $hint = $l->t('Parameters missing in order to complete the request. Missing Parameters: "%s"', [$parameterList]);
50
+        parent::__construct($message, $hint);
51
+    }
52 52
 
53
-	/**
54
-	 * get array with the return message as defined in the OCM API
55
-	 *
56
-	 * @since 14.0.0
57
-	 *
58
-	 * @return array
59
-	 */
60
-	public function getReturnMessage() {
61
-		$result = [
62
-			'message' => 'RESOURCE_NOT_FOUND',
63
-			'validationErrors' =>[
64
-			]
65
-		];
53
+    /**
54
+     * get array with the return message as defined in the OCM API
55
+     *
56
+     * @since 14.0.0
57
+     *
58
+     * @return array
59
+     */
60
+    public function getReturnMessage() {
61
+        $result = [
62
+            'message' => 'RESOURCE_NOT_FOUND',
63
+            'validationErrors' =>[
64
+            ]
65
+        ];
66 66
 
67
-		foreach ($this->parameterList as $missingParameter) {
68
-			$result['validationErrors'] = [
69
-				'name' => $missingParameter,
70
-				'message' => 'NOT_FOUND'
71
-			];
72
-		}
67
+        foreach ($this->parameterList as $missingParameter) {
68
+            $result['validationErrors'] = [
69
+                'name' => $missingParameter,
70
+                'message' => 'NOT_FOUND'
71
+            ];
72
+        }
73 73
 
74
-		return $result;
75
-	}
74
+        return $result;
75
+    }
76 76
 
77 77
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Capabilities.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -28,37 +28,37 @@
 block discarded – undo
28 28
 
29 29
 class Capabilities implements ICapability {
30 30
 
31
-	/** @var IURLGenerator */
32
-	private $urlGenerator;
31
+    /** @var IURLGenerator */
32
+    private $urlGenerator;
33 33
 
34
-	public function __construct(IURLGenerator $urlGenerator) {
35
-		$this->urlGenerator = $urlGenerator;
36
-	}
34
+    public function __construct(IURLGenerator $urlGenerator) {
35
+        $this->urlGenerator = $urlGenerator;
36
+    }
37 37
 
38
-	/**
39
-	 * Function an app uses to return the capabilities
40
-	 *
41
-	 * @return array Array containing the apps capabilities
42
-	 * @since 8.2.0
43
-	 */
44
-	public function getCapabilities() {
45
-		$url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
46
-		$capabilities = ['ocm' =>
47
-			[
48
-				'enabled' => true,
49
-				'apiVersion' => '1.0-proposal1',
50
-				'endPoint' => substr($url, 0, strrpos($url, '/')),
51
-				'shareTypes' => [
52
-					[
53
-						'name' => 'file',
54
-						'protocols' => [
55
-							'webdav' => '/public.php/webdav/',
56
-						]
57
-					],
58
-				]
59
-			]
60
-		];
38
+    /**
39
+     * Function an app uses to return the capabilities
40
+     *
41
+     * @return array Array containing the apps capabilities
42
+     * @since 8.2.0
43
+     */
44
+    public function getCapabilities() {
45
+        $url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
46
+        $capabilities = ['ocm' =>
47
+            [
48
+                'enabled' => true,
49
+                'apiVersion' => '1.0-proposal1',
50
+                'endPoint' => substr($url, 0, strrpos($url, '/')),
51
+                'shareTypes' => [
52
+                    [
53
+                        'name' => 'file',
54
+                        'protocols' => [
55
+                            'webdav' => '/public.php/webdav/',
56
+                        ]
57
+                    ],
58
+                ]
59
+            ]
60
+        ];
61 61
 
62
-		return $capabilities;
63
-	}
62
+        return $capabilities;
63
+    }
64 64
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -247,8 +247,7 @@
 block discarded – undo
247 247
 			return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
248 248
 		} catch (AuthenticationFailedException $e) {
249 249
 			return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
250
-		}
251
-		catch (\Exception $e) {
250
+		} catch (\Exception $e) {
252 251
 			return new JSONResponse(
253 252
 				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
254 253
 				Http::STATUS_BAD_REQUEST
Please login to merge, or discard this patch.
Indentation   +245 added lines, -245 removed lines patch added patch discarded remove patch
@@ -52,250 +52,250 @@
 block discarded – undo
52 52
  */
53 53
 class RequestHandlerController extends Controller {
54 54
 
55
-	/** @var ILogger */
56
-	private $logger;
57
-
58
-	/** @var IUserManager */
59
-	private $userManager;
60
-
61
-	/** @var IGroupManager */
62
-	private $groupManager;
63
-
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-
67
-	/** @var ICloudFederationProviderManager */
68
-	private $cloudFederationProviderManager;
69
-
70
-	/** @var Config */
71
-	private $config;
72
-
73
-	/** @var ICloudFederationFactory */
74
-	private $factory;
75
-
76
-	/** @var ICloudIdManager */
77
-	private $cloudIdManager;
78
-
79
-	public function __construct($appName,
80
-								IRequest $request,
81
-								ILogger $logger,
82
-								IUserManager $userManager,
83
-								IGroupManager $groupManager,
84
-								IURLGenerator $urlGenerator,
85
-								ICloudFederationProviderManager $cloudFederationProviderManager,
86
-								Config $config,
87
-								ICloudFederationFactory $factory,
88
-								ICloudIdManager $cloudIdManager
89
-	) {
90
-		parent::__construct($appName, $request);
91
-
92
-		$this->logger = $logger;
93
-		$this->userManager = $userManager;
94
-		$this->groupManager = $groupManager;
95
-		$this->urlGenerator = $urlGenerator;
96
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
97
-		$this->config = $config;
98
-		$this->factory = $factory;
99
-		$this->cloudIdManager = $cloudIdManager;
100
-	}
101
-
102
-	/**
103
-	 * add share
104
-	 *
105
-	 * @NoCSRFRequired
106
-	 * @PublicPage
107
-	 * @BruteForceProtection(action=receiveFederatedShare)
108
-	 *
109
-	 * @param string $shareWith
110
-	 * @param string $name resource name (e.g. document.odt)
111
-	 * @param string $description share description (optional)
112
-	 * @param string $providerId resource UID on the provider side
113
-	 * @param string $owner provider specific UID of the user who owns the resource
114
-	 * @param string $ownerDisplayName display name of the user who shared the item
115
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
116
-	 * @param string $sharedByDisplayName display name of the user who shared the resource
117
-	 * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
118
-	 * @param string $shareType ('group' or 'user' share)
119
-	 * @param $resourceType ('file', 'calendar',...)
120
-	 * @return Http\DataResponse|JSONResponse
121
-	 *
122
-	 * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
123
-	 */
124
-	public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
125
-
126
-		// check if all required parameters are set
127
-		if ($shareWith === null ||
128
-			$name === null ||
129
-			$providerId === null ||
130
-			$owner === null ||
131
-			$resourceType === null ||
132
-			$shareType === null ||
133
-			!is_array($protocol) ||
134
-			!isset($protocol['name']) ||
135
-			!isset ($protocol['options']) ||
136
-			!is_array($protocol['options']) ||
137
-			!isset($protocol['options']['sharedSecret'])
138
-		) {
139
-			return new JSONResponse(
140
-				['message' => 'Missing arguments'],
141
-				Http::STATUS_BAD_REQUEST
142
-			);
143
-		}
144
-
145
-		$supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
146
-		if (!in_array($shareType, $supportedShareTypes)) {
147
-			return new JSONResponse(
148
-				['message' => 'Share type "' . $shareType . '" not implemented'],
149
-				Http::STATUS_NOT_IMPLEMENTED
150
-			);
151
-		}
152
-
153
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
154
-		$shareWithLocalId = $cloudId->getUser();
155
-
156
-		if ($shareType === 'user') {
157
-			$shareWith = $this->mapUid($shareWithLocalId);
158
-
159
-			if (!$this->userManager->userExists($shareWith)) {
160
-				return new JSONResponse(
161
-					['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
162
-					Http::STATUS_BAD_REQUEST
163
-				);
164
-			}
165
-		}
166
-
167
-		if ($shareType === 'group') {
168
-			if(!$this->groupManager->groupExists($shareWithLocalId)) {
169
-				return new JSONResponse(
170
-					['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
171
-					Http::STATUS_BAD_REQUEST
172
-				);
173
-			}
174
-		}
175
-
176
-		// if no explicit display name is given, we use the uid as display name
177
-		$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
178
-		$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
179
-
180
-		// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
181
-		if ($sharedBy === null) {
182
-			$sharedBy = $owner;
183
-			$sharedByDisplayName = $ownerDisplayName;
184
-		}
185
-
186
-		try {
187
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
188
-			$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
189
-			$share->setProtocol($protocol);
190
-			$provider->shareReceived($share);
191
-		} catch (ProviderDoesNotExistsException $e) {
192
-			return new JSONResponse(
193
-				['message' => $e->getMessage()],
194
-				Http::STATUS_NOT_IMPLEMENTED
195
-			);
196
-		} catch (ProviderCouldNotAddShareException $e) {
197
-			return new JSONResponse(
198
-				['message' => $e->getMessage()],
199
-				$e->getCode()
200
-			);
201
-		} catch (\Exception $e) {
202
-			return new JSONResponse(
203
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
204
-				Http::STATUS_BAD_REQUEST
205
-			);
206
-		}
207
-
208
-		$user = $this->userManager->get($shareWithLocalId);
209
-		$recipientDisplayName = '';
210
-		if($user) {
211
-			$recipientDisplayName = $user->getDisplayName();
212
-		}
213
-
214
-		return new JSONResponse(
215
-			['recipientDisplayName' => $recipientDisplayName],
216
-			Http::STATUS_CREATED);
217
-
218
-	}
219
-
220
-	/**
221
-	 * receive notification about existing share
222
-	 *
223
-	 * @NoCSRFRequired
224
-	 * @PublicPage
225
-	 * @BruteForceProtection(action=receiveFederatedShareNotification)
226
-	 *
227
-	 * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
228
-	 * @param string $resourceType (calendar, file, contact,...)
229
-	 * @param string $providerId id of the share
230
-	 * @param array $notification the actual payload of the notification
231
-	 * @return JSONResponse
232
-	 */
233
-	public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
234
-
235
-		// check if all required parameters are set
236
-		if ($notificationType === null ||
237
-			$resourceType === null ||
238
-			$providerId === null ||
239
-			!is_array($notification)
240
-		) {
241
-			return new JSONResponse(
242
-				['message' => 'Missing arguments'],
243
-				Http::STATUS_BAD_REQUEST
244
-			);
245
-		}
246
-
247
-		try {
248
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
249
-			$result = $provider->notificationReceived($notificationType, $providerId, $notification);
250
-		} catch (ProviderDoesNotExistsException $e) {
251
-			return new JSONResponse(
252
-				['message' => $e->getMessage()],
253
-				Http::STATUS_BAD_REQUEST
254
-			);
255
-		} catch (ShareNotFound $e) {
256
-			return new JSONResponse(
257
-				['message' => $e->getMessage()],
258
-				Http::STATUS_BAD_REQUEST
259
-			);
260
-		} catch (ActionNotSupportedException $e) {
261
-			return new JSONResponse(
262
-				['message' => $e->getMessage()],
263
-				Http::STATUS_NOT_IMPLEMENTED
264
-			);
265
-		} catch (BadRequestException $e) {
266
-			return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
267
-		} catch (AuthenticationFailedException $e) {
268
-			return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
269
-		}
270
-		catch (\Exception $e) {
271
-			return new JSONResponse(
272
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
273
-				Http::STATUS_BAD_REQUEST
274
-			);
275
-		}
276
-
277
-		return new JSONResponse($result,Http::STATUS_CREATED);
278
-
279
-	}
280
-
281
-	/**
282
-	 * map login name to internal LDAP UID if a LDAP backend is in use
283
-	 *
284
-	 * @param string $uid
285
-	 * @return string mixed
286
-	 */
287
-	private function mapUid($uid) {
288
-		\OC::$server->getURLGenerator()->linkToDocs('key');
289
-		// FIXME this should be a method in the user management instead
290
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
291
-		\OCP\Util::emitHook(
292
-			'\OCA\Files_Sharing\API\Server2Server',
293
-			'preLoginNameUsedAsUserName',
294
-			array('uid' => &$uid)
295
-		);
296
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
297
-
298
-		return $uid;
299
-	}
55
+    /** @var ILogger */
56
+    private $logger;
57
+
58
+    /** @var IUserManager */
59
+    private $userManager;
60
+
61
+    /** @var IGroupManager */
62
+    private $groupManager;
63
+
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+
67
+    /** @var ICloudFederationProviderManager */
68
+    private $cloudFederationProviderManager;
69
+
70
+    /** @var Config */
71
+    private $config;
72
+
73
+    /** @var ICloudFederationFactory */
74
+    private $factory;
75
+
76
+    /** @var ICloudIdManager */
77
+    private $cloudIdManager;
78
+
79
+    public function __construct($appName,
80
+                                IRequest $request,
81
+                                ILogger $logger,
82
+                                IUserManager $userManager,
83
+                                IGroupManager $groupManager,
84
+                                IURLGenerator $urlGenerator,
85
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
86
+                                Config $config,
87
+                                ICloudFederationFactory $factory,
88
+                                ICloudIdManager $cloudIdManager
89
+    ) {
90
+        parent::__construct($appName, $request);
91
+
92
+        $this->logger = $logger;
93
+        $this->userManager = $userManager;
94
+        $this->groupManager = $groupManager;
95
+        $this->urlGenerator = $urlGenerator;
96
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
97
+        $this->config = $config;
98
+        $this->factory = $factory;
99
+        $this->cloudIdManager = $cloudIdManager;
100
+    }
101
+
102
+    /**
103
+     * add share
104
+     *
105
+     * @NoCSRFRequired
106
+     * @PublicPage
107
+     * @BruteForceProtection(action=receiveFederatedShare)
108
+     *
109
+     * @param string $shareWith
110
+     * @param string $name resource name (e.g. document.odt)
111
+     * @param string $description share description (optional)
112
+     * @param string $providerId resource UID on the provider side
113
+     * @param string $owner provider specific UID of the user who owns the resource
114
+     * @param string $ownerDisplayName display name of the user who shared the item
115
+     * @param string $sharedBy provider specific UID of the user who shared the resource
116
+     * @param string $sharedByDisplayName display name of the user who shared the resource
117
+     * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
118
+     * @param string $shareType ('group' or 'user' share)
119
+     * @param $resourceType ('file', 'calendar',...)
120
+     * @return Http\DataResponse|JSONResponse
121
+     *
122
+     * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
123
+     */
124
+    public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
125
+
126
+        // check if all required parameters are set
127
+        if ($shareWith === null ||
128
+            $name === null ||
129
+            $providerId === null ||
130
+            $owner === null ||
131
+            $resourceType === null ||
132
+            $shareType === null ||
133
+            !is_array($protocol) ||
134
+            !isset($protocol['name']) ||
135
+            !isset ($protocol['options']) ||
136
+            !is_array($protocol['options']) ||
137
+            !isset($protocol['options']['sharedSecret'])
138
+        ) {
139
+            return new JSONResponse(
140
+                ['message' => 'Missing arguments'],
141
+                Http::STATUS_BAD_REQUEST
142
+            );
143
+        }
144
+
145
+        $supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
146
+        if (!in_array($shareType, $supportedShareTypes)) {
147
+            return new JSONResponse(
148
+                ['message' => 'Share type "' . $shareType . '" not implemented'],
149
+                Http::STATUS_NOT_IMPLEMENTED
150
+            );
151
+        }
152
+
153
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
154
+        $shareWithLocalId = $cloudId->getUser();
155
+
156
+        if ($shareType === 'user') {
157
+            $shareWith = $this->mapUid($shareWithLocalId);
158
+
159
+            if (!$this->userManager->userExists($shareWith)) {
160
+                return new JSONResponse(
161
+                    ['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
162
+                    Http::STATUS_BAD_REQUEST
163
+                );
164
+            }
165
+        }
166
+
167
+        if ($shareType === 'group') {
168
+            if(!$this->groupManager->groupExists($shareWithLocalId)) {
169
+                return new JSONResponse(
170
+                    ['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
171
+                    Http::STATUS_BAD_REQUEST
172
+                );
173
+            }
174
+        }
175
+
176
+        // if no explicit display name is given, we use the uid as display name
177
+        $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
178
+        $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
179
+
180
+        // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
181
+        if ($sharedBy === null) {
182
+            $sharedBy = $owner;
183
+            $sharedByDisplayName = $ownerDisplayName;
184
+        }
185
+
186
+        try {
187
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
188
+            $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
189
+            $share->setProtocol($protocol);
190
+            $provider->shareReceived($share);
191
+        } catch (ProviderDoesNotExistsException $e) {
192
+            return new JSONResponse(
193
+                ['message' => $e->getMessage()],
194
+                Http::STATUS_NOT_IMPLEMENTED
195
+            );
196
+        } catch (ProviderCouldNotAddShareException $e) {
197
+            return new JSONResponse(
198
+                ['message' => $e->getMessage()],
199
+                $e->getCode()
200
+            );
201
+        } catch (\Exception $e) {
202
+            return new JSONResponse(
203
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
204
+                Http::STATUS_BAD_REQUEST
205
+            );
206
+        }
207
+
208
+        $user = $this->userManager->get($shareWithLocalId);
209
+        $recipientDisplayName = '';
210
+        if($user) {
211
+            $recipientDisplayName = $user->getDisplayName();
212
+        }
213
+
214
+        return new JSONResponse(
215
+            ['recipientDisplayName' => $recipientDisplayName],
216
+            Http::STATUS_CREATED);
217
+
218
+    }
219
+
220
+    /**
221
+     * receive notification about existing share
222
+     *
223
+     * @NoCSRFRequired
224
+     * @PublicPage
225
+     * @BruteForceProtection(action=receiveFederatedShareNotification)
226
+     *
227
+     * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
228
+     * @param string $resourceType (calendar, file, contact,...)
229
+     * @param string $providerId id of the share
230
+     * @param array $notification the actual payload of the notification
231
+     * @return JSONResponse
232
+     */
233
+    public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
234
+
235
+        // check if all required parameters are set
236
+        if ($notificationType === null ||
237
+            $resourceType === null ||
238
+            $providerId === null ||
239
+            !is_array($notification)
240
+        ) {
241
+            return new JSONResponse(
242
+                ['message' => 'Missing arguments'],
243
+                Http::STATUS_BAD_REQUEST
244
+            );
245
+        }
246
+
247
+        try {
248
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
249
+            $result = $provider->notificationReceived($notificationType, $providerId, $notification);
250
+        } catch (ProviderDoesNotExistsException $e) {
251
+            return new JSONResponse(
252
+                ['message' => $e->getMessage()],
253
+                Http::STATUS_BAD_REQUEST
254
+            );
255
+        } catch (ShareNotFound $e) {
256
+            return new JSONResponse(
257
+                ['message' => $e->getMessage()],
258
+                Http::STATUS_BAD_REQUEST
259
+            );
260
+        } catch (ActionNotSupportedException $e) {
261
+            return new JSONResponse(
262
+                ['message' => $e->getMessage()],
263
+                Http::STATUS_NOT_IMPLEMENTED
264
+            );
265
+        } catch (BadRequestException $e) {
266
+            return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
267
+        } catch (AuthenticationFailedException $e) {
268
+            return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
269
+        }
270
+        catch (\Exception $e) {
271
+            return new JSONResponse(
272
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
273
+                Http::STATUS_BAD_REQUEST
274
+            );
275
+        }
276
+
277
+        return new JSONResponse($result,Http::STATUS_CREATED);
278
+
279
+    }
280
+
281
+    /**
282
+     * map login name to internal LDAP UID if a LDAP backend is in use
283
+     *
284
+     * @param string $uid
285
+     * @return string mixed
286
+     */
287
+    private function mapUid($uid) {
288
+        \OC::$server->getURLGenerator()->linkToDocs('key');
289
+        // FIXME this should be a method in the user management instead
290
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
291
+        \OCP\Util::emitHook(
292
+            '\OCA\Files_Sharing\API\Server2Server',
293
+            'preLoginNameUsedAsUserName',
294
+            array('uid' => &$uid)
295
+        );
296
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
297
+
298
+        return $uid;
299
+    }
300 300
 
301 301
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 		$supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
146 146
 		if (!in_array($shareType, $supportedShareTypes)) {
147 147
 			return new JSONResponse(
148
-				['message' => 'Share type "' . $shareType . '" not implemented'],
148
+				['message' => 'Share type "'.$shareType.'" not implemented'],
149 149
 				Http::STATUS_NOT_IMPLEMENTED
150 150
 			);
151 151
 		}
@@ -158,16 +158,16 @@  discard block
 block discarded – undo
158 158
 
159 159
 			if (!$this->userManager->userExists($shareWith)) {
160 160
 				return new JSONResponse(
161
-					['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
161
+					['message' => 'User "'.$shareWith.'" does not exists at '.$this->urlGenerator->getBaseUrl()],
162 162
 					Http::STATUS_BAD_REQUEST
163 163
 				);
164 164
 			}
165 165
 		}
166 166
 
167 167
 		if ($shareType === 'group') {
168
-			if(!$this->groupManager->groupExists($shareWithLocalId)) {
168
+			if (!$this->groupManager->groupExists($shareWithLocalId)) {
169 169
 				return new JSONResponse(
170
-					['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
170
+					['message' => 'Group "'.$shareWith.'" does not exists at '.$this->urlGenerator->getBaseUrl()],
171 171
 					Http::STATUS_BAD_REQUEST
172 172
 				);
173 173
 			}
@@ -200,14 +200,14 @@  discard block
 block discarded – undo
200 200
 			);
201 201
 		} catch (\Exception $e) {
202 202
 			return new JSONResponse(
203
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
203
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
204 204
 				Http::STATUS_BAD_REQUEST
205 205
 			);
206 206
 		}
207 207
 
208 208
 		$user = $this->userManager->get($shareWithLocalId);
209 209
 		$recipientDisplayName = '';
210
-		if($user) {
210
+		if ($user) {
211 211
 			$recipientDisplayName = $user->getDisplayName();
212 212
 		}
213 213
 
@@ -269,12 +269,12 @@  discard block
 block discarded – undo
269 269
 		}
270 270
 		catch (\Exception $e) {
271 271
 			return new JSONResponse(
272
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
272
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
273 273
 				Http::STATUS_BAD_REQUEST
274 274
 			);
275 275
 		}
276 276
 
277
-		return new JSONResponse($result,Http::STATUS_CREATED);
277
+		return new JSONResponse($result, Http::STATUS_CREATED);
278 278
 
279 279
 	}
280 280
 
@@ -287,13 +287,13 @@  discard block
 block discarded – undo
287 287
 	private function mapUid($uid) {
288 288
 		\OC::$server->getURLGenerator()->linkToDocs('key');
289 289
 		// FIXME this should be a method in the user management instead
290
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
290
+		$this->logger->debug('shareWith before, '.$uid, ['app' => $this->appName]);
291 291
 		\OCP\Util::emitHook(
292 292
 			'\OCA\Files_Sharing\API\Server2Server',
293 293
 			'preLoginNameUsedAsUserName',
294 294
 			array('uid' => &$uid)
295 295
 		);
296
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
296
+		$this->logger->debug('shareWith after, '.$uid, ['app' => $this->appName]);
297 297
 
298 298
 		return $uid;
299 299
 	}
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 3 patches
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 	 *
325 325
 	 * @param string $remoteDomain
326 326
 	 * @param string $token
327
-	 * @param $remoteId id of the share
327
+	 * @param integer $remoteId id of the share
328 328
 	 * @param string $feedback
329 329
 	 * @return bool
330 330
 	 */
@@ -421,6 +421,9 @@  discard block
 block discarded – undo
421 421
 		return $result;
422 422
 	}
423 423
 
424
+	/**
425
+	 * @param string $mountPoint
426
+	 */
424 427
 	public function removeShare($mountPoint) {
425 428
 
426 429
 		$mountPointObj = $this->mountManager->find($mountPoint);
Please login to merge, or discard this patch.
Indentation   +476 added lines, -476 removed lines patch added patch discarded remove patch
@@ -44,520 +44,520 @@
 block discarded – undo
44 44
 use OCP\Share;
45 45
 
46 46
 class Manager {
47
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $uid;
53
-
54
-	/**
55
-	 * @var IDBConnection
56
-	 */
57
-	private $connection;
58
-
59
-	/**
60
-	 * @var \OC\Files\Mount\Manager
61
-	 */
62
-	private $mountManager;
63
-
64
-	/**
65
-	 * @var IStorageFactory
66
-	 */
67
-	private $storageLoader;
68
-
69
-	/**
70
-	 * @var IClientService
71
-	 */
72
-	private $clientService;
73
-
74
-	/**
75
-	 * @var IManager
76
-	 */
77
-	private $notificationManager;
78
-
79
-	/**
80
-	 * @var IDiscoveryService
81
-	 */
82
-	private $discoveryService;
83
-
84
-	/** @var ICloudFederationProviderManager */
85
-	private $cloudFederationProviderManager;
86
-
87
-	/** @var ICloudFederationFactory */
88
-	private $cloudFederationFactory;
89
-
90
-	/**
91
-	 * @param IDBConnection $connection
92
-	 * @param \OC\Files\Mount\Manager $mountManager
93
-	 * @param IStorageFactory $storageLoader
94
-	 * @param IClientService $clientService
95
-	 * @param IManager $notificationManager
96
-	 * @param IDiscoveryService $discoveryService
97
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
-	 * @param ICloudFederationFactory $cloudFederationFactory
99
-	 * @param string $uid
100
-	 */
101
-	public function __construct(IDBConnection $connection,
102
-								\OC\Files\Mount\Manager $mountManager,
103
-								IStorageFactory $storageLoader,
104
-								IClientService $clientService,
105
-								IManager $notificationManager,
106
-								IDiscoveryService $discoveryService,
107
-								ICloudFederationProviderManager $cloudFederationProviderManager,
108
-								ICloudFederationFactory $cloudFederationFactory,
109
-								$uid) {
110
-		$this->connection = $connection;
111
-		$this->mountManager = $mountManager;
112
-		$this->storageLoader = $storageLoader;
113
-		$this->clientService = $clientService;
114
-		$this->uid = $uid;
115
-		$this->notificationManager = $notificationManager;
116
-		$this->discoveryService = $discoveryService;
117
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
-		$this->cloudFederationFactory = $cloudFederationFactory;
119
-	}
120
-
121
-	/**
122
-	 * add new server-to-server share
123
-	 *
124
-	 * @param string $remote
125
-	 * @param string $token
126
-	 * @param string $password
127
-	 * @param string $name
128
-	 * @param string $owner
129
-	 * @param int $shareType
130
-	 * @param boolean $accepted
131
-	 * @param string $user
132
-	 * @param int $remoteId
133
-	 * @param int $parent
134
-	 * @return Mount|null
135
-	 * @throws \Doctrine\DBAL\DBALException
136
-	 */
137
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
138
-
139
-		$user = $user ? $user : $this->uid;
140
-		$accepted = $accepted ? 1 : 0;
141
-		$name = Filesystem::normalizePath('/' . $name);
142
-
143
-		if (!$accepted) {
144
-			// To avoid conflicts with the mount point generation later,
145
-			// we only use a temporary mount point name here. The real
146
-			// mount point name will be generated when accepting the share,
147
-			// using the original share item name.
148
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
149
-			$mountPoint = $tmpMountPointName;
150
-			$hash = md5($tmpMountPointName);
151
-			$data = [
152
-				'remote'		=> $remote,
153
-				'share_token'	=> $token,
154
-				'password'		=> $password,
155
-				'name'			=> $name,
156
-				'owner'			=> $owner,
157
-				'user'			=> $user,
158
-				'mountpoint'	=> $mountPoint,
159
-				'mountpoint_hash'	=> $hash,
160
-				'accepted'		=> $accepted,
161
-				'remote_id'		=> $remoteId,
162
-				'share_type'    => $shareType,
163
-			];
164
-
165
-			$i = 1;
166
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
167
-				// The external share already exists for the user
168
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
169
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
170
-				$i++;
171
-			}
172
-			return null;
173
-		}
174
-
175
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
176
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
177
-		$hash = md5($mountPoint);
178
-
179
-		$query = $this->connection->prepare('
47
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $uid;
53
+
54
+    /**
55
+     * @var IDBConnection
56
+     */
57
+    private $connection;
58
+
59
+    /**
60
+     * @var \OC\Files\Mount\Manager
61
+     */
62
+    private $mountManager;
63
+
64
+    /**
65
+     * @var IStorageFactory
66
+     */
67
+    private $storageLoader;
68
+
69
+    /**
70
+     * @var IClientService
71
+     */
72
+    private $clientService;
73
+
74
+    /**
75
+     * @var IManager
76
+     */
77
+    private $notificationManager;
78
+
79
+    /**
80
+     * @var IDiscoveryService
81
+     */
82
+    private $discoveryService;
83
+
84
+    /** @var ICloudFederationProviderManager */
85
+    private $cloudFederationProviderManager;
86
+
87
+    /** @var ICloudFederationFactory */
88
+    private $cloudFederationFactory;
89
+
90
+    /**
91
+     * @param IDBConnection $connection
92
+     * @param \OC\Files\Mount\Manager $mountManager
93
+     * @param IStorageFactory $storageLoader
94
+     * @param IClientService $clientService
95
+     * @param IManager $notificationManager
96
+     * @param IDiscoveryService $discoveryService
97
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
+     * @param ICloudFederationFactory $cloudFederationFactory
99
+     * @param string $uid
100
+     */
101
+    public function __construct(IDBConnection $connection,
102
+                                \OC\Files\Mount\Manager $mountManager,
103
+                                IStorageFactory $storageLoader,
104
+                                IClientService $clientService,
105
+                                IManager $notificationManager,
106
+                                IDiscoveryService $discoveryService,
107
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
108
+                                ICloudFederationFactory $cloudFederationFactory,
109
+                                $uid) {
110
+        $this->connection = $connection;
111
+        $this->mountManager = $mountManager;
112
+        $this->storageLoader = $storageLoader;
113
+        $this->clientService = $clientService;
114
+        $this->uid = $uid;
115
+        $this->notificationManager = $notificationManager;
116
+        $this->discoveryService = $discoveryService;
117
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
+        $this->cloudFederationFactory = $cloudFederationFactory;
119
+    }
120
+
121
+    /**
122
+     * add new server-to-server share
123
+     *
124
+     * @param string $remote
125
+     * @param string $token
126
+     * @param string $password
127
+     * @param string $name
128
+     * @param string $owner
129
+     * @param int $shareType
130
+     * @param boolean $accepted
131
+     * @param string $user
132
+     * @param int $remoteId
133
+     * @param int $parent
134
+     * @return Mount|null
135
+     * @throws \Doctrine\DBAL\DBALException
136
+     */
137
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
138
+
139
+        $user = $user ? $user : $this->uid;
140
+        $accepted = $accepted ? 1 : 0;
141
+        $name = Filesystem::normalizePath('/' . $name);
142
+
143
+        if (!$accepted) {
144
+            // To avoid conflicts with the mount point generation later,
145
+            // we only use a temporary mount point name here. The real
146
+            // mount point name will be generated when accepting the share,
147
+            // using the original share item name.
148
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
149
+            $mountPoint = $tmpMountPointName;
150
+            $hash = md5($tmpMountPointName);
151
+            $data = [
152
+                'remote'		=> $remote,
153
+                'share_token'	=> $token,
154
+                'password'		=> $password,
155
+                'name'			=> $name,
156
+                'owner'			=> $owner,
157
+                'user'			=> $user,
158
+                'mountpoint'	=> $mountPoint,
159
+                'mountpoint_hash'	=> $hash,
160
+                'accepted'		=> $accepted,
161
+                'remote_id'		=> $remoteId,
162
+                'share_type'    => $shareType,
163
+            ];
164
+
165
+            $i = 1;
166
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
167
+                // The external share already exists for the user
168
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
169
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
170
+                $i++;
171
+            }
172
+            return null;
173
+        }
174
+
175
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
176
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
177
+        $hash = md5($mountPoint);
178
+
179
+        $query = $this->connection->prepare('
180 180
 				INSERT INTO `*PREFIX*share_external`
181 181
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
182 182
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
183 183
 			');
184
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
185
-
186
-		$options = array(
187
-			'remote'	=> $remote,
188
-			'token'		=> $token,
189
-			'password'	=> $password,
190
-			'mountpoint'	=> $mountPoint,
191
-			'owner'		=> $owner
192
-		);
193
-		return $this->mountShare($options);
194
-	}
195
-
196
-	/**
197
-	 * get share
198
-	 *
199
-	 * @param int $id share id
200
-	 * @return mixed share of false
201
-	 */
202
-	public function getShare($id) {
203
-		$getShare = $this->connection->prepare('
184
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
185
+
186
+        $options = array(
187
+            'remote'	=> $remote,
188
+            'token'		=> $token,
189
+            'password'	=> $password,
190
+            'mountpoint'	=> $mountPoint,
191
+            'owner'		=> $owner
192
+        );
193
+        return $this->mountShare($options);
194
+    }
195
+
196
+    /**
197
+     * get share
198
+     *
199
+     * @param int $id share id
200
+     * @return mixed share of false
201
+     */
202
+    public function getShare($id) {
203
+        $getShare = $this->connection->prepare('
204 204
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
205 205
 			FROM  `*PREFIX*share_external`
206 206
 			WHERE `id` = ? AND `user` = ?');
207
-		$result = $getShare->execute(array($id, $this->uid));
208
-
209
-		return $result ? $getShare->fetch() : false;
210
-	}
211
-
212
-	/**
213
-	 * accept server-to-server share
214
-	 *
215
-	 * @param int $id
216
-	 * @return bool True if the share could be accepted, false otherwise
217
-	 */
218
-	public function acceptShare($id) {
219
-
220
-		$share = $this->getShare($id);
221
-		$result = false;
222
-
223
-		if ($share) {
224
-			\OC_Util::setupFS($this->uid);
225
-			$shareFolder = Helper::getShareFolder();
226
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
227
-			$mountPoint = Filesystem::normalizePath($mountPoint);
228
-			$hash = md5($mountPoint);
229
-
230
-			if($share['share_type'] === \OCP\Share::SHARE_TYPE_USER) {
231
-				$acceptShare = $this->connection->prepare('
207
+        $result = $getShare->execute(array($id, $this->uid));
208
+
209
+        return $result ? $getShare->fetch() : false;
210
+    }
211
+
212
+    /**
213
+     * accept server-to-server share
214
+     *
215
+     * @param int $id
216
+     * @return bool True if the share could be accepted, false otherwise
217
+     */
218
+    public function acceptShare($id) {
219
+
220
+        $share = $this->getShare($id);
221
+        $result = false;
222
+
223
+        if ($share) {
224
+            \OC_Util::setupFS($this->uid);
225
+            $shareFolder = Helper::getShareFolder();
226
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
227
+            $mountPoint = Filesystem::normalizePath($mountPoint);
228
+            $hash = md5($mountPoint);
229
+
230
+            if($share['share_type'] === \OCP\Share::SHARE_TYPE_USER) {
231
+                $acceptShare = $this->connection->prepare('
232 232
 				UPDATE `*PREFIX*share_external`
233 233
 				SET `accepted` = ?,
234 234
 					`mountpoint` = ?,
235 235
 					`mountpoint_hash` = ?
236 236
 				WHERE `id` = ? AND `user` = ?');
237
-				$updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
238
-			} else {
239
-				// TODO group share, add additional row for the user who accepted it
240
-			}
241
-			if ($updated === true) {
242
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
243
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
244
-				$result = true;
245
-			}
246
-		}
247
-
248
-		// Make sure the user has no notification for something that does not exist anymore.
249
-		$this->processNotification($id);
250
-
251
-		return $result;
252
-	}
253
-
254
-	/**
255
-	 * decline server-to-server share
256
-	 *
257
-	 * @param int $id
258
-	 * @return bool True if the share could be declined, false otherwise
259
-	 */
260
-	public function declineShare($id) {
261
-
262
-		$share = $this->getShare($id);
263
-
264
-		if ($share) {
265
-			$removeShare = $this->connection->prepare('
237
+                $updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
238
+            } else {
239
+                // TODO group share, add additional row for the user who accepted it
240
+            }
241
+            if ($updated === true) {
242
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
243
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
244
+                $result = true;
245
+            }
246
+        }
247
+
248
+        // Make sure the user has no notification for something that does not exist anymore.
249
+        $this->processNotification($id);
250
+
251
+        return $result;
252
+    }
253
+
254
+    /**
255
+     * decline server-to-server share
256
+     *
257
+     * @param int $id
258
+     * @return bool True if the share could be declined, false otherwise
259
+     */
260
+    public function declineShare($id) {
261
+
262
+        $share = $this->getShare($id);
263
+
264
+        if ($share) {
265
+            $removeShare = $this->connection->prepare('
266 266
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
267
-			$removeShare->execute(array($id, $this->uid));
268
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
269
-
270
-			$this->processNotification($id);
271
-			return true;
272
-		}
273
-
274
-		return false;
275
-	}
276
-
277
-	/**
278
-	 * @param int $remoteShare
279
-	 */
280
-	public function processNotification($remoteShare) {
281
-		$filter = $this->notificationManager->createNotification();
282
-		$filter->setApp('files_sharing')
283
-			->setUser($this->uid)
284
-			->setObject('remote_share', (int) $remoteShare);
285
-		$this->notificationManager->markProcessed($filter);
286
-	}
287
-
288
-	/**
289
-	 * inform remote server whether server-to-server share was accepted/declined
290
-	 *
291
-	 * @param string $remote
292
-	 * @param string $token
293
-	 * @param int $remoteId Share id on the remote host
294
-	 * @param string $feedback
295
-	 * @return boolean
296
-	 */
297
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
298
-
299
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
300
-
301
-		if($result === true) {
302
-			return true;
303
-		}
304
-
305
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
306
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
307
-
308
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
309
-		$fields = array('token' => $token);
310
-
311
-		$client = $this->clientService->newClient();
312
-
313
-		try {
314
-			$response = $client->post(
315
-				$url,
316
-				[
317
-					'body' => $fields,
318
-					'connect_timeout' => 10,
319
-				]
320
-			);
321
-		} catch (\Exception $e) {
322
-			return false;
323
-		}
324
-
325
-		$status = json_decode($response->getBody(), true);
326
-
327
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
328
-	}
329
-
330
-	/**
331
-	 * try send accept message to ocm end-point
332
-	 *
333
-	 * @param string $remoteDomain
334
-	 * @param string $token
335
-	 * @param $remoteId id of the share
336
-	 * @param string $feedback
337
-	 * @return bool
338
-	 */
339
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
340
-		switch ($feedback) {
341
-			case 'accept':
342
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
343
-				$notification->setMessage(
344
-					'SHARE_ACCEPTED',
345
-					'file',
346
-					$remoteId,
347
-					[
348
-						'sharedSecret' => $token,
349
-						'message' => 'Recipient accept the share'
350
-					]
351
-
352
-				);
353
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
354
-			case 'decline':
355
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
356
-				$notification->setMessage(
357
-					'SHARE_DECLINED',
358
-					'file',
359
-					$remoteId,
360
-					[
361
-						'sharedSecret' => $token,
362
-						'message' => 'Recipient declined the share'
363
-					]
364
-
365
-				);
366
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
367
-		}
368
-
369
-		return false;
370
-
371
-	}
372
-
373
-
374
-	/**
375
-	 * remove '/user/files' from the path and trailing slashes
376
-	 *
377
-	 * @param string $path
378
-	 * @return string
379
-	 */
380
-	protected function stripPath($path) {
381
-		$prefix = '/' . $this->uid . '/files';
382
-		return rtrim(substr($path, strlen($prefix)), '/');
383
-	}
384
-
385
-	public function getMount($data) {
386
-		$data['manager'] = $this;
387
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
388
-		$data['mountpoint'] = $mountPoint;
389
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
390
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
391
-	}
392
-
393
-	/**
394
-	 * @param array $data
395
-	 * @return Mount
396
-	 */
397
-	protected function mountShare($data) {
398
-		$mount = $this->getMount($data);
399
-		$this->mountManager->addMount($mount);
400
-		return $mount;
401
-	}
402
-
403
-	/**
404
-	 * @return \OC\Files\Mount\Manager
405
-	 */
406
-	public function getMountManager() {
407
-		return $this->mountManager;
408
-	}
409
-
410
-	/**
411
-	 * @param string $source
412
-	 * @param string $target
413
-	 * @return bool
414
-	 */
415
-	public function setMountPoint($source, $target) {
416
-		$source = $this->stripPath($source);
417
-		$target = $this->stripPath($target);
418
-		$sourceHash = md5($source);
419
-		$targetHash = md5($target);
420
-
421
-		$query = $this->connection->prepare('
267
+            $removeShare->execute(array($id, $this->uid));
268
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
269
+
270
+            $this->processNotification($id);
271
+            return true;
272
+        }
273
+
274
+        return false;
275
+    }
276
+
277
+    /**
278
+     * @param int $remoteShare
279
+     */
280
+    public function processNotification($remoteShare) {
281
+        $filter = $this->notificationManager->createNotification();
282
+        $filter->setApp('files_sharing')
283
+            ->setUser($this->uid)
284
+            ->setObject('remote_share', (int) $remoteShare);
285
+        $this->notificationManager->markProcessed($filter);
286
+    }
287
+
288
+    /**
289
+     * inform remote server whether server-to-server share was accepted/declined
290
+     *
291
+     * @param string $remote
292
+     * @param string $token
293
+     * @param int $remoteId Share id on the remote host
294
+     * @param string $feedback
295
+     * @return boolean
296
+     */
297
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
298
+
299
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
300
+
301
+        if($result === true) {
302
+            return true;
303
+        }
304
+
305
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
306
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
307
+
308
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
309
+        $fields = array('token' => $token);
310
+
311
+        $client = $this->clientService->newClient();
312
+
313
+        try {
314
+            $response = $client->post(
315
+                $url,
316
+                [
317
+                    'body' => $fields,
318
+                    'connect_timeout' => 10,
319
+                ]
320
+            );
321
+        } catch (\Exception $e) {
322
+            return false;
323
+        }
324
+
325
+        $status = json_decode($response->getBody(), true);
326
+
327
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
328
+    }
329
+
330
+    /**
331
+     * try send accept message to ocm end-point
332
+     *
333
+     * @param string $remoteDomain
334
+     * @param string $token
335
+     * @param $remoteId id of the share
336
+     * @param string $feedback
337
+     * @return bool
338
+     */
339
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
340
+        switch ($feedback) {
341
+            case 'accept':
342
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
343
+                $notification->setMessage(
344
+                    'SHARE_ACCEPTED',
345
+                    'file',
346
+                    $remoteId,
347
+                    [
348
+                        'sharedSecret' => $token,
349
+                        'message' => 'Recipient accept the share'
350
+                    ]
351
+
352
+                );
353
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
354
+            case 'decline':
355
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
356
+                $notification->setMessage(
357
+                    'SHARE_DECLINED',
358
+                    'file',
359
+                    $remoteId,
360
+                    [
361
+                        'sharedSecret' => $token,
362
+                        'message' => 'Recipient declined the share'
363
+                    ]
364
+
365
+                );
366
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
367
+        }
368
+
369
+        return false;
370
+
371
+    }
372
+
373
+
374
+    /**
375
+     * remove '/user/files' from the path and trailing slashes
376
+     *
377
+     * @param string $path
378
+     * @return string
379
+     */
380
+    protected function stripPath($path) {
381
+        $prefix = '/' . $this->uid . '/files';
382
+        return rtrim(substr($path, strlen($prefix)), '/');
383
+    }
384
+
385
+    public function getMount($data) {
386
+        $data['manager'] = $this;
387
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
388
+        $data['mountpoint'] = $mountPoint;
389
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
390
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
391
+    }
392
+
393
+    /**
394
+     * @param array $data
395
+     * @return Mount
396
+     */
397
+    protected function mountShare($data) {
398
+        $mount = $this->getMount($data);
399
+        $this->mountManager->addMount($mount);
400
+        return $mount;
401
+    }
402
+
403
+    /**
404
+     * @return \OC\Files\Mount\Manager
405
+     */
406
+    public function getMountManager() {
407
+        return $this->mountManager;
408
+    }
409
+
410
+    /**
411
+     * @param string $source
412
+     * @param string $target
413
+     * @return bool
414
+     */
415
+    public function setMountPoint($source, $target) {
416
+        $source = $this->stripPath($source);
417
+        $target = $this->stripPath($target);
418
+        $sourceHash = md5($source);
419
+        $targetHash = md5($target);
420
+
421
+        $query = $this->connection->prepare('
422 422
 			UPDATE `*PREFIX*share_external`
423 423
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
424 424
 			WHERE `mountpoint_hash` = ?
425 425
 			AND `user` = ?
426 426
 		');
427
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
427
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
428 428
 
429
-		return $result;
430
-	}
429
+        return $result;
430
+    }
431 431
 
432
-	public function removeShare($mountPoint) {
432
+    public function removeShare($mountPoint) {
433 433
 
434
-		$mountPointObj = $this->mountManager->find($mountPoint);
435
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
434
+        $mountPointObj = $this->mountManager->find($mountPoint);
435
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
436 436
 
437
-		$mountPoint = $this->stripPath($mountPoint);
438
-		$hash = md5($mountPoint);
437
+        $mountPoint = $this->stripPath($mountPoint);
438
+        $hash = md5($mountPoint);
439 439
 
440
-		$getShare = $this->connection->prepare('
440
+        $getShare = $this->connection->prepare('
441 441
 			SELECT `remote`, `share_token`, `remote_id`
442 442
 			FROM  `*PREFIX*share_external`
443 443
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
444
-		$result = $getShare->execute(array($hash, $this->uid));
445
-
446
-		if ($result) {
447
-			try {
448
-				$share = $getShare->fetch();
449
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
450
-			} catch (\Exception $e) {
451
-				// if we fail to notify the remote (probably cause the remote is down)
452
-				// we still want the share to be gone to prevent undeletable remotes
453
-			}
454
-		}
455
-		$getShare->closeCursor();
456
-
457
-		$query = $this->connection->prepare('
444
+        $result = $getShare->execute(array($hash, $this->uid));
445
+
446
+        if ($result) {
447
+            try {
448
+                $share = $getShare->fetch();
449
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
450
+            } catch (\Exception $e) {
451
+                // if we fail to notify the remote (probably cause the remote is down)
452
+                // we still want the share to be gone to prevent undeletable remotes
453
+            }
454
+        }
455
+        $getShare->closeCursor();
456
+
457
+        $query = $this->connection->prepare('
458 458
 			DELETE FROM `*PREFIX*share_external`
459 459
 			WHERE `mountpoint_hash` = ?
460 460
 			AND `user` = ?
461 461
 		');
462
-		$result = (bool)$query->execute(array($hash, $this->uid));
463
-
464
-		if($result) {
465
-			$this->removeReShares($id);
466
-		}
467
-
468
-		return $result;
469
-	}
470
-
471
-	/**
472
-	 * remove re-shares from share table and mapping in the federated_reshares table
473
-	 *
474
-	 * @param $mountPointId
475
-	 */
476
-	protected function removeReShares($mountPointId) {
477
-		$selectQuery = $this->connection->getQueryBuilder();
478
-		$query = $this->connection->getQueryBuilder();
479
-		$selectQuery->select('id')->from('share')
480
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
481
-		$select = $selectQuery->getSQL();
482
-
483
-
484
-		$query->delete('federated_reshares')
485
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
486
-		$query->execute();
487
-
488
-		$deleteReShares = $this->connection->getQueryBuilder();
489
-		$deleteReShares->delete('share')
490
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
491
-		$deleteReShares->execute();
492
-	}
493
-
494
-	/**
495
-	 * remove all shares for user $uid if the user was deleted
496
-	 *
497
-	 * @param string $uid
498
-	 * @return bool
499
-	 */
500
-	public function removeUserShares($uid) {
501
-		$getShare = $this->connection->prepare('
462
+        $result = (bool)$query->execute(array($hash, $this->uid));
463
+
464
+        if($result) {
465
+            $this->removeReShares($id);
466
+        }
467
+
468
+        return $result;
469
+    }
470
+
471
+    /**
472
+     * remove re-shares from share table and mapping in the federated_reshares table
473
+     *
474
+     * @param $mountPointId
475
+     */
476
+    protected function removeReShares($mountPointId) {
477
+        $selectQuery = $this->connection->getQueryBuilder();
478
+        $query = $this->connection->getQueryBuilder();
479
+        $selectQuery->select('id')->from('share')
480
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
481
+        $select = $selectQuery->getSQL();
482
+
483
+
484
+        $query->delete('federated_reshares')
485
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
486
+        $query->execute();
487
+
488
+        $deleteReShares = $this->connection->getQueryBuilder();
489
+        $deleteReShares->delete('share')
490
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
491
+        $deleteReShares->execute();
492
+    }
493
+
494
+    /**
495
+     * remove all shares for user $uid if the user was deleted
496
+     *
497
+     * @param string $uid
498
+     * @return bool
499
+     */
500
+    public function removeUserShares($uid) {
501
+        $getShare = $this->connection->prepare('
502 502
 			SELECT `remote`, `share_token`, `remote_id`
503 503
 			FROM  `*PREFIX*share_external`
504 504
 			WHERE `user` = ?');
505
-		$result = $getShare->execute(array($uid));
505
+        $result = $getShare->execute(array($uid));
506 506
 
507
-		if ($result) {
508
-			$shares = $getShare->fetchAll();
509
-			foreach($shares as $share) {
510
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
511
-			}
512
-		}
507
+        if ($result) {
508
+            $shares = $getShare->fetchAll();
509
+            foreach($shares as $share) {
510
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
511
+            }
512
+        }
513 513
 
514
-		$query = $this->connection->prepare('
514
+        $query = $this->connection->prepare('
515 515
 			DELETE FROM `*PREFIX*share_external`
516 516
 			WHERE `user` = ?
517 517
 		');
518
-		return (bool)$query->execute(array($uid));
519
-	}
520
-
521
-	/**
522
-	 * return a list of shares which are not yet accepted by the user
523
-	 *
524
-	 * @return array list of open server-to-server shares
525
-	 */
526
-	public function getOpenShares() {
527
-		return $this->getShares(false);
528
-	}
529
-
530
-	/**
531
-	 * return a list of shares which are accepted by the user
532
-	 *
533
-	 * @return array list of accepted server-to-server shares
534
-	 */
535
-	public function getAcceptedShares() {
536
-		return $this->getShares(true);
537
-	}
538
-
539
-	/**
540
-	 * return a list of shares for the user
541
-	 *
542
-	 * @param bool|null $accepted True for accepted only,
543
-	 *                            false for not accepted,
544
-	 *                            null for all shares of the user
545
-	 * @return array list of open server-to-server shares
546
-	 */
547
-	private function getShares($accepted) {
548
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
518
+        return (bool)$query->execute(array($uid));
519
+    }
520
+
521
+    /**
522
+     * return a list of shares which are not yet accepted by the user
523
+     *
524
+     * @return array list of open server-to-server shares
525
+     */
526
+    public function getOpenShares() {
527
+        return $this->getShares(false);
528
+    }
529
+
530
+    /**
531
+     * return a list of shares which are accepted by the user
532
+     *
533
+     * @return array list of accepted server-to-server shares
534
+     */
535
+    public function getAcceptedShares() {
536
+        return $this->getShares(true);
537
+    }
538
+
539
+    /**
540
+     * return a list of shares for the user
541
+     *
542
+     * @param bool|null $accepted True for accepted only,
543
+     *                            false for not accepted,
544
+     *                            null for all shares of the user
545
+     * @return array list of open server-to-server shares
546
+     */
547
+    private function getShares($accepted) {
548
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
549 549
 		          FROM `*PREFIX*share_external` 
550 550
 				  WHERE `user` = ?';
551
-		$parameters = [$this->uid];
552
-		if (!is_null($accepted)) {
553
-			$query .= ' AND `accepted` = ?';
554
-			$parameters[] = (int) $accepted;
555
-		}
556
-		$query .= ' ORDER BY `id` ASC';
557
-
558
-		$shares = $this->connection->prepare($query);
559
-		$result = $shares->execute($parameters);
560
-
561
-		return $result ? $shares->fetchAll() : [];
562
-	}
551
+        $parameters = [$this->uid];
552
+        if (!is_null($accepted)) {
553
+            $query .= ' AND `accepted` = ?';
554
+            $parameters[] = (int) $accepted;
555
+        }
556
+        $query .= ' ORDER BY `id` ASC';
557
+
558
+        $shares = $this->connection->prepare($query);
559
+        $result = $shares->execute($parameters);
560
+
561
+        return $result ? $shares->fetchAll() : [];
562
+    }
563 563
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -134,18 +134,18 @@  discard block
 block discarded – undo
134 134
 	 * @return Mount|null
135 135
 	 * @throws \Doctrine\DBAL\DBALException
136 136
 	 */
137
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
137
+	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = -1, $parent = -1) {
138 138
 
139 139
 		$user = $user ? $user : $this->uid;
140 140
 		$accepted = $accepted ? 1 : 0;
141
-		$name = Filesystem::normalizePath('/' . $name);
141
+		$name = Filesystem::normalizePath('/'.$name);
142 142
 
143 143
 		if (!$accepted) {
144 144
 			// To avoid conflicts with the mount point generation later,
145 145
 			// we only use a temporary mount point name here. The real
146 146
 			// mount point name will be generated when accepting the share,
147 147
 			// using the original share item name.
148
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
148
+			$tmpMountPointName = '{{TemporaryMountPointName#'.$name.'}}';
149 149
 			$mountPoint = $tmpMountPointName;
150 150
 			$hash = md5($tmpMountPointName);
151 151
 			$data = [
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			$i = 1;
166 166
 			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
167 167
 				// The external share already exists for the user
168
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
168
+				$data['mountpoint'] = $tmpMountPointName.'-'.$i;
169 169
 				$data['mountpoint_hash'] = md5($data['mountpoint']);
170 170
 				$i++;
171 171
 			}
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 		}
174 174
 
175 175
 		$mountPoint = Files::buildNotExistingFileName('/', $name);
176
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
176
+		$mountPoint = Filesystem::normalizePath('/'.$mountPoint);
177 177
 		$hash = md5($mountPoint);
178 178
 
179 179
 		$query = $this->connection->prepare('
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 			$mountPoint = Filesystem::normalizePath($mountPoint);
228 228
 			$hash = md5($mountPoint);
229 229
 
230
-			if($share['share_type'] === \OCP\Share::SHARE_TYPE_USER) {
230
+			if ($share['share_type'] === \OCP\Share::SHARE_TYPE_USER) {
231 231
 				$acceptShare = $this->connection->prepare('
232 232
 				UPDATE `*PREFIX*share_external`
233 233
 				SET `accepted` = ?,
@@ -298,14 +298,14 @@  discard block
 block discarded – undo
298 298
 
299 299
 		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
300 300
 
301
-		if($result === true) {
301
+		if ($result === true) {
302 302
 			return true;
303 303
 		}
304 304
 
305 305
 		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
306 306
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
307 307
 
308
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
308
+		$url = rtrim($remote, '/').$endpoint.'/'.$remoteId.'/'.$feedback.'?format='.\OCP\Share::RESPONSE_FORMAT;
309 309
 		$fields = array('token' => $token);
310 310
 
311 311
 		$client = $this->clientService->newClient();
@@ -378,13 +378,13 @@  discard block
 block discarded – undo
378 378
 	 * @return string
379 379
 	 */
380 380
 	protected function stripPath($path) {
381
-		$prefix = '/' . $this->uid . '/files';
381
+		$prefix = '/'.$this->uid.'/files';
382 382
 		return rtrim(substr($path, strlen($prefix)), '/');
383 383
 	}
384 384
 
385 385
 	public function getMount($data) {
386 386
 		$data['manager'] = $this;
387
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
387
+		$mountPoint = '/'.$this->uid.'/files'.$data['mountpoint'];
388 388
 		$data['mountpoint'] = $mountPoint;
389 389
 		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
390 390
 		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
 			WHERE `mountpoint_hash` = ?
425 425
 			AND `user` = ?
426 426
 		');
427
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
427
+		$result = (bool) $query->execute(array($target, $targetHash, $sourceHash, $this->uid));
428 428
 
429 429
 		return $result;
430 430
 	}
@@ -459,9 +459,9 @@  discard block
 block discarded – undo
459 459
 			WHERE `mountpoint_hash` = ?
460 460
 			AND `user` = ?
461 461
 		');
462
-		$result = (bool)$query->execute(array($hash, $this->uid));
462
+		$result = (bool) $query->execute(array($hash, $this->uid));
463 463
 
464
-		if($result) {
464
+		if ($result) {
465 465
 			$this->removeReShares($id);
466 466
 		}
467 467
 
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 
483 483
 
484 484
 		$query->delete('federated_reshares')
485
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
485
+			->where($query->expr()->in('share_id', $query->createFunction('('.$select.')')));
486 486
 		$query->execute();
487 487
 
488 488
 		$deleteReShares = $this->connection->getQueryBuilder();
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
 
507 507
 		if ($result) {
508 508
 			$shares = $getShare->fetchAll();
509
-			foreach($shares as $share) {
509
+			foreach ($shares as $share) {
510 510
 				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
511 511
 			}
512 512
 		}
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
 			DELETE FROM `*PREFIX*share_external`
516 516
 			WHERE `user` = ?
517 517
 		');
518
-		return (bool)$query->execute(array($uid));
518
+		return (bool) $query->execute(array($uid));
519 519
 	}
520 520
 
521 521
 	/**
Please login to merge, or discard this patch.