Completed
Pull Request — master (#9345)
by Björn
23:31
created
lib/private/Federation/CloudFederationProviderManager.php 1 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.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 1 patch
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -51,225 +51,225 @@
 block discarded – undo
51 51
  */
52 52
 class RequestHandlerController extends Controller {
53 53
 
54
-	/** @var ILogger */
55
-	private $logger;
54
+    /** @var ILogger */
55
+    private $logger;
56 56
 
57
-	/** @var IUserManager */
58
-	private $userManager;
57
+    /** @var IUserManager */
58
+    private $userManager;
59 59
 
60
-	/** @var IURLGenerator */
61
-	private $urlGenerator;
60
+    /** @var IURLGenerator */
61
+    private $urlGenerator;
62 62
 
63
-	/** @var ICloudFederationProviderManager */
64
-	private $cloudFederationProviderManager;
63
+    /** @var ICloudFederationProviderManager */
64
+    private $cloudFederationProviderManager;
65 65
 
66
-	/** @var Config */
67
-	private $config;
66
+    /** @var Config */
67
+    private $config;
68 68
 
69
-	/** @var ICloudFederationFactory */
70
-	private $factory;
69
+    /** @var ICloudFederationFactory */
70
+    private $factory;
71 71
 
72
-	/** @var ICloudIdManager */
73
-	private $cloudIdManager;
72
+    /** @var ICloudIdManager */
73
+    private $cloudIdManager;
74 74
 
75
-	public function __construct($appName,
76
-								IRequest $request,
77
-								ILogger $logger,
78
-								IUserManager $userManager,
79
-								IURLGenerator $urlGenerator,
80
-								ICloudFederationProviderManager $cloudFederationProviderManager,
81
-								Config $config,
82
-								ICloudFederationFactory $factory,
83
-								ICloudIdManager $cloudIdManager
84
-	) {
85
-		parent::__construct($appName, $request);
75
+    public function __construct($appName,
76
+                                IRequest $request,
77
+                                ILogger $logger,
78
+                                IUserManager $userManager,
79
+                                IURLGenerator $urlGenerator,
80
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
81
+                                Config $config,
82
+                                ICloudFederationFactory $factory,
83
+                                ICloudIdManager $cloudIdManager
84
+    ) {
85
+        parent::__construct($appName, $request);
86 86
 
87
-		$this->logger = $logger;
88
-		$this->userManager = $userManager;
89
-		$this->urlGenerator = $urlGenerator;
90
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
91
-		$this->config = $config;
92
-		$this->factory = $factory;
93
-		$this->cloudIdManager = $cloudIdManager;
94
-	}
87
+        $this->logger = $logger;
88
+        $this->userManager = $userManager;
89
+        $this->urlGenerator = $urlGenerator;
90
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
91
+        $this->config = $config;
92
+        $this->factory = $factory;
93
+        $this->cloudIdManager = $cloudIdManager;
94
+    }
95 95
 
96
-	/**
97
-	 * add share
98
-	 *
99
-	 * @NoCSRFRequired
100
-	 * @PublicPage
101
-	 * @BruteForceProtection(action=receiveFederatedShare)
102
-	 *
103
-	 * @param string $shareWith
104
-	 * @param string $name resource name (e.g. document.odt)
105
-	 * @param string $description share description (optional)
106
-	 * @param string $providerId resource UID on the provider side
107
-	 * @param string $owner provider specific UID of the user who owns the resource
108
-	 * @param string $ownerDisplayName display name of the user who shared the item
109
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
110
-	 * @param string $sharedByDisplayName display name of the user who shared the resource
111
-	 * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
112
-	 * @param string $shareType ('group' or 'user' share)
113
-	 * @param $resourceType ('file', 'calendar',...)
114
-	 * @return Http\DataResponse|JSONResponse
115
-	 *
116
-	 * 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
117
-	 */
118
-	public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
96
+    /**
97
+     * add share
98
+     *
99
+     * @NoCSRFRequired
100
+     * @PublicPage
101
+     * @BruteForceProtection(action=receiveFederatedShare)
102
+     *
103
+     * @param string $shareWith
104
+     * @param string $name resource name (e.g. document.odt)
105
+     * @param string $description share description (optional)
106
+     * @param string $providerId resource UID on the provider side
107
+     * @param string $owner provider specific UID of the user who owns the resource
108
+     * @param string $ownerDisplayName display name of the user who shared the item
109
+     * @param string $sharedBy provider specific UID of the user who shared the resource
110
+     * @param string $sharedByDisplayName display name of the user who shared the resource
111
+     * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
112
+     * @param string $shareType ('group' or 'user' share)
113
+     * @param $resourceType ('file', 'calendar',...)
114
+     * @return Http\DataResponse|JSONResponse
115
+     *
116
+     * 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
117
+     */
118
+    public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
119 119
 
120
-		// check if all required parameters are set
121
-		if ($shareWith === null ||
122
-			$name === null ||
123
-			$providerId === null ||
124
-			$owner === null ||
125
-			$resourceType === null ||
126
-			$shareType === null ||
127
-			!is_array($protocol) ||
128
-			!isset($protocol['name']) ||
129
-			!isset ($protocol['options']) ||
130
-			!is_array($protocol['options']) ||
131
-			!isset($protocol['options']['sharedSecret'])
132
-		) {
133
-			return new JSONResponse(
134
-				['message' => 'Missing arguments'],
135
-				Http::STATUS_BAD_REQUEST
136
-			);
137
-		}
120
+        // check if all required parameters are set
121
+        if ($shareWith === null ||
122
+            $name === null ||
123
+            $providerId === null ||
124
+            $owner === null ||
125
+            $resourceType === null ||
126
+            $shareType === null ||
127
+            !is_array($protocol) ||
128
+            !isset($protocol['name']) ||
129
+            !isset ($protocol['options']) ||
130
+            !is_array($protocol['options']) ||
131
+            !isset($protocol['options']['sharedSecret'])
132
+        ) {
133
+            return new JSONResponse(
134
+                ['message' => 'Missing arguments'],
135
+                Http::STATUS_BAD_REQUEST
136
+            );
137
+        }
138 138
 
139
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
140
-		$shareWithLocalId = $cloudId->getUser();
141
-		$shareWith = $this->mapUid($shareWithLocalId);
139
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
140
+        $shareWithLocalId = $cloudId->getUser();
141
+        $shareWith = $this->mapUid($shareWithLocalId);
142 142
 
143
-		if (!$this->userManager->userExists($shareWith)) {
144
-			return new JSONResponse(
145
-				['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
146
-				Http::STATUS_BAD_REQUEST
147
-			);
148
-		}
143
+        if (!$this->userManager->userExists($shareWith)) {
144
+            return new JSONResponse(
145
+                ['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
146
+                Http::STATUS_BAD_REQUEST
147
+            );
148
+        }
149 149
 
150
-		// if no explicit display name is given, we use the uid as display name
151
-		$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
152
-		$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
150
+        // if no explicit display name is given, we use the uid as display name
151
+        $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
152
+        $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
153 153
 
154
-		// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
155
-		if ($sharedBy === null) {
156
-			$sharedBy = $owner;
157
-			$sharedByDisplayName = $ownerDisplayName;
158
-		}
154
+        // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
155
+        if ($sharedBy === null) {
156
+            $sharedBy = $owner;
157
+            $sharedByDisplayName = $ownerDisplayName;
158
+        }
159 159
 
160
-		try {
161
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
162
-			$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
163
-			$share->setProtocol($protocol);
164
-			$id = $provider->shareReceived($share);
165
-		} catch (ProviderDoesNotExistsException $e) {
166
-			return new JSONResponse(
167
-				['message' => $e->getMessage()],
168
-				Http::STATUS_NOT_IMPLEMENTED
169
-			);
170
-		} catch (ProviderCouldNotAddShareException $e) {
171
-			return new JSONResponse(
172
-				['message' => $e->getMessage()],
173
-				$e->getCode()
174
-			);
175
-		} catch (\Exception $e) {
176
-			return new JSONResponse(
177
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
178
-				Http::STATUS_BAD_REQUEST
179
-			);
180
-		}
160
+        try {
161
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
162
+            $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
163
+            $share->setProtocol($protocol);
164
+            $id = $provider->shareReceived($share);
165
+        } catch (ProviderDoesNotExistsException $e) {
166
+            return new JSONResponse(
167
+                ['message' => $e->getMessage()],
168
+                Http::STATUS_NOT_IMPLEMENTED
169
+            );
170
+        } catch (ProviderCouldNotAddShareException $e) {
171
+            return new JSONResponse(
172
+                ['message' => $e->getMessage()],
173
+                $e->getCode()
174
+            );
175
+        } catch (\Exception $e) {
176
+            return new JSONResponse(
177
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
178
+                Http::STATUS_BAD_REQUEST
179
+            );
180
+        }
181 181
 
182
-		$user = $this->userManager->get($shareWithLocalId);
183
-		$recipientDisplayName = '';
184
-		if($user) {
185
-			$recipientDisplayName = $user->getDisplayName();
186
-		}
182
+        $user = $this->userManager->get($shareWithLocalId);
183
+        $recipientDisplayName = '';
184
+        if($user) {
185
+            $recipientDisplayName = $user->getDisplayName();
186
+        }
187 187
 
188
-		return new JSONResponse(
189
-			['recipientDisplayName' => $recipientDisplayName],
190
-			Http::STATUS_CREATED);
188
+        return new JSONResponse(
189
+            ['recipientDisplayName' => $recipientDisplayName],
190
+            Http::STATUS_CREATED);
191 191
 
192
-	}
192
+    }
193 193
 
194
-	/**
195
-	 * receive notification about existing share
196
-	 *
197
-	 * @NoCSRFRequired
198
-	 * @PublicPage
199
-	 * @BruteForceProtection(action=receiveFederatedShareNotification)
200
-	 *
201
-	 * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
202
-	 * @param string $resourceType (calendar, file, contact,...)
203
-	 * @param string $providerId id of the share
204
-	 * @param array $notification the actual payload of the notification
205
-	 * @return JSONResponse
206
-	 */
207
-	public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
194
+    /**
195
+     * receive notification about existing share
196
+     *
197
+     * @NoCSRFRequired
198
+     * @PublicPage
199
+     * @BruteForceProtection(action=receiveFederatedShareNotification)
200
+     *
201
+     * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
202
+     * @param string $resourceType (calendar, file, contact,...)
203
+     * @param string $providerId id of the share
204
+     * @param array $notification the actual payload of the notification
205
+     * @return JSONResponse
206
+     */
207
+    public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
208 208
 
209
-		// check if all required parameters are set
210
-		if ($notificationType === null ||
211
-			$resourceType === null ||
212
-			$providerId === null ||
213
-			!is_array($notification)
214
-		) {
215
-			return new JSONResponse(
216
-				['message' => 'Missing arguments'],
217
-				Http::STATUS_BAD_REQUEST
218
-			);
219
-		}
209
+        // check if all required parameters are set
210
+        if ($notificationType === null ||
211
+            $resourceType === null ||
212
+            $providerId === null ||
213
+            !is_array($notification)
214
+        ) {
215
+            return new JSONResponse(
216
+                ['message' => 'Missing arguments'],
217
+                Http::STATUS_BAD_REQUEST
218
+            );
219
+        }
220 220
 
221
-		try {
222
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
223
-			$result = $provider->notificationReceived($notificationType, $providerId, $notification);
224
-		} catch (ProviderDoesNotExistsException $e) {
225
-			return new JSONResponse(
226
-				['message' => $e->getMessage()],
227
-				Http::STATUS_BAD_REQUEST
228
-			);
229
-		} catch (ShareNotFound $e) {
230
-			return new JSONResponse(
231
-				['message' => $e->getMessage()],
232
-				Http::STATUS_BAD_REQUEST
233
-			);
234
-		} catch (ActionNotSupportedException $e) {
235
-			return new JSONResponse(
236
-				['message' => $e->getMessage()],
237
-				Http::STATUS_NOT_IMPLEMENTED
238
-			);
239
-		} catch (BadRequestException $e) {
240
-			return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
241
-		} catch (AuthenticationFailedException $e) {
242
-			return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
243
-		}
244
-		catch (\Exception $e) {
245
-			return new JSONResponse(
246
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
247
-				Http::STATUS_BAD_REQUEST
248
-			);
249
-		}
221
+        try {
222
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
223
+            $result = $provider->notificationReceived($notificationType, $providerId, $notification);
224
+        } catch (ProviderDoesNotExistsException $e) {
225
+            return new JSONResponse(
226
+                ['message' => $e->getMessage()],
227
+                Http::STATUS_BAD_REQUEST
228
+            );
229
+        } catch (ShareNotFound $e) {
230
+            return new JSONResponse(
231
+                ['message' => $e->getMessage()],
232
+                Http::STATUS_BAD_REQUEST
233
+            );
234
+        } catch (ActionNotSupportedException $e) {
235
+            return new JSONResponse(
236
+                ['message' => $e->getMessage()],
237
+                Http::STATUS_NOT_IMPLEMENTED
238
+            );
239
+        } catch (BadRequestException $e) {
240
+            return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
241
+        } catch (AuthenticationFailedException $e) {
242
+            return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
243
+        }
244
+        catch (\Exception $e) {
245
+            return new JSONResponse(
246
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
247
+                Http::STATUS_BAD_REQUEST
248
+            );
249
+        }
250 250
 
251
-		return new JSONResponse($result,Http::STATUS_CREATED);
251
+        return new JSONResponse($result,Http::STATUS_CREATED);
252 252
 
253
-	}
253
+    }
254 254
 
255
-	/**
256
-	 * map login name to internal LDAP UID if a LDAP backend is in use
257
-	 *
258
-	 * @param string $uid
259
-	 * @return string mixed
260
-	 */
261
-	private function mapUid($uid) {
262
-		\OC::$server->getURLGenerator()->linkToDocs('key');
263
-		// FIXME this should be a method in the user management instead
264
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
265
-		\OCP\Util::emitHook(
266
-			'\OCA\Files_Sharing\API\Server2Server',
267
-			'preLoginNameUsedAsUserName',
268
-			array('uid' => &$uid)
269
-		);
270
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
255
+    /**
256
+     * map login name to internal LDAP UID if a LDAP backend is in use
257
+     *
258
+     * @param string $uid
259
+     * @return string mixed
260
+     */
261
+    private function mapUid($uid) {
262
+        \OC::$server->getURLGenerator()->linkToDocs('key');
263
+        // FIXME this should be a method in the user management instead
264
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
265
+        \OCP\Util::emitHook(
266
+            '\OCA\Files_Sharing\API\Server2Server',
267
+            'preLoginNameUsedAsUserName',
268
+            array('uid' => &$uid)
269
+        );
270
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
271 271
 
272
-		return $uid;
273
-	}
272
+        return $uid;
273
+    }
274 274
 
275 275
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Config.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -35,23 +35,23 @@
 block discarded – undo
35 35
  */
36 36
 class Config {
37 37
 
38
-	/** @var ICloudFederationProviderManager */
39
-	private $cloudFederationProviderManager;
40
-
41
-	public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager) {
42
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
43
-	}
44
-
45
-	/**
46
-	 * get a list of supported share types
47
-	 *
48
-	 * @param string $resourceType
49
-	 * @return array
50
-	 * @throws \OCP\Federation\Exceptions\ProviderDoesNotExistsException
51
-	 */
52
-	public function getSupportedShareTypes($resourceType) {
53
-		$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
54
-		return $provider->getSupportedShareTypes();
55
-	}
38
+    /** @var ICloudFederationProviderManager */
39
+    private $cloudFederationProviderManager;
40
+
41
+    public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager) {
42
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
43
+    }
44
+
45
+    /**
46
+     * get a list of supported share types
47
+     *
48
+     * @param string $resourceType
49
+     * @return array
50
+     * @throws \OCP\Federation\Exceptions\ProviderDoesNotExistsException
51
+     */
52
+    public function getSupportedShareTypes($resourceType) {
53
+        $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
54
+        return $provider->getSupportedShareTypes();
55
+    }
56 56
 
57 57
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php 1 patch
Indentation   +722 added lines, -722 removed lines patch added patch discarded remove patch
@@ -50,726 +50,726 @@
 block discarded – undo
50 50
 
51 51
 class CloudFederationProviderFiles implements ICloudFederationProvider {
52 52
 
53
-	/** @var IAppManager */
54
-	private $appManager;
55
-
56
-	/** @var FederatedShareProvider */
57
-	private $federatedShareProvider;
58
-
59
-	/** @var AddressHandler */
60
-	private $addressHandler;
61
-
62
-	/** @var ILogger */
63
-	private $logger;
64
-
65
-	/** @var IUserManager */
66
-	private $userManager;
67
-
68
-	/** @var ICloudIdManager */
69
-	private $cloudIdManager;
70
-
71
-	/** @var IActivityManager */
72
-	private $activityManager;
73
-
74
-	/** @var INotificationManager */
75
-	private $notificationManager;
76
-
77
-	/** @var IURLGenerator */
78
-	private $urlGenerator;
79
-
80
-	/** @var ICloudFederationFactory */
81
-	private $cloudFederationFactory;
82
-
83
-	/** @var ICloudFederationProviderManager */
84
-	private $cloudFederationProviderManager;
85
-
86
-	/** @var IDBConnection */
87
-	private $connection;
88
-
89
-	/**
90
-	 * CloudFederationProvider constructor.
91
-	 *
92
-	 * @param IAppManager $appManager
93
-	 * @param FederatedShareProvider $federatedShareProvider
94
-	 * @param AddressHandler $addressHandler
95
-	 * @param ILogger $logger
96
-	 * @param IUserManager $userManager
97
-	 * @param ICloudIdManager $cloudIdManager
98
-	 * @param IActivityManager $activityManager
99
-	 * @param INotificationManager $notificationManager
100
-	 * @param IURLGenerator $urlGenerator
101
-	 * @param ICloudFederationFactory $cloudFederationFactory
102
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
103
-	 * @param IDBConnection $connection
104
-	 */
105
-	public function __construct(IAppManager $appManager,
106
-								FederatedShareProvider $federatedShareProvider,
107
-								AddressHandler $addressHandler,
108
-								ILogger $logger,
109
-								IUserManager $userManager,
110
-								ICloudIdManager $cloudIdManager,
111
-								IActivityManager $activityManager,
112
-								INotificationManager $notificationManager,
113
-								IURLGenerator $urlGenerator,
114
-								ICloudFederationFactory $cloudFederationFactory,
115
-								ICloudFederationProviderManager $cloudFederationProviderManager,
116
-								IDBConnection $connection
117
-	) {
118
-		$this->appManager = $appManager;
119
-		$this->federatedShareProvider = $federatedShareProvider;
120
-		$this->addressHandler = $addressHandler;
121
-		$this->logger = $logger;
122
-		$this->userManager = $userManager;
123
-		$this->cloudIdManager = $cloudIdManager;
124
-		$this->activityManager = $activityManager;
125
-		$this->notificationManager = $notificationManager;
126
-		$this->urlGenerator = $urlGenerator;
127
-		$this->cloudFederationFactory = $cloudFederationFactory;
128
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
129
-		$this->connection = $connection;
130
-	}
131
-
132
-
133
-
134
-	/**
135
-	 * @return string
136
-	 */
137
-	public function getShareType() {
138
-		return 'file';
139
-	}
140
-
141
-	/**
142
-	 * share received from another server
143
-	 *
144
-	 * @param ICloudFederationShare $share
145
-	 * @return string provider specific unique ID of the share
146
-	 *
147
-	 * @throws ProviderCouldNotAddShareException
148
-	 * @throws \OCP\AppFramework\QueryException
149
-	 * @throws \OC\HintException
150
-	 * @since 14.0.0
151
-	 */
152
-	public function shareReceived(ICloudFederationShare $share) {
153
-
154
-		if (!$this->isS2SEnabled(true)) {
155
-			throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
156
-		}
157
-
158
-		$protocol = $share->getProtocol();
159
-		if ($protocol['name'] !== 'webdav') {
160
-			throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
161
-		}
162
-
163
-		list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
164
-		// for backward compatibility make sure that the remote url stored in the
165
-		// database ends with a trailing slash
166
-		if (substr($remote, -1) !== '/') {
167
-			$remote = $remote . '/';
168
-		}
169
-
170
-		$token = $share->getShareSecret();
171
-		$name = $share->getResourceName();
172
-		$owner = $share->getOwnerDisplayName();
173
-		$sharedBy = $share->getSharedByDisplayName();
174
-		$shareWith = $share->getShareWith();
175
-		$remoteId = $share->getProviderId();
176
-		$sharedByFederatedId = $share->getSharedBy();
177
-		$ownerFederatedId = $share->getOwner();
178
-
179
-		// if no explicit information about the person who created the share was send
180
-		// we assume that the share comes from the owner
181
-		if ($sharedByFederatedId === null) {
182
-			$sharedBy = $owner;
183
-			$sharedByFederatedId = $ownerFederatedId;
184
-		}
185
-
186
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
187
-
188
-			if (!Util::isValidFileName($name)) {
189
-				throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
190
-			}
191
-
192
-			// FIXME this should be a method in the user management instead
193
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
194
-			Util::emitHook(
195
-				'\OCA\Files_Sharing\API\Server2Server',
196
-				'preLoginNameUsedAsUserName',
197
-				array('uid' => &$shareWith)
198
-			);
199
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
200
-
201
-			if (!$this->userManager->userExists($shareWith)) {
202
-				throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
203
-			}
204
-
205
-			\OC_Util::setupFS($shareWith);
206
-
207
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
208
-				\OC::$server->getDatabaseConnection(),
209
-				Filesystem::getMountManager(),
210
-				Filesystem::getLoader(),
211
-				\OC::$server->getHTTPClientService(),
212
-				\OC::$server->getNotificationManager(),
213
-				\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
214
-				\OC::$server->getCloudFederationProviderManager(),
215
-				\OC::$server->getCloudFederationFactory(),
216
-				$shareWith
217
-			);
218
-
219
-			try {
220
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
221
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
222
-
223
-				$event = $this->activityManager->generateEvent();
224
-				$event->setApp('files_sharing')
225
-					->setType('remote_share')
226
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
227
-					->setAffectedUser($shareWith)
228
-					->setObject('remote_share', (int)$shareId, $name);
229
-				\OC::$server->getActivityManager()->publish($event);
230
-
231
-				$notification = $this->notificationManager->createNotification();
232
-				$notification->setApp('files_sharing')
233
-					->setUser($shareWith)
234
-					->setDateTime(new \DateTime())
235
-					->setObject('remote_share', $shareId)
236
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
237
-
238
-				$declineAction = $notification->createAction();
239
-				$declineAction->setLabel('decline')
240
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
241
-				$notification->addAction($declineAction);
242
-
243
-				$acceptAction = $notification->createAction();
244
-				$acceptAction->setLabel('accept')
245
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
246
-				$notification->addAction($acceptAction);
247
-
248
-				$this->notificationManager->notify($notification);
249
-
250
-				return $shareId;
251
-			} catch (\Exception $e) {
252
-				$this->logger->logException($e, [
253
-					'message' => 'Server can not add remote share.',
254
-					'level' => ILogger::ERROR,
255
-					'app' => 'files_sharing'
256
-				]);
257
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
258
-			}
259
-		}
260
-
261
-		throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
262
-
263
-	}
264
-
265
-	/**
266
-	 * notification received from another server
267
-	 *
268
-	 * @param string $notificationType (e.g. SHARE_ACCEPTED)
269
-	 * @param string $providerId id of the share
270
-	 * @param array $notification payload of the notification
271
-	 * @return array data send back to the sender
272
-	 *
273
-	 * @throws ActionNotSupportedException
274
-	 * @throws AuthenticationFailedException
275
-	 * @throws BadRequestException
276
-	 * @throws \OC\HintException
277
-	 * @since 14.0.0
278
-	 */
279
-	public function notificationReceived($notificationType, $providerId, array $notification) {
280
-
281
-		switch ($notificationType) {
282
-			case 'SHARE_ACCEPTED':
283
-				return $this->shareAccepted($providerId, $notification);
284
-			case 'SHARE_DECLINED':
285
-				return $this->shareDeclined($providerId, $notification);
286
-			case 'SHARE_UNSHARED':
287
-				return $this->unshare($providerId, $notification);
288
-			case 'REQUEST_RESHARE':
289
-				return $this->reshareRequested($providerId, $notification);
290
-			case 'RESHARE_UNDO':
291
-				return $this->undoReshare($providerId, $notification);
292
-			case 'RESHARE_CHANGE_PERMISSION':
293
-				return $this->updateResharePermissions($providerId, $notification);
294
-		}
295
-
296
-
297
-		throw new BadRequestException([$notificationType]);
298
-	}
299
-
300
-	/**
301
-	 * process notification that the recipient accepted a share
302
-	 *
303
-	 * @param string $id
304
-	 * @param array $notification
305
-	 * @return array
306
-	 * @throws ActionNotSupportedException
307
-	 * @throws AuthenticationFailedException
308
-	 * @throws BadRequestException
309
-	 * @throws \OC\HintException
310
-	 */
311
-	private function shareAccepted($id, array $notification) {
312
-
313
-		if (!$this->isS2SEnabled()) {
314
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
315
-		}
316
-
317
-		if (!isset($notification['sharedSecret'])) {
318
-			throw new BadRequestException(['sharedSecret']);
319
-		}
320
-
321
-		$token = $notification['sharedSecret'];
322
-
323
-		$share = $this->federatedShareProvider->getShareById($id);
324
-
325
-		$this->verifyShare($share, $token);
326
-		$this->executeAcceptShare($share);
327
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
328
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
329
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
330
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
331
-			$notification->setMessage(
332
-				'SHARE_ACCEPTED',
333
-				'file',
334
-				$remoteId,
335
-				[
336
-					'sharedSecret' => $token,
337
-					'message' => 'Recipient accepted the re-share'
338
-				]
339
-
340
-			);
341
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
342
-
343
-		}
344
-
345
-		return [];
346
-	}
347
-
348
-	/**
349
-	 * @param IShare $share
350
-	 * @throws ShareNotFound
351
-	 */
352
-	protected function executeAcceptShare(IShare $share) {
353
-		try {
354
-			$fileId = (int)$share->getNode()->getId();
355
-			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
356
-		} catch (\Exception $e) {
357
-			throw new ShareNotFound();
358
-		}
359
-
360
-		$event = $this->activityManager->generateEvent();
361
-		$event->setApp('files_sharing')
362
-			->setType('remote_share')
363
-			->setAffectedUser($this->getCorrectUid($share))
364
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
365
-			->setObject('files', $fileId, $file)
366
-			->setLink($link);
367
-		$this->activityManager->publish($event);
368
-	}
369
-
370
-	/**
371
-	 * process notification that the recipient declined a share
372
-	 *
373
-	 * @param string $id
374
-	 * @param array $notification
375
-	 * @return array
376
-	 * @throws ActionNotSupportedException
377
-	 * @throws AuthenticationFailedException
378
-	 * @throws BadRequestException
379
-	 * @throws ShareNotFound
380
-	 * @throws \OC\HintException
381
-	 *
382
-	 */
383
-	protected function shareDeclined($id, array $notification) {
384
-
385
-		if (!$this->isS2SEnabled()) {
386
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
387
-		}
388
-
389
-		if (!isset($notification['sharedSecret'])) {
390
-			throw new BadRequestException(['sharedSecret']);
391
-		}
392
-
393
-		$token = $notification['sharedSecret'];
394
-
395
-		$share = $this->federatedShareProvider->getShareById($id);
396
-
397
-		$this->verifyShare($share, $token);
398
-
399
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
400
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
401
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
402
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
403
-			$notification->setMessage(
404
-				'SHARE_DECLINED',
405
-				'file',
406
-				$remoteId,
407
-				[
408
-					'sharedSecret' => $token,
409
-					'message' => 'Recipient declined the re-share'
410
-				]
411
-
412
-			);
413
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
414
-		}
415
-
416
-		$this->executeDeclineShare($share);
417
-
418
-		return [];
419
-
420
-	}
421
-
422
-	/**
423
-	 * delete declined share and create a activity
424
-	 *
425
-	 * @param IShare $share
426
-	 * @throws ShareNotFound
427
-	 */
428
-	protected function executeDeclineShare(IShare $share) {
429
-		$this->federatedShareProvider->removeShareFromTable($share);
430
-
431
-		try {
432
-			$fileId = (int)$share->getNode()->getId();
433
-			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
434
-		} catch (\Exception $e) {
435
-			throw new ShareNotFound();
436
-		}
437
-
438
-		$event = $this->activityManager->generateEvent();
439
-		$event->setApp('files_sharing')
440
-			->setType('remote_share')
441
-			->setAffectedUser($this->getCorrectUid($share))
442
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
443
-			->setObject('files', $fileId, $file)
444
-			->setLink($link);
445
-		$this->activityManager->publish($event);
446
-
447
-	}
448
-
449
-	/**
450
-	 * received the notification that the owner unshared a file from you
451
-	 *
452
-	 * @param string $id
453
-	 * @param array $notification
454
-	 * @return array
455
-	 * @throws AuthenticationFailedException
456
-	 * @throws BadRequestException
457
-	 */
458
-	private function undoReshare($id, array $notification) {
459
-		if (!isset($notification['sharedSecret'])) {
460
-			throw new BadRequestException(['sharedSecret']);
461
-		}
462
-		$token = $notification['sharedSecret'];
463
-
464
-		$share = $this->federatedShareProvider->getShareById($id);
465
-
466
-		$this->verifyShare($share, $token);
467
-		$this->federatedShareProvider->removeShareFromTable($share);
468
-		return [];
469
-	}
470
-
471
-	/**
472
-	 * unshare file from self
473
-	 *
474
-	 * @param string $id
475
-	 * @param array $notification
476
-	 * @return array
477
-	 * @throws ActionNotSupportedException
478
-	 * @throws BadRequestException
479
-	 */
480
-	private function unshare($id, array $notification) {
481
-
482
-		if (!$this->isS2SEnabled(true)) {
483
-			throw new ActionNotSupportedException("incoming shares disabled!");
484
-		}
485
-
486
-		if (!isset($notification['sharedSecret'])) {
487
-			throw new BadRequestException(['sharedSecret']);
488
-		}
489
-		$token = $notification['sharedSecret'];
490
-
491
-		$qb = $this->connection->getQueryBuilder();
492
-		$qb->select('*')
493
-			->from('share_external')
494
-			->where(
495
-				$qb->expr()->andX(
496
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
497
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
498
-				)
499
-			);
500
-
501
-		$result = $qb->execute();
502
-		$share = $result->fetch();
503
-		$result->closeCursor();
504
-
505
-		if ($token && $id && !empty($share)) {
506
-
507
-			$remote = $this->cleanupRemote($share['remote']);
508
-
509
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
510
-			$mountpoint = $share['mountpoint'];
511
-			$user = $share['user'];
512
-
513
-			$qb = $this->connection->getQueryBuilder();
514
-			$qb->delete('share_external')
515
-				->where(
516
-					$qb->expr()->andX(
517
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
518
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
519
-					)
520
-				);
521
-
522
-			$qb->execute();
523
-
524
-			if ($share['accepted']) {
525
-				$path = trim($mountpoint, '/');
526
-			} else {
527
-				$path = trim($share['name'], '/');
528
-			}
529
-
530
-			$notification = $this->notificationManager->createNotification();
531
-			$notification->setApp('files_sharing')
532
-				->setUser($share['user'])
533
-				->setObject('remote_share', (int)$share['id']);
534
-			$this->notificationManager->markProcessed($notification);
535
-
536
-			$event = $this->activityManager->generateEvent();
537
-			$event->setApp('files_sharing')
538
-				->setType('remote_share')
539
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
540
-				->setAffectedUser($user)
541
-				->setObject('remote_share', (int)$share['id'], $path);
542
-			\OC::$server->getActivityManager()->publish($event);
543
-		}
544
-
545
-		return [];
546
-	}
547
-
548
-	private function cleanupRemote($remote) {
549
-		$remote = substr($remote, strpos($remote, '://') + 3);
550
-
551
-		return rtrim($remote, '/');
552
-	}
553
-
554
-	/**
555
-	 * recipient of a share request to re-share the file with another user
556
-	 *
557
-	 * @param string $id
558
-	 * @param array $notification
559
-	 * @return array
560
-	 * @throws AuthenticationFailedException
561
-	 * @throws BadRequestException
562
-	 * @throws ProviderCouldNotAddShareException
563
-	 * @throws ShareNotFound
564
-	 */
565
-	protected function reshareRequested($id, array $notification) {
566
-
567
-		if (!isset($notification['sharedSecret'])) {
568
-			throw new BadRequestException(['sharedSecret']);
569
-		}
570
-		$token = $notification['sharedSecret'];
571
-
572
-		if (!isset($notification['shareWith'])) {
573
-			throw new BadRequestException(['shareWith']);
574
-		}
575
-		$shareWith = $notification['shareWith'];
576
-
577
-		if (!isset($notification['senderId'])) {
578
-			throw new BadRequestException(['senderId']);
579
-		}
580
-		$senderId = $notification['senderId'];
581
-
582
-		$share = $this->federatedShareProvider->getShareById($id);
583
-		// don't allow to share a file back to the owner
584
-		try {
585
-			list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
586
-			$owner = $share->getShareOwner();
587
-			$currentServer = $this->addressHandler->generateRemoteURL();
588
-			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
589
-				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
590
-			}
591
-		} catch (\Exception $e) {
592
-			throw new ProviderCouldNotAddShareException($e->getMessage());
593
-		}
594
-
595
-		$this->verifyShare($share, $token);
596
-
597
-		// check if re-sharing is allowed
598
-		if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
599
-			// the recipient of the initial share is now the initiator for the re-share
600
-			$share->setSharedBy($share->getSharedWith());
601
-			$share->setSharedWith($shareWith);
602
-			$result = $this->federatedShareProvider->create($share);
603
-			$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
604
-			return ['token' => $result->getToken(), 'providerId' => $result->getId()];
605
-		} else {
606
-			throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
607
-		}
608
-
609
-	}
610
-
611
-	/**
612
-	 * update permission of a re-share so that the share dialog shows the right
613
-	 * permission if the owner or the sender changes the permission
614
-	 *
615
-	 * @param string $id
616
-	 * @param array $notification
617
-	 * @return array
618
-	 * @throws AuthenticationFailedException
619
-	 * @throws BadRequestException
620
-	 */
621
-	protected function updateResharePermissions($id, array $notification) {
622
-
623
-		if (!isset($notification['sharedSecret'])) {
624
-			throw new BadRequestException(['sharedSecret']);
625
-		}
626
-		$token = $notification['sharedSecret'];
627
-
628
-		if (!isset($notification['permission'])) {
629
-			throw new BadRequestException(['permission']);
630
-		}
631
-		$ocmPermissions = $notification['permission'];
632
-
633
-		$share = $this->federatedShareProvider->getShareById($id);
634
-
635
-		$ncPermission = $this->ocmPermissions2ncPermissions($ocmPermissions);
636
-
637
-		$this->verifyShare($share, $token);
638
-		$this->updatePermissionsInDatabase($share, $ncPermission);
639
-
640
-		return [];
641
-	}
642
-
643
-	/**
644
-	 * translate OCM Permissions to Nextcloud permissions
645
-	 *
646
-	 * @param array $ocmPermissions
647
-	 * @return int
648
-	 * @throws BadRequestException
649
-	 */
650
-	protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
651
-		$ncPermissions = 0;
652
-		foreach($ocmPermissions as $permission) {
653
-			switch (strtolower($permission)) {
654
-				case 'read':
655
-					$ncPermissions += Constants::PERMISSION_READ;
656
-					break;
657
-				case 'write':
658
-					$ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
659
-					break;
660
-				case 'share':
661
-					$ncPermissions += Constants::PERMISSION_SHARE;
662
-					break;
663
-				default:
664
-					throw new BadRequestException(['permission']);
665
-			}
666
-
667
-			error_log("new permissions: " . $ncPermissions);
668
-		}
669
-
670
-		return $ncPermissions;
671
-	}
672
-
673
-	/**
674
-	 * update permissions in database
675
-	 *
676
-	 * @param IShare $share
677
-	 * @param int $permissions
678
-	 */
679
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
680
-		$query = $this->connection->getQueryBuilder();
681
-		$query->update('share')
682
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
683
-			->set('permissions', $query->createNamedParameter($permissions))
684
-			->execute();
685
-	}
686
-
687
-
688
-	/**
689
-	 * get file
690
-	 *
691
-	 * @param string $user
692
-	 * @param int $fileSource
693
-	 * @return array with internal path of the file and a absolute link to it
694
-	 */
695
-	private function getFile($user, $fileSource) {
696
-		\OC_Util::setupFS($user);
697
-
698
-		try {
699
-			$file = Filesystem::getPath($fileSource);
700
-		} catch (NotFoundException $e) {
701
-			$file = null;
702
-		}
703
-		$args = Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
704
-		$link = Util::linkToAbsolute('files', 'index.php', $args);
705
-
706
-		return [$file, $link];
707
-
708
-	}
709
-
710
-	/**
711
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
712
-	 *
713
-	 * @param IShare $share
714
-	 * @return string
715
-	 */
716
-	protected function getCorrectUid(IShare $share) {
717
-		if ($this->userManager->userExists($share->getShareOwner())) {
718
-			return $share->getShareOwner();
719
-		}
720
-
721
-		return $share->getSharedBy();
722
-	}
723
-
724
-
725
-
726
-	/**
727
-	 * check if we got the right share
728
-	 *
729
-	 * @param IShare $share
730
-	 * @param string $token
731
-	 * @return bool
732
-	 * @throws AuthenticationFailedException
733
-	 */
734
-	protected function verifyShare(IShare $share, $token) {
735
-		if (
736
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
737
-			$share->getToken() === $token
738
-		) {
739
-			return true;
740
-		}
741
-
742
-		throw new AuthenticationFailedException();
743
-	}
744
-
745
-
746
-
747
-	/**
748
-	 * check if server-to-server sharing is enabled
749
-	 *
750
-	 * @param bool $incoming
751
-	 * @return bool
752
-	 */
753
-	private function isS2SEnabled($incoming = false) {
754
-
755
-		$result = $this->appManager->isEnabledForUser('files_sharing');
756
-
757
-		if ($incoming) {
758
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
759
-		} else {
760
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
761
-		}
762
-
763
-		return $result;
764
-	}
765
-
766
-
767
-	/**
768
-	 * get the supported share types, e.g. "user", "group", etc.
769
-	 *
770
-	 * @return array
771
-	 */
772
-	public function getSupportedShareTypes() {
773
-		return ['user'];
774
-	}
53
+    /** @var IAppManager */
54
+    private $appManager;
55
+
56
+    /** @var FederatedShareProvider */
57
+    private $federatedShareProvider;
58
+
59
+    /** @var AddressHandler */
60
+    private $addressHandler;
61
+
62
+    /** @var ILogger */
63
+    private $logger;
64
+
65
+    /** @var IUserManager */
66
+    private $userManager;
67
+
68
+    /** @var ICloudIdManager */
69
+    private $cloudIdManager;
70
+
71
+    /** @var IActivityManager */
72
+    private $activityManager;
73
+
74
+    /** @var INotificationManager */
75
+    private $notificationManager;
76
+
77
+    /** @var IURLGenerator */
78
+    private $urlGenerator;
79
+
80
+    /** @var ICloudFederationFactory */
81
+    private $cloudFederationFactory;
82
+
83
+    /** @var ICloudFederationProviderManager */
84
+    private $cloudFederationProviderManager;
85
+
86
+    /** @var IDBConnection */
87
+    private $connection;
88
+
89
+    /**
90
+     * CloudFederationProvider constructor.
91
+     *
92
+     * @param IAppManager $appManager
93
+     * @param FederatedShareProvider $federatedShareProvider
94
+     * @param AddressHandler $addressHandler
95
+     * @param ILogger $logger
96
+     * @param IUserManager $userManager
97
+     * @param ICloudIdManager $cloudIdManager
98
+     * @param IActivityManager $activityManager
99
+     * @param INotificationManager $notificationManager
100
+     * @param IURLGenerator $urlGenerator
101
+     * @param ICloudFederationFactory $cloudFederationFactory
102
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
103
+     * @param IDBConnection $connection
104
+     */
105
+    public function __construct(IAppManager $appManager,
106
+                                FederatedShareProvider $federatedShareProvider,
107
+                                AddressHandler $addressHandler,
108
+                                ILogger $logger,
109
+                                IUserManager $userManager,
110
+                                ICloudIdManager $cloudIdManager,
111
+                                IActivityManager $activityManager,
112
+                                INotificationManager $notificationManager,
113
+                                IURLGenerator $urlGenerator,
114
+                                ICloudFederationFactory $cloudFederationFactory,
115
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
116
+                                IDBConnection $connection
117
+    ) {
118
+        $this->appManager = $appManager;
119
+        $this->federatedShareProvider = $federatedShareProvider;
120
+        $this->addressHandler = $addressHandler;
121
+        $this->logger = $logger;
122
+        $this->userManager = $userManager;
123
+        $this->cloudIdManager = $cloudIdManager;
124
+        $this->activityManager = $activityManager;
125
+        $this->notificationManager = $notificationManager;
126
+        $this->urlGenerator = $urlGenerator;
127
+        $this->cloudFederationFactory = $cloudFederationFactory;
128
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
129
+        $this->connection = $connection;
130
+    }
131
+
132
+
133
+
134
+    /**
135
+     * @return string
136
+     */
137
+    public function getShareType() {
138
+        return 'file';
139
+    }
140
+
141
+    /**
142
+     * share received from another server
143
+     *
144
+     * @param ICloudFederationShare $share
145
+     * @return string provider specific unique ID of the share
146
+     *
147
+     * @throws ProviderCouldNotAddShareException
148
+     * @throws \OCP\AppFramework\QueryException
149
+     * @throws \OC\HintException
150
+     * @since 14.0.0
151
+     */
152
+    public function shareReceived(ICloudFederationShare $share) {
153
+
154
+        if (!$this->isS2SEnabled(true)) {
155
+            throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
156
+        }
157
+
158
+        $protocol = $share->getProtocol();
159
+        if ($protocol['name'] !== 'webdav') {
160
+            throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
161
+        }
162
+
163
+        list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
164
+        // for backward compatibility make sure that the remote url stored in the
165
+        // database ends with a trailing slash
166
+        if (substr($remote, -1) !== '/') {
167
+            $remote = $remote . '/';
168
+        }
169
+
170
+        $token = $share->getShareSecret();
171
+        $name = $share->getResourceName();
172
+        $owner = $share->getOwnerDisplayName();
173
+        $sharedBy = $share->getSharedByDisplayName();
174
+        $shareWith = $share->getShareWith();
175
+        $remoteId = $share->getProviderId();
176
+        $sharedByFederatedId = $share->getSharedBy();
177
+        $ownerFederatedId = $share->getOwner();
178
+
179
+        // if no explicit information about the person who created the share was send
180
+        // we assume that the share comes from the owner
181
+        if ($sharedByFederatedId === null) {
182
+            $sharedBy = $owner;
183
+            $sharedByFederatedId = $ownerFederatedId;
184
+        }
185
+
186
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
187
+
188
+            if (!Util::isValidFileName($name)) {
189
+                throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
190
+            }
191
+
192
+            // FIXME this should be a method in the user management instead
193
+            $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
194
+            Util::emitHook(
195
+                '\OCA\Files_Sharing\API\Server2Server',
196
+                'preLoginNameUsedAsUserName',
197
+                array('uid' => &$shareWith)
198
+            );
199
+            $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
200
+
201
+            if (!$this->userManager->userExists($shareWith)) {
202
+                throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
203
+            }
204
+
205
+            \OC_Util::setupFS($shareWith);
206
+
207
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
208
+                \OC::$server->getDatabaseConnection(),
209
+                Filesystem::getMountManager(),
210
+                Filesystem::getLoader(),
211
+                \OC::$server->getHTTPClientService(),
212
+                \OC::$server->getNotificationManager(),
213
+                \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
214
+                \OC::$server->getCloudFederationProviderManager(),
215
+                \OC::$server->getCloudFederationFactory(),
216
+                $shareWith
217
+            );
218
+
219
+            try {
220
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
221
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
222
+
223
+                $event = $this->activityManager->generateEvent();
224
+                $event->setApp('files_sharing')
225
+                    ->setType('remote_share')
226
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
227
+                    ->setAffectedUser($shareWith)
228
+                    ->setObject('remote_share', (int)$shareId, $name);
229
+                \OC::$server->getActivityManager()->publish($event);
230
+
231
+                $notification = $this->notificationManager->createNotification();
232
+                $notification->setApp('files_sharing')
233
+                    ->setUser($shareWith)
234
+                    ->setDateTime(new \DateTime())
235
+                    ->setObject('remote_share', $shareId)
236
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
237
+
238
+                $declineAction = $notification->createAction();
239
+                $declineAction->setLabel('decline')
240
+                    ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
241
+                $notification->addAction($declineAction);
242
+
243
+                $acceptAction = $notification->createAction();
244
+                $acceptAction->setLabel('accept')
245
+                    ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
246
+                $notification->addAction($acceptAction);
247
+
248
+                $this->notificationManager->notify($notification);
249
+
250
+                return $shareId;
251
+            } catch (\Exception $e) {
252
+                $this->logger->logException($e, [
253
+                    'message' => 'Server can not add remote share.',
254
+                    'level' => ILogger::ERROR,
255
+                    'app' => 'files_sharing'
256
+                ]);
257
+                throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
258
+            }
259
+        }
260
+
261
+        throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
262
+
263
+    }
264
+
265
+    /**
266
+     * notification received from another server
267
+     *
268
+     * @param string $notificationType (e.g. SHARE_ACCEPTED)
269
+     * @param string $providerId id of the share
270
+     * @param array $notification payload of the notification
271
+     * @return array data send back to the sender
272
+     *
273
+     * @throws ActionNotSupportedException
274
+     * @throws AuthenticationFailedException
275
+     * @throws BadRequestException
276
+     * @throws \OC\HintException
277
+     * @since 14.0.0
278
+     */
279
+    public function notificationReceived($notificationType, $providerId, array $notification) {
280
+
281
+        switch ($notificationType) {
282
+            case 'SHARE_ACCEPTED':
283
+                return $this->shareAccepted($providerId, $notification);
284
+            case 'SHARE_DECLINED':
285
+                return $this->shareDeclined($providerId, $notification);
286
+            case 'SHARE_UNSHARED':
287
+                return $this->unshare($providerId, $notification);
288
+            case 'REQUEST_RESHARE':
289
+                return $this->reshareRequested($providerId, $notification);
290
+            case 'RESHARE_UNDO':
291
+                return $this->undoReshare($providerId, $notification);
292
+            case 'RESHARE_CHANGE_PERMISSION':
293
+                return $this->updateResharePermissions($providerId, $notification);
294
+        }
295
+
296
+
297
+        throw new BadRequestException([$notificationType]);
298
+    }
299
+
300
+    /**
301
+     * process notification that the recipient accepted a share
302
+     *
303
+     * @param string $id
304
+     * @param array $notification
305
+     * @return array
306
+     * @throws ActionNotSupportedException
307
+     * @throws AuthenticationFailedException
308
+     * @throws BadRequestException
309
+     * @throws \OC\HintException
310
+     */
311
+    private function shareAccepted($id, array $notification) {
312
+
313
+        if (!$this->isS2SEnabled()) {
314
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
315
+        }
316
+
317
+        if (!isset($notification['sharedSecret'])) {
318
+            throw new BadRequestException(['sharedSecret']);
319
+        }
320
+
321
+        $token = $notification['sharedSecret'];
322
+
323
+        $share = $this->federatedShareProvider->getShareById($id);
324
+
325
+        $this->verifyShare($share, $token);
326
+        $this->executeAcceptShare($share);
327
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
328
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
329
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
330
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
331
+            $notification->setMessage(
332
+                'SHARE_ACCEPTED',
333
+                'file',
334
+                $remoteId,
335
+                [
336
+                    'sharedSecret' => $token,
337
+                    'message' => 'Recipient accepted the re-share'
338
+                ]
339
+
340
+            );
341
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
342
+
343
+        }
344
+
345
+        return [];
346
+    }
347
+
348
+    /**
349
+     * @param IShare $share
350
+     * @throws ShareNotFound
351
+     */
352
+    protected function executeAcceptShare(IShare $share) {
353
+        try {
354
+            $fileId = (int)$share->getNode()->getId();
355
+            list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
356
+        } catch (\Exception $e) {
357
+            throw new ShareNotFound();
358
+        }
359
+
360
+        $event = $this->activityManager->generateEvent();
361
+        $event->setApp('files_sharing')
362
+            ->setType('remote_share')
363
+            ->setAffectedUser($this->getCorrectUid($share))
364
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
365
+            ->setObject('files', $fileId, $file)
366
+            ->setLink($link);
367
+        $this->activityManager->publish($event);
368
+    }
369
+
370
+    /**
371
+     * process notification that the recipient declined a share
372
+     *
373
+     * @param string $id
374
+     * @param array $notification
375
+     * @return array
376
+     * @throws ActionNotSupportedException
377
+     * @throws AuthenticationFailedException
378
+     * @throws BadRequestException
379
+     * @throws ShareNotFound
380
+     * @throws \OC\HintException
381
+     *
382
+     */
383
+    protected function shareDeclined($id, array $notification) {
384
+
385
+        if (!$this->isS2SEnabled()) {
386
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
387
+        }
388
+
389
+        if (!isset($notification['sharedSecret'])) {
390
+            throw new BadRequestException(['sharedSecret']);
391
+        }
392
+
393
+        $token = $notification['sharedSecret'];
394
+
395
+        $share = $this->federatedShareProvider->getShareById($id);
396
+
397
+        $this->verifyShare($share, $token);
398
+
399
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
400
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
401
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
402
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
403
+            $notification->setMessage(
404
+                'SHARE_DECLINED',
405
+                'file',
406
+                $remoteId,
407
+                [
408
+                    'sharedSecret' => $token,
409
+                    'message' => 'Recipient declined the re-share'
410
+                ]
411
+
412
+            );
413
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
414
+        }
415
+
416
+        $this->executeDeclineShare($share);
417
+
418
+        return [];
419
+
420
+    }
421
+
422
+    /**
423
+     * delete declined share and create a activity
424
+     *
425
+     * @param IShare $share
426
+     * @throws ShareNotFound
427
+     */
428
+    protected function executeDeclineShare(IShare $share) {
429
+        $this->federatedShareProvider->removeShareFromTable($share);
430
+
431
+        try {
432
+            $fileId = (int)$share->getNode()->getId();
433
+            list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
434
+        } catch (\Exception $e) {
435
+            throw new ShareNotFound();
436
+        }
437
+
438
+        $event = $this->activityManager->generateEvent();
439
+        $event->setApp('files_sharing')
440
+            ->setType('remote_share')
441
+            ->setAffectedUser($this->getCorrectUid($share))
442
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
443
+            ->setObject('files', $fileId, $file)
444
+            ->setLink($link);
445
+        $this->activityManager->publish($event);
446
+
447
+    }
448
+
449
+    /**
450
+     * received the notification that the owner unshared a file from you
451
+     *
452
+     * @param string $id
453
+     * @param array $notification
454
+     * @return array
455
+     * @throws AuthenticationFailedException
456
+     * @throws BadRequestException
457
+     */
458
+    private function undoReshare($id, array $notification) {
459
+        if (!isset($notification['sharedSecret'])) {
460
+            throw new BadRequestException(['sharedSecret']);
461
+        }
462
+        $token = $notification['sharedSecret'];
463
+
464
+        $share = $this->federatedShareProvider->getShareById($id);
465
+
466
+        $this->verifyShare($share, $token);
467
+        $this->federatedShareProvider->removeShareFromTable($share);
468
+        return [];
469
+    }
470
+
471
+    /**
472
+     * unshare file from self
473
+     *
474
+     * @param string $id
475
+     * @param array $notification
476
+     * @return array
477
+     * @throws ActionNotSupportedException
478
+     * @throws BadRequestException
479
+     */
480
+    private function unshare($id, array $notification) {
481
+
482
+        if (!$this->isS2SEnabled(true)) {
483
+            throw new ActionNotSupportedException("incoming shares disabled!");
484
+        }
485
+
486
+        if (!isset($notification['sharedSecret'])) {
487
+            throw new BadRequestException(['sharedSecret']);
488
+        }
489
+        $token = $notification['sharedSecret'];
490
+
491
+        $qb = $this->connection->getQueryBuilder();
492
+        $qb->select('*')
493
+            ->from('share_external')
494
+            ->where(
495
+                $qb->expr()->andX(
496
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
497
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
498
+                )
499
+            );
500
+
501
+        $result = $qb->execute();
502
+        $share = $result->fetch();
503
+        $result->closeCursor();
504
+
505
+        if ($token && $id && !empty($share)) {
506
+
507
+            $remote = $this->cleanupRemote($share['remote']);
508
+
509
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
510
+            $mountpoint = $share['mountpoint'];
511
+            $user = $share['user'];
512
+
513
+            $qb = $this->connection->getQueryBuilder();
514
+            $qb->delete('share_external')
515
+                ->where(
516
+                    $qb->expr()->andX(
517
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
518
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
519
+                    )
520
+                );
521
+
522
+            $qb->execute();
523
+
524
+            if ($share['accepted']) {
525
+                $path = trim($mountpoint, '/');
526
+            } else {
527
+                $path = trim($share['name'], '/');
528
+            }
529
+
530
+            $notification = $this->notificationManager->createNotification();
531
+            $notification->setApp('files_sharing')
532
+                ->setUser($share['user'])
533
+                ->setObject('remote_share', (int)$share['id']);
534
+            $this->notificationManager->markProcessed($notification);
535
+
536
+            $event = $this->activityManager->generateEvent();
537
+            $event->setApp('files_sharing')
538
+                ->setType('remote_share')
539
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
540
+                ->setAffectedUser($user)
541
+                ->setObject('remote_share', (int)$share['id'], $path);
542
+            \OC::$server->getActivityManager()->publish($event);
543
+        }
544
+
545
+        return [];
546
+    }
547
+
548
+    private function cleanupRemote($remote) {
549
+        $remote = substr($remote, strpos($remote, '://') + 3);
550
+
551
+        return rtrim($remote, '/');
552
+    }
553
+
554
+    /**
555
+     * recipient of a share request to re-share the file with another user
556
+     *
557
+     * @param string $id
558
+     * @param array $notification
559
+     * @return array
560
+     * @throws AuthenticationFailedException
561
+     * @throws BadRequestException
562
+     * @throws ProviderCouldNotAddShareException
563
+     * @throws ShareNotFound
564
+     */
565
+    protected function reshareRequested($id, array $notification) {
566
+
567
+        if (!isset($notification['sharedSecret'])) {
568
+            throw new BadRequestException(['sharedSecret']);
569
+        }
570
+        $token = $notification['sharedSecret'];
571
+
572
+        if (!isset($notification['shareWith'])) {
573
+            throw new BadRequestException(['shareWith']);
574
+        }
575
+        $shareWith = $notification['shareWith'];
576
+
577
+        if (!isset($notification['senderId'])) {
578
+            throw new BadRequestException(['senderId']);
579
+        }
580
+        $senderId = $notification['senderId'];
581
+
582
+        $share = $this->federatedShareProvider->getShareById($id);
583
+        // don't allow to share a file back to the owner
584
+        try {
585
+            list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
586
+            $owner = $share->getShareOwner();
587
+            $currentServer = $this->addressHandler->generateRemoteURL();
588
+            if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
589
+                throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
590
+            }
591
+        } catch (\Exception $e) {
592
+            throw new ProviderCouldNotAddShareException($e->getMessage());
593
+        }
594
+
595
+        $this->verifyShare($share, $token);
596
+
597
+        // check if re-sharing is allowed
598
+        if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
599
+            // the recipient of the initial share is now the initiator for the re-share
600
+            $share->setSharedBy($share->getSharedWith());
601
+            $share->setSharedWith($shareWith);
602
+            $result = $this->federatedShareProvider->create($share);
603
+            $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
604
+            return ['token' => $result->getToken(), 'providerId' => $result->getId()];
605
+        } else {
606
+            throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
607
+        }
608
+
609
+    }
610
+
611
+    /**
612
+     * update permission of a re-share so that the share dialog shows the right
613
+     * permission if the owner or the sender changes the permission
614
+     *
615
+     * @param string $id
616
+     * @param array $notification
617
+     * @return array
618
+     * @throws AuthenticationFailedException
619
+     * @throws BadRequestException
620
+     */
621
+    protected function updateResharePermissions($id, array $notification) {
622
+
623
+        if (!isset($notification['sharedSecret'])) {
624
+            throw new BadRequestException(['sharedSecret']);
625
+        }
626
+        $token = $notification['sharedSecret'];
627
+
628
+        if (!isset($notification['permission'])) {
629
+            throw new BadRequestException(['permission']);
630
+        }
631
+        $ocmPermissions = $notification['permission'];
632
+
633
+        $share = $this->federatedShareProvider->getShareById($id);
634
+
635
+        $ncPermission = $this->ocmPermissions2ncPermissions($ocmPermissions);
636
+
637
+        $this->verifyShare($share, $token);
638
+        $this->updatePermissionsInDatabase($share, $ncPermission);
639
+
640
+        return [];
641
+    }
642
+
643
+    /**
644
+     * translate OCM Permissions to Nextcloud permissions
645
+     *
646
+     * @param array $ocmPermissions
647
+     * @return int
648
+     * @throws BadRequestException
649
+     */
650
+    protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
651
+        $ncPermissions = 0;
652
+        foreach($ocmPermissions as $permission) {
653
+            switch (strtolower($permission)) {
654
+                case 'read':
655
+                    $ncPermissions += Constants::PERMISSION_READ;
656
+                    break;
657
+                case 'write':
658
+                    $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
659
+                    break;
660
+                case 'share':
661
+                    $ncPermissions += Constants::PERMISSION_SHARE;
662
+                    break;
663
+                default:
664
+                    throw new BadRequestException(['permission']);
665
+            }
666
+
667
+            error_log("new permissions: " . $ncPermissions);
668
+        }
669
+
670
+        return $ncPermissions;
671
+    }
672
+
673
+    /**
674
+     * update permissions in database
675
+     *
676
+     * @param IShare $share
677
+     * @param int $permissions
678
+     */
679
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
680
+        $query = $this->connection->getQueryBuilder();
681
+        $query->update('share')
682
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
683
+            ->set('permissions', $query->createNamedParameter($permissions))
684
+            ->execute();
685
+    }
686
+
687
+
688
+    /**
689
+     * get file
690
+     *
691
+     * @param string $user
692
+     * @param int $fileSource
693
+     * @return array with internal path of the file and a absolute link to it
694
+     */
695
+    private function getFile($user, $fileSource) {
696
+        \OC_Util::setupFS($user);
697
+
698
+        try {
699
+            $file = Filesystem::getPath($fileSource);
700
+        } catch (NotFoundException $e) {
701
+            $file = null;
702
+        }
703
+        $args = Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
704
+        $link = Util::linkToAbsolute('files', 'index.php', $args);
705
+
706
+        return [$file, $link];
707
+
708
+    }
709
+
710
+    /**
711
+     * check if we are the initiator or the owner of a re-share and return the correct UID
712
+     *
713
+     * @param IShare $share
714
+     * @return string
715
+     */
716
+    protected function getCorrectUid(IShare $share) {
717
+        if ($this->userManager->userExists($share->getShareOwner())) {
718
+            return $share->getShareOwner();
719
+        }
720
+
721
+        return $share->getSharedBy();
722
+    }
723
+
724
+
725
+
726
+    /**
727
+     * check if we got the right share
728
+     *
729
+     * @param IShare $share
730
+     * @param string $token
731
+     * @return bool
732
+     * @throws AuthenticationFailedException
733
+     */
734
+    protected function verifyShare(IShare $share, $token) {
735
+        if (
736
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
737
+            $share->getToken() === $token
738
+        ) {
739
+            return true;
740
+        }
741
+
742
+        throw new AuthenticationFailedException();
743
+    }
744
+
745
+
746
+
747
+    /**
748
+     * check if server-to-server sharing is enabled
749
+     *
750
+     * @param bool $incoming
751
+     * @return bool
752
+     */
753
+    private function isS2SEnabled($incoming = false) {
754
+
755
+        $result = $this->appManager->isEnabledForUser('files_sharing');
756
+
757
+        if ($incoming) {
758
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
759
+        } else {
760
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
761
+        }
762
+
763
+        return $result;
764
+    }
765
+
766
+
767
+    /**
768
+     * get the supported share types, e.g. "user", "group", etc.
769
+     *
770
+     * @return array
771
+     */
772
+    public function getSupportedShareTypes() {
773
+        return ['user'];
774
+    }
775 775
 }
Please login to merge, or discard this patch.