Completed
Pull Request — master (#9895)
by Björn
168:09 queued 150:46
created
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   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -42,191 +42,191 @@
 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
-				$result = json_decode($response->getBody(), true);
149
-				return (is_array($result)) ? $result : [];
150
-			}
151
-
152
-		} catch (\Exception $e) {
153
-			// if flat re-sharing is not supported by the remote server
154
-			// we re-throw the exception and fall back to the old behaviour.
155
-			// (flat re-shares has been introduced in Nextcloud 9.1)
156
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
157
-				$this->logger->debug($e->getMessage());
158
-				throw $e;
159
-			}
160
-		}
161
-
162
-		return false;
163
-
164
-	}
165
-
166
-	/**
167
-	 * @param string $url
168
-	 * @param ICloudFederationNotification $notification
169
-	 * @return mixed
170
-	 */
171
-	public function sendNotification($url, ICloudFederationNotification $notification) {
172
-		$ocmEndPoint = $this->getOCMEndPoint($url);
173
-
174
-		if (empty($ocmEndPoint)) {
175
-			return false;
176
-		}
177
-
178
-		$client = $this->httpClientService->newClient();
179
-		try {
180
-			$response = $client->post($ocmEndPoint . '/notifications', [
181
-				'body' => $notification->getMessage(),
182
-				'timeout' => 10,
183
-				'connect_timeout' => 10,
184
-			]);
185
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
186
-				$result = json_decode($response->getBody(), true);
187
-				return (is_array($result)) ? $result : [];
188
-			}
189
-		} catch (\Exception $e) {
190
-			// log the error and return false
191
-			$this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
192
-		}
193
-
194
-		return false;
195
-	}
196
-
197
-	/**
198
-	 * check if the new cloud federation API is ready to be used
199
-	 *
200
-	 * @return bool
201
-	 */
202
-	public function isReady() {
203
-		return $this->appManager->isEnabledForUser('cloud_federation_api');
204
-	}
205
-	/**
206
-	 * check if server supports the new OCM api and ask for the correct end-point
207
-	 *
208
-	 * @param string $url full base URL of the cloud server
209
-	 * @return string
210
-	 */
211
-	protected function getOCMEndPoint($url) {
212
-		$client = $this->httpClientService->newClient();
213
-		try {
214
-			$response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
215
-		} catch (\Exception $e) {
216
-			return '';
217
-		}
218
-
219
-		$result = $response->getBody();
220
-		$result = json_decode($result, true);
221
-
222
-		$supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
223
-
224
-		if (isset($result['endPoint']) && $supportedVersion) {
225
-			return $result['endPoint'];
226
-		}
227
-
228
-		return '';
229
-	}
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
+                $result = json_decode($response->getBody(), true);
149
+                return (is_array($result)) ? $result : [];
150
+            }
151
+
152
+        } catch (\Exception $e) {
153
+            // if flat re-sharing is not supported by the remote server
154
+            // we re-throw the exception and fall back to the old behaviour.
155
+            // (flat re-shares has been introduced in Nextcloud 9.1)
156
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
157
+                $this->logger->debug($e->getMessage());
158
+                throw $e;
159
+            }
160
+        }
161
+
162
+        return false;
163
+
164
+    }
165
+
166
+    /**
167
+     * @param string $url
168
+     * @param ICloudFederationNotification $notification
169
+     * @return mixed
170
+     */
171
+    public function sendNotification($url, ICloudFederationNotification $notification) {
172
+        $ocmEndPoint = $this->getOCMEndPoint($url);
173
+
174
+        if (empty($ocmEndPoint)) {
175
+            return false;
176
+        }
177
+
178
+        $client = $this->httpClientService->newClient();
179
+        try {
180
+            $response = $client->post($ocmEndPoint . '/notifications', [
181
+                'body' => $notification->getMessage(),
182
+                'timeout' => 10,
183
+                'connect_timeout' => 10,
184
+            ]);
185
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
186
+                $result = json_decode($response->getBody(), true);
187
+                return (is_array($result)) ? $result : [];
188
+            }
189
+        } catch (\Exception $e) {
190
+            // log the error and return false
191
+            $this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
192
+        }
193
+
194
+        return false;
195
+    }
196
+
197
+    /**
198
+     * check if the new cloud federation API is ready to be used
199
+     *
200
+     * @return bool
201
+     */
202
+    public function isReady() {
203
+        return $this->appManager->isEnabledForUser('cloud_federation_api');
204
+    }
205
+    /**
206
+     * check if server supports the new OCM api and ask for the correct end-point
207
+     *
208
+     * @param string $url full base URL of the cloud server
209
+     * @return string
210
+     */
211
+    protected function getOCMEndPoint($url) {
212
+        $client = $this->httpClientService->newClient();
213
+        try {
214
+            $response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
215
+        } catch (\Exception $e) {
216
+            return '';
217
+        }
218
+
219
+        $result = $response->getBody();
220
+        $result = json_decode($result, true);
221
+
222
+        $supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
223
+
224
+        if (isset($result['endPoint']) && $supportedVersion) {
225
+            return $result['endPoint'];
226
+        }
227
+
228
+        return '';
229
+    }
230 230
 
231 231
 
232 232
 }
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   +244 added lines, -244 removed lines patch added patch discarded remove patch
@@ -52,249 +52,249 @@
 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
-		$shareWith = $cloudId->getUser();
155
-
156
-		if ($shareType === 'user') {
157
-			$shareWith = $this->mapUid($shareWith);
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($shareWith)) {
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($shareWith);
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
-		// FIXME this should be a method in the user management instead
289
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
290
-		\OCP\Util::emitHook(
291
-			'\OCA\Files_Sharing\API\Server2Server',
292
-			'preLoginNameUsedAsUserName',
293
-			array('uid' => &$uid)
294
-		);
295
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
296
-
297
-		return $uid;
298
-	}
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
+        $shareWith = $cloudId->getUser();
155
+
156
+        if ($shareType === 'user') {
157
+            $shareWith = $this->mapUid($shareWith);
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($shareWith)) {
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($shareWith);
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
+        // FIXME this should be a method in the user management instead
289
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
290
+        \OCP\Util::emitHook(
291
+            '\OCA\Files_Sharing\API\Server2Server',
292
+            'preLoginNameUsedAsUserName',
293
+            array('uid' => &$uid)
294
+        );
295
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
296
+
297
+        return $uid;
298
+    }
299 299
 
300 300
 }
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($shareWith)) {
168
+			if (!$this->groupManager->groupExists($shareWith)) {
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($shareWith);
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
 
@@ -286,13 +286,13 @@  discard block
 block discarded – undo
286 286
 	 */
287 287
 	private function mapUid($uid) {
288 288
 		// FIXME this should be a method in the user management instead
289
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
289
+		$this->logger->debug('shareWith before, '.$uid, ['app' => $this->appName]);
290 290
 		\OCP\Util::emitHook(
291 291
 			'\OCA\Files_Sharing\API\Server2Server',
292 292
 			'preLoginNameUsedAsUserName',
293 293
 			array('uid' => &$uid)
294 294
 		);
295
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
295
+		$this->logger->debug('shareWith after, '.$uid, ['app' => $this->appName]);
296 296
 
297 297
 		return $uid;
298 298
 	}
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 			$ocsStatus = isset($status['ocs']);
118 118
 			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119 119
 
120
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
120
+			if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
121 121
 				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122 122
 				return true;
123 123
 			}
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 			return [$ocmResult['token'], $ocmResult['providerId']];
161 161
 		}
162 162
 
163
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
163
+		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/'.$id.'/reshare', $fields);
164 164
 		$status = json_decode($result['result'], true);
165 165
 
166 166
 		$httpRequestSuccessful = $result['success'];
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172 172
 			return [
173 173
 				$status['ocs']['data']['token'],
174
-				(int)$status['ocs']['data']['remoteId']
174
+				(int) $status['ocs']['data']['remoteId']
175 175
 			];
176 176
 		}
177 177
 
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			$fields[$key] = $value;
259 259
 		}
260 260
 
261
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
261
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$remoteId.'/'.$action, $fields, $action);
262 262
 		$status = json_decode($result['result'], true);
263 263
 
264 264
 		if ($result['success'] &&
@@ -306,10 +306,10 @@  discard block
 block discarded – undo
306 306
 	 * @return array
307 307
 	 * @throws \Exception
308 308
 	 */
309
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
309
+	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
310 310
 
311 311
 		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
-			$remoteDomain = 'https://' . $remoteDomain;
312
+			$remoteDomain = 'https://'.$remoteDomain;
313 313
 		}
314 314
 
315 315
 		$result = [
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
349 349
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
350 350
 		try {
351
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
351
+			$response = $client->post($remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT, [
352 352
 				'body' => $fields,
353 353
 				'timeout' => 10,
354 354
 				'connect_timeout' => 10,
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 		switch ($action) {
406 406
 			case 'share':
407 407
 				$share = $this->cloudFederationFactory->getCloudFederationShare(
408
-					$fields['shareWith'] . '@' . $remoteDomain,
408
+					$fields['shareWith'].'@'.$remoteDomain,
409 409
 					$fields['name'],
410 410
 					'',
411 411
 					$fields['remoteId'],
Please login to merge, or discard this patch.
Indentation   +433 added lines, -433 removed lines patch added patch discarded remove patch
@@ -33,437 +33,437 @@
 block discarded – undo
33 33
 use OCP\OCS\IDiscoveryService;
34 34
 
35 35
 class Notifications {
36
-	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
-
38
-	/** @var AddressHandler */
39
-	private $addressHandler;
40
-
41
-	/** @var IClientService */
42
-	private $httpClientService;
43
-
44
-	/** @var IDiscoveryService */
45
-	private $discoveryService;
46
-
47
-	/** @var IJobList  */
48
-	private $jobList;
49
-
50
-	/** @var ICloudFederationProviderManager */
51
-	private $federationProviderManager;
52
-
53
-	/** @var ICloudFederationFactory */
54
-	private $cloudFederationFactory;
55
-
56
-	/**
57
-	 * @param AddressHandler $addressHandler
58
-	 * @param IClientService $httpClientService
59
-	 * @param IDiscoveryService $discoveryService
60
-	 * @param IJobList $jobList
61
-	 * @param ICloudFederationProviderManager $federationProviderManager
62
-	 * @param ICloudFederationFactory $cloudFederationFactory
63
-	 */
64
-	public function __construct(
65
-		AddressHandler $addressHandler,
66
-		IClientService $httpClientService,
67
-		IDiscoveryService $discoveryService,
68
-		IJobList $jobList,
69
-		ICloudFederationProviderManager $federationProviderManager,
70
-		ICloudFederationFactory $cloudFederationFactory
71
-	) {
72
-		$this->addressHandler = $addressHandler;
73
-		$this->httpClientService = $httpClientService;
74
-		$this->discoveryService = $discoveryService;
75
-		$this->jobList = $jobList;
76
-		$this->federationProviderManager = $federationProviderManager;
77
-		$this->cloudFederationFactory = $cloudFederationFactory;
78
-	}
79
-
80
-	/**
81
-	 * send server-to-server share to remote server
82
-	 *
83
-	 * @param string $token
84
-	 * @param string $shareWith
85
-	 * @param string $name
86
-	 * @param int $remote_id
87
-	 * @param string $owner
88
-	 * @param string $ownerFederatedId
89
-	 * @param string $sharedBy
90
-	 * @param string $sharedByFederatedId
91
-	 * @param int $shareType (can be a remote user or group share)
92
-	 * @return bool
93
-	 * @throws \OC\HintException
94
-	 * @throws \OC\ServerNotAvailableException
95
-	 */
96
-	public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
97
-
98
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
99
-
100
-		if ($user && $remote) {
101
-			$local = $this->addressHandler->generateRemoteURL();
102
-
103
-			$fields = array(
104
-				'shareWith' => $user,
105
-				'token' => $token,
106
-				'name' => $name,
107
-				'remoteId' => $remote_id,
108
-				'owner' => $owner,
109
-				'ownerFederatedId' => $ownerFederatedId,
110
-				'sharedBy' => $sharedBy,
111
-				'sharedByFederatedId' => $sharedByFederatedId,
112
-				'remote' => $local,
113
-				'shareType' => $shareType
114
-			);
115
-
116
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
117
-			$status = json_decode($result['result'], true);
118
-
119
-			$ocsStatus = isset($status['ocs']);
120
-			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
121
-
122
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
123
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
124
-				return true;
125
-			}
126
-
127
-		}
128
-
129
-		return false;
130
-	}
131
-
132
-	/**
133
-	 * ask owner to re-share the file with the given user
134
-	 *
135
-	 * @param string $token
136
-	 * @param int $id remote Id
137
-	 * @param int $shareId internal share Id
138
-	 * @param string $remote remote address of the owner
139
-	 * @param string $shareWith
140
-	 * @param int $permission
141
-	 * @param string $filename
142
-	 * @return bool
143
-	 * @throws \OC\HintException
144
-	 * @throws \OC\ServerNotAvailableException
145
-	 */
146
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
147
-
148
-		$fields = array(
149
-			'shareWith' => $shareWith,
150
-			'token' => $token,
151
-			'permission' => $permission,
152
-			'remoteId' => $shareId,
153
-		);
154
-
155
-		$ocmFields = $fields;
156
-		$ocmFields['remoteId'] = $id;
157
-		$ocmFields['localId'] = $shareId;
158
-		$ocmFields['name'] = $filename;
159
-
160
-		$ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
161
-		if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
162
-			return [$ocmResult['token'], $ocmResult['providerId']];
163
-		}
164
-
165
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
166
-		$status = json_decode($result['result'], true);
167
-
168
-		$httpRequestSuccessful = $result['success'];
169
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
170
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
171
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
172
-
173
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
174
-			return [
175
-				$status['ocs']['data']['token'],
176
-				(int)$status['ocs']['data']['remoteId']
177
-			];
178
-		}
179
-
180
-		return false;
181
-	}
182
-
183
-	/**
184
-	 * send server-to-server unshare to remote server
185
-	 *
186
-	 * @param string $remote url
187
-	 * @param int $id share id
188
-	 * @param string $token
189
-	 * @return bool
190
-	 */
191
-	public function sendRemoteUnShare($remote, $id, $token) {
192
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
193
-	}
194
-
195
-	/**
196
-	 * send server-to-server unshare to remote server
197
-	 *
198
-	 * @param string $remote url
199
-	 * @param int $id share id
200
-	 * @param string $token
201
-	 * @return bool
202
-	 */
203
-	public function sendRevokeShare($remote, $id, $token) {
204
-		$this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
205
-	}
206
-
207
-	/**
208
-	 * send notification to remote server if the permissions was changed
209
-	 *
210
-	 * @param string $remote
211
-	 * @param int $remoteId
212
-	 * @param string $token
213
-	 * @param int $permissions
214
-	 * @return bool
215
-	 */
216
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
217
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
218
-	}
219
-
220
-	/**
221
-	 * forward accept reShare to remote server
222
-	 *
223
-	 * @param string $remote
224
-	 * @param int $remoteId
225
-	 * @param string $token
226
-	 */
227
-	public function sendAcceptShare($remote, $remoteId, $token) {
228
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
229
-	}
230
-
231
-	/**
232
-	 * forward decline reShare to remote server
233
-	 *
234
-	 * @param string $remote
235
-	 * @param int $remoteId
236
-	 * @param string $token
237
-	 */
238
-	public function sendDeclineShare($remote, $remoteId, $token) {
239
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
240
-	}
241
-
242
-	/**
243
-	 * inform remote server whether server-to-server share was accepted/declined
244
-	 *
245
-	 * @param string $remote
246
-	 * @param string $token
247
-	 * @param int $remoteId Share id on the remote host
248
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
249
-	 * @param array $data
250
-	 * @param int $try
251
-	 * @return boolean
252
-	 */
253
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
254
-
255
-		$fields = [
256
-			'token' => $token,
257
-			'remoteId' => $remoteId
258
-			];
259
-		foreach ($data as $key => $value) {
260
-			$fields[$key] = $value;
261
-		}
262
-
263
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
264
-		$status = json_decode($result['result'], true);
265
-
266
-		if ($result['success'] &&
267
-			($status['ocs']['meta']['statuscode'] === 100 ||
268
-				$status['ocs']['meta']['statuscode'] === 200
269
-			)
270
-		) {
271
-			return true;
272
-		} elseif ($try === 0) {
273
-			// only add new job on first try
274
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
275
-				[
276
-					'remote' => $remote,
277
-					'remoteId' => $remoteId,
278
-					'token' => $token,
279
-					'action' => $action,
280
-					'data' => json_encode($data),
281
-					'try' => $try,
282
-					'lastRun' => $this->getTimestamp()
283
-				]
284
-			);
285
-		}
286
-
287
-		return false;
288
-	}
289
-
290
-
291
-	/**
292
-	 * return current timestamp
293
-	 *
294
-	 * @return int
295
-	 */
296
-	protected function getTimestamp() {
297
-		return time();
298
-	}
299
-
300
-	/**
301
-	 * try http post with the given protocol, if no protocol is given we pick
302
-	 * the secure one (https)
303
-	 *
304
-	 * @param string $remoteDomain
305
-	 * @param string $urlSuffix
306
-	 * @param array $fields post parameters
307
-	 * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
308
-	 * @return array
309
-	 * @throws \Exception
310
-	 */
311
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
312
-
313
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
314
-			$remoteDomain = 'https://' . $remoteDomain;
315
-		}
316
-
317
-		$result = [
318
-			'success' => false,
319
-			'result' => '',
320
-		];
321
-
322
-		// if possible we use the new OCM API
323
-		$ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
324
-		if (is_array($ocmResult)) {
325
-			$result['success'] = true;
326
-			$result['result'] = json_encode([
327
-				'ocs' => ['meta' => ['statuscode' => 200]]]);
328
-			return $result;
329
-		}
330
-
331
-		return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
332
-	}
333
-
334
-	/**
335
-	 * try old federated sharing API if the OCM api doesn't work
336
-	 *
337
-	 * @param $remoteDomain
338
-	 * @param $urlSuffix
339
-	 * @param array $fields
340
-	 * @return mixed
341
-	 * @throws \Exception
342
-	 */
343
-	protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
344
-
345
-		$result = [
346
-			'success' => false,
347
-			'result' => '',
348
-		];
349
-
350
-		// Fall back to old API
351
-		$client = $this->httpClientService->newClient();
352
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
353
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
354
-		try {
355
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
356
-				'body' => $fields,
357
-				'timeout' => 10,
358
-				'connect_timeout' => 10,
359
-			]);
360
-			$result['result'] = $response->getBody();
361
-			$result['success'] = true;
362
-		} catch (\Exception $e) {
363
-			// if flat re-sharing is not supported by the remote server
364
-			// we re-throw the exception and fall back to the old behaviour.
365
-			// (flat re-shares has been introduced in Nextcloud 9.1)
366
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
367
-				throw $e;
368
-			}
369
-		}
370
-
371
-		return $result;
372
-
373
-	}
374
-
375
-	/**
376
-	 * check if server supports the new OCM api and ask for the correct end-point
377
-	 *
378
-	 * @param string $url
379
-	 * @return string
380
-	 */
381
-	protected function getOCMEndPoint($url) {
382
-		$client = $this->httpClientService->newClient();
383
-		try {
384
-			$response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 10]);
385
-		} catch (\Exception $e) {
386
-			return '';
387
-		}
388
-
389
-		$result = $response->getBody();
390
-		$result = json_decode($result, true);
391
-
392
-		if (isset($result['end-point'])) {
393
-			return $result['end-point'];
394
-		}
395
-
396
-		return '';
397
-	}
398
-
399
-	/**
400
-	 * send action regarding federated sharing to the remote server using the OCM API
401
-	 *
402
-	 * @param $remoteDomain
403
-	 * @param $fields
404
-	 * @param $action
405
-	 *
406
-	 * @return bool
407
-	 */
408
-	protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
409
-		switch ($action) {
410
-			case 'share':
411
-				$share = $this->cloudFederationFactory->getCloudFederationShare(
412
-					$fields['shareWith'] . '@' . $remoteDomain,
413
-					$fields['name'],
414
-					'',
415
-					$fields['remoteId'],
416
-					$fields['ownerFederatedId'],
417
-					$fields['owner'],
418
-					$fields['sharedByFederatedId'],
419
-					$fields['sharedBy'],
420
-					$fields['token'],
421
-					$fields['shareType'],
422
-					'file'
423
-				);
424
-				return $this->federationProviderManager->sendShare($share);
425
-			case 'reshare':
426
-				// ask owner to reshare a file
427
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
428
-				$notification->setMessage('REQUEST_RESHARE',
429
-					'file',
430
-					$fields['remoteId'],
431
-					[
432
-						'sharedSecret' => $fields['token'],
433
-						'shareWith' => $fields['shareWith'],
434
-						'senderId' => $fields['localId'],
435
-						'shareType' => $fields['shareType'],
436
-						'message' => 'Ask owner to reshare the file'
437
-					]
438
-				);
439
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
440
-			case 'unshare':
441
-				//owner unshares the file from the recipient again
442
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
443
-				$notification->setMessage('SHARE_UNSHARED',
444
-					'file',
445
-					$fields['remoteId'],
446
-					[
447
-						'sharedSecret' => $fields['token'],
448
-						'messgage' => 'file is no longer shared with you'
449
-					]
450
-				);
451
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
452
-			case 'reshare_undo':
453
-				// if a reshare was unshared we send the information to the initiator/owner
454
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
455
-				$notification->setMessage('RESHARE_UNDO',
456
-					'file',
457
-					$fields['remoteId'],
458
-					[
459
-						'sharedSecret' => $fields['token'],
460
-						'message' => 'reshare was revoked'
461
-					]
462
-				);
463
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
464
-		}
465
-
466
-		return false;
467
-
468
-	}
36
+    const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
+
38
+    /** @var AddressHandler */
39
+    private $addressHandler;
40
+
41
+    /** @var IClientService */
42
+    private $httpClientService;
43
+
44
+    /** @var IDiscoveryService */
45
+    private $discoveryService;
46
+
47
+    /** @var IJobList  */
48
+    private $jobList;
49
+
50
+    /** @var ICloudFederationProviderManager */
51
+    private $federationProviderManager;
52
+
53
+    /** @var ICloudFederationFactory */
54
+    private $cloudFederationFactory;
55
+
56
+    /**
57
+     * @param AddressHandler $addressHandler
58
+     * @param IClientService $httpClientService
59
+     * @param IDiscoveryService $discoveryService
60
+     * @param IJobList $jobList
61
+     * @param ICloudFederationProviderManager $federationProviderManager
62
+     * @param ICloudFederationFactory $cloudFederationFactory
63
+     */
64
+    public function __construct(
65
+        AddressHandler $addressHandler,
66
+        IClientService $httpClientService,
67
+        IDiscoveryService $discoveryService,
68
+        IJobList $jobList,
69
+        ICloudFederationProviderManager $federationProviderManager,
70
+        ICloudFederationFactory $cloudFederationFactory
71
+    ) {
72
+        $this->addressHandler = $addressHandler;
73
+        $this->httpClientService = $httpClientService;
74
+        $this->discoveryService = $discoveryService;
75
+        $this->jobList = $jobList;
76
+        $this->federationProviderManager = $federationProviderManager;
77
+        $this->cloudFederationFactory = $cloudFederationFactory;
78
+    }
79
+
80
+    /**
81
+     * send server-to-server share to remote server
82
+     *
83
+     * @param string $token
84
+     * @param string $shareWith
85
+     * @param string $name
86
+     * @param int $remote_id
87
+     * @param string $owner
88
+     * @param string $ownerFederatedId
89
+     * @param string $sharedBy
90
+     * @param string $sharedByFederatedId
91
+     * @param int $shareType (can be a remote user or group share)
92
+     * @return bool
93
+     * @throws \OC\HintException
94
+     * @throws \OC\ServerNotAvailableException
95
+     */
96
+    public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
97
+
98
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
99
+
100
+        if ($user && $remote) {
101
+            $local = $this->addressHandler->generateRemoteURL();
102
+
103
+            $fields = array(
104
+                'shareWith' => $user,
105
+                'token' => $token,
106
+                'name' => $name,
107
+                'remoteId' => $remote_id,
108
+                'owner' => $owner,
109
+                'ownerFederatedId' => $ownerFederatedId,
110
+                'sharedBy' => $sharedBy,
111
+                'sharedByFederatedId' => $sharedByFederatedId,
112
+                'remote' => $local,
113
+                'shareType' => $shareType
114
+            );
115
+
116
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
117
+            $status = json_decode($result['result'], true);
118
+
119
+            $ocsStatus = isset($status['ocs']);
120
+            $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
121
+
122
+            if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
123
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
124
+                return true;
125
+            }
126
+
127
+        }
128
+
129
+        return false;
130
+    }
131
+
132
+    /**
133
+     * ask owner to re-share the file with the given user
134
+     *
135
+     * @param string $token
136
+     * @param int $id remote Id
137
+     * @param int $shareId internal share Id
138
+     * @param string $remote remote address of the owner
139
+     * @param string $shareWith
140
+     * @param int $permission
141
+     * @param string $filename
142
+     * @return bool
143
+     * @throws \OC\HintException
144
+     * @throws \OC\ServerNotAvailableException
145
+     */
146
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
147
+
148
+        $fields = array(
149
+            'shareWith' => $shareWith,
150
+            'token' => $token,
151
+            'permission' => $permission,
152
+            'remoteId' => $shareId,
153
+        );
154
+
155
+        $ocmFields = $fields;
156
+        $ocmFields['remoteId'] = $id;
157
+        $ocmFields['localId'] = $shareId;
158
+        $ocmFields['name'] = $filename;
159
+
160
+        $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
161
+        if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
162
+            return [$ocmResult['token'], $ocmResult['providerId']];
163
+        }
164
+
165
+        $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
166
+        $status = json_decode($result['result'], true);
167
+
168
+        $httpRequestSuccessful = $result['success'];
169
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
170
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
171
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
172
+
173
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
174
+            return [
175
+                $status['ocs']['data']['token'],
176
+                (int)$status['ocs']['data']['remoteId']
177
+            ];
178
+        }
179
+
180
+        return false;
181
+    }
182
+
183
+    /**
184
+     * send server-to-server unshare to remote server
185
+     *
186
+     * @param string $remote url
187
+     * @param int $id share id
188
+     * @param string $token
189
+     * @return bool
190
+     */
191
+    public function sendRemoteUnShare($remote, $id, $token) {
192
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
193
+    }
194
+
195
+    /**
196
+     * send server-to-server unshare to remote server
197
+     *
198
+     * @param string $remote url
199
+     * @param int $id share id
200
+     * @param string $token
201
+     * @return bool
202
+     */
203
+    public function sendRevokeShare($remote, $id, $token) {
204
+        $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
205
+    }
206
+
207
+    /**
208
+     * send notification to remote server if the permissions was changed
209
+     *
210
+     * @param string $remote
211
+     * @param int $remoteId
212
+     * @param string $token
213
+     * @param int $permissions
214
+     * @return bool
215
+     */
216
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
217
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
218
+    }
219
+
220
+    /**
221
+     * forward accept reShare to remote server
222
+     *
223
+     * @param string $remote
224
+     * @param int $remoteId
225
+     * @param string $token
226
+     */
227
+    public function sendAcceptShare($remote, $remoteId, $token) {
228
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
229
+    }
230
+
231
+    /**
232
+     * forward decline reShare to remote server
233
+     *
234
+     * @param string $remote
235
+     * @param int $remoteId
236
+     * @param string $token
237
+     */
238
+    public function sendDeclineShare($remote, $remoteId, $token) {
239
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
240
+    }
241
+
242
+    /**
243
+     * inform remote server whether server-to-server share was accepted/declined
244
+     *
245
+     * @param string $remote
246
+     * @param string $token
247
+     * @param int $remoteId Share id on the remote host
248
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
249
+     * @param array $data
250
+     * @param int $try
251
+     * @return boolean
252
+     */
253
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
254
+
255
+        $fields = [
256
+            'token' => $token,
257
+            'remoteId' => $remoteId
258
+            ];
259
+        foreach ($data as $key => $value) {
260
+            $fields[$key] = $value;
261
+        }
262
+
263
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
264
+        $status = json_decode($result['result'], true);
265
+
266
+        if ($result['success'] &&
267
+            ($status['ocs']['meta']['statuscode'] === 100 ||
268
+                $status['ocs']['meta']['statuscode'] === 200
269
+            )
270
+        ) {
271
+            return true;
272
+        } elseif ($try === 0) {
273
+            // only add new job on first try
274
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
275
+                [
276
+                    'remote' => $remote,
277
+                    'remoteId' => $remoteId,
278
+                    'token' => $token,
279
+                    'action' => $action,
280
+                    'data' => json_encode($data),
281
+                    'try' => $try,
282
+                    'lastRun' => $this->getTimestamp()
283
+                ]
284
+            );
285
+        }
286
+
287
+        return false;
288
+    }
289
+
290
+
291
+    /**
292
+     * return current timestamp
293
+     *
294
+     * @return int
295
+     */
296
+    protected function getTimestamp() {
297
+        return time();
298
+    }
299
+
300
+    /**
301
+     * try http post with the given protocol, if no protocol is given we pick
302
+     * the secure one (https)
303
+     *
304
+     * @param string $remoteDomain
305
+     * @param string $urlSuffix
306
+     * @param array $fields post parameters
307
+     * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
308
+     * @return array
309
+     * @throws \Exception
310
+     */
311
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
312
+
313
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
314
+            $remoteDomain = 'https://' . $remoteDomain;
315
+        }
316
+
317
+        $result = [
318
+            'success' => false,
319
+            'result' => '',
320
+        ];
321
+
322
+        // if possible we use the new OCM API
323
+        $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
324
+        if (is_array($ocmResult)) {
325
+            $result['success'] = true;
326
+            $result['result'] = json_encode([
327
+                'ocs' => ['meta' => ['statuscode' => 200]]]);
328
+            return $result;
329
+        }
330
+
331
+        return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
332
+    }
333
+
334
+    /**
335
+     * try old federated sharing API if the OCM api doesn't work
336
+     *
337
+     * @param $remoteDomain
338
+     * @param $urlSuffix
339
+     * @param array $fields
340
+     * @return mixed
341
+     * @throws \Exception
342
+     */
343
+    protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
344
+
345
+        $result = [
346
+            'success' => false,
347
+            'result' => '',
348
+        ];
349
+
350
+        // Fall back to old API
351
+        $client = $this->httpClientService->newClient();
352
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
353
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
354
+        try {
355
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
356
+                'body' => $fields,
357
+                'timeout' => 10,
358
+                'connect_timeout' => 10,
359
+            ]);
360
+            $result['result'] = $response->getBody();
361
+            $result['success'] = true;
362
+        } catch (\Exception $e) {
363
+            // if flat re-sharing is not supported by the remote server
364
+            // we re-throw the exception and fall back to the old behaviour.
365
+            // (flat re-shares has been introduced in Nextcloud 9.1)
366
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
367
+                throw $e;
368
+            }
369
+        }
370
+
371
+        return $result;
372
+
373
+    }
374
+
375
+    /**
376
+     * check if server supports the new OCM api and ask for the correct end-point
377
+     *
378
+     * @param string $url
379
+     * @return string
380
+     */
381
+    protected function getOCMEndPoint($url) {
382
+        $client = $this->httpClientService->newClient();
383
+        try {
384
+            $response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 10]);
385
+        } catch (\Exception $e) {
386
+            return '';
387
+        }
388
+
389
+        $result = $response->getBody();
390
+        $result = json_decode($result, true);
391
+
392
+        if (isset($result['end-point'])) {
393
+            return $result['end-point'];
394
+        }
395
+
396
+        return '';
397
+    }
398
+
399
+    /**
400
+     * send action regarding federated sharing to the remote server using the OCM API
401
+     *
402
+     * @param $remoteDomain
403
+     * @param $fields
404
+     * @param $action
405
+     *
406
+     * @return bool
407
+     */
408
+    protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
409
+        switch ($action) {
410
+            case 'share':
411
+                $share = $this->cloudFederationFactory->getCloudFederationShare(
412
+                    $fields['shareWith'] . '@' . $remoteDomain,
413
+                    $fields['name'],
414
+                    '',
415
+                    $fields['remoteId'],
416
+                    $fields['ownerFederatedId'],
417
+                    $fields['owner'],
418
+                    $fields['sharedByFederatedId'],
419
+                    $fields['sharedBy'],
420
+                    $fields['token'],
421
+                    $fields['shareType'],
422
+                    'file'
423
+                );
424
+                return $this->federationProviderManager->sendShare($share);
425
+            case 'reshare':
426
+                // ask owner to reshare a file
427
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
428
+                $notification->setMessage('REQUEST_RESHARE',
429
+                    'file',
430
+                    $fields['remoteId'],
431
+                    [
432
+                        'sharedSecret' => $fields['token'],
433
+                        'shareWith' => $fields['shareWith'],
434
+                        'senderId' => $fields['localId'],
435
+                        'shareType' => $fields['shareType'],
436
+                        'message' => 'Ask owner to reshare the file'
437
+                    ]
438
+                );
439
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
440
+            case 'unshare':
441
+                //owner unshares the file from the recipient again
442
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
443
+                $notification->setMessage('SHARE_UNSHARED',
444
+                    'file',
445
+                    $fields['remoteId'],
446
+                    [
447
+                        'sharedSecret' => $fields['token'],
448
+                        'messgage' => 'file is no longer shared with you'
449
+                    ]
450
+                );
451
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
452
+            case 'reshare_undo':
453
+                // if a reshare was unshared we send the information to the initiator/owner
454
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
455
+                $notification->setMessage('RESHARE_UNDO',
456
+                    'file',
457
+                    $fields['remoteId'],
458
+                    [
459
+                        'sharedSecret' => $fields['token'],
460
+                        'message' => 'reshare was revoked'
461
+                    ]
462
+                );
463
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
464
+        }
465
+
466
+        return false;
467
+
468
+    }
469 469
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -450,7 +450,7 @@
 block discarded – undo
450 450
 	/**
451 451
 	 * translate Nextcloud permissions to OCM Permissions
452 452
 	 *
453
-	 * @param $ncPermissions
453
+	 * @param integer $ncPermissions
454 454
 	 * @return array
455 455
 	 */
456 456
 	protected function ncPermissions2ocmPermissions($ncPermissions) {
Please login to merge, or discard this patch.
Indentation   +427 added lines, -427 removed lines patch added patch discarded remove patch
@@ -52,431 +52,431 @@
 block discarded – undo
52 52
 
53 53
 class RequestHandlerController extends OCSController {
54 54
 
55
-	/** @var FederatedShareProvider */
56
-	private $federatedShareProvider;
57
-
58
-	/** @var IDBConnection */
59
-	private $connection;
60
-
61
-	/** @var Share\IManager */
62
-	private $shareManager;
63
-
64
-	/** @var Notifications */
65
-	private $notifications;
66
-
67
-	/** @var AddressHandler */
68
-	private $addressHandler;
69
-
70
-	/** @var  IUserManager */
71
-	private $userManager;
72
-
73
-	/** @var string */
74
-	private $shareTable = 'share';
75
-
76
-	/** @var ICloudIdManager */
77
-	private $cloudIdManager;
78
-
79
-	/** @var ILogger */
80
-	private $logger;
81
-
82
-	/** @var ICloudFederationFactory */
83
-	private $cloudFederationFactory;
84
-
85
-	/** @var ICloudFederationProviderManager */
86
-	private $cloudFederationProviderManager;
87
-
88
-	/**
89
-	 * Server2Server constructor.
90
-	 *
91
-	 * @param string $appName
92
-	 * @param IRequest $request
93
-	 * @param FederatedShareProvider $federatedShareProvider
94
-	 * @param IDBConnection $connection
95
-	 * @param Share\IManager $shareManager
96
-	 * @param Notifications $notifications
97
-	 * @param AddressHandler $addressHandler
98
-	 * @param IUserManager $userManager
99
-	 * @param ICloudIdManager $cloudIdManager
100
-	 * @param ILogger $logger
101
-	 * @param ICloudFederationFactory $cloudFederationFactory
102
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
103
-	 */
104
-	public function __construct($appName,
105
-								IRequest $request,
106
-								FederatedShareProvider $federatedShareProvider,
107
-								IDBConnection $connection,
108
-								Share\IManager $shareManager,
109
-								Notifications $notifications,
110
-								AddressHandler $addressHandler,
111
-								IUserManager $userManager,
112
-								ICloudIdManager $cloudIdManager,
113
-								ILogger $logger,
114
-								ICloudFederationFactory $cloudFederationFactory,
115
-								ICloudFederationProviderManager $cloudFederationProviderManager
116
-	) {
117
-		parent::__construct($appName, $request);
118
-
119
-		$this->federatedShareProvider = $federatedShareProvider;
120
-		$this->connection = $connection;
121
-		$this->shareManager = $shareManager;
122
-		$this->notifications = $notifications;
123
-		$this->addressHandler = $addressHandler;
124
-		$this->userManager = $userManager;
125
-		$this->cloudIdManager = $cloudIdManager;
126
-		$this->logger = $logger;
127
-		$this->cloudFederationFactory = $cloudFederationFactory;
128
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
129
-	}
130
-
131
-	/**
132
-	 * @NoCSRFRequired
133
-	 * @PublicPage
134
-	 *
135
-	 * create a new share
136
-	 *
137
-	 * @return Http\DataResponse
138
-	 * @throws OCSException
139
-	 */
140
-	public function createShare() {
141
-
142
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
143
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
144
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
145
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
146
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
147
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
148
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
149
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
150
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
151
-
152
-		if ($ownerFederatedId === null) {
153
-			$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
154
-		}
155
-		// if the owner of the share and the initiator are the same user
156
-		// we also complete the federated share ID for the initiator
157
-		if ($sharedByFederatedId === null && $owner === $sharedBy) {
158
-			$sharedByFederatedId = $ownerFederatedId;
159
-		}
160
-
161
-		$share = $this->cloudFederationFactory->getCloudFederationShare(
162
-			$shareWith,
163
-			$name,
164
-			'',
165
-			$remoteId,
166
-			$ownerFederatedId,
167
-			$owner,
168
-			$sharedByFederatedId,
169
-			$sharedBy,
170
-			$token,
171
-			'user',
172
-			'file'
173
-		);
174
-
175
-		try {
176
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
177
-			$provider->shareReceived($share);
178
-		} catch (ProviderDoesNotExistsException $e) {
179
-			throw new OCSException('Server does not support federated cloud sharing', 503);
180
-		} catch (ProviderCouldNotAddShareException $e) {
181
-			throw new OCSException($e->getMessage(), 400);
182
-		} catch (\Exception $e) {
183
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
184
-		}
185
-
186
-		return new Http\DataResponse();
187
-	}
188
-
189
-	/**
190
-	 * @NoCSRFRequired
191
-	 * @PublicPage
192
-	 *
193
-	 * create re-share on behalf of another user
194
-	 *
195
-	 * @param int $id
196
-	 * @return Http\DataResponse
197
-	 * @throws OCSBadRequestException
198
-	 * @throws OCSException
199
-	 * @throws OCSForbiddenException
200
-	 */
201
-	public function reShare($id) {
202
-
203
-		$token = $this->request->getParam('token', null);
204
-		$shareWith = $this->request->getParam('shareWith', null);
205
-		$permission = (int)$this->request->getParam('permission', null);
206
-		$remoteId = (int)$this->request->getParam('remoteId', null);
207
-
208
-		if ($id === null ||
209
-			$token === null ||
210
-			$shareWith === null ||
211
-			$permission === null ||
212
-			$remoteId === null
213
-		) {
214
-			throw new OCSBadRequestException();
215
-		}
216
-
217
-		$notification = [
218
-			'sharedSecret' => $token,
219
-			'shareWith' => $shareWith,
220
-			'senderId' => $remoteId,
221
-			'message' => 'Recipient of a share ask the owner to reshare the file'
222
-		];
223
-
224
-		try {
225
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
226
-			list($newToken, $localId) = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
227
-			return new Http\DataResponse([
228
-				'token' => $newToken,
229
-				'remoteId' => $localId
230
-			]);
231
-		} catch (ProviderDoesNotExistsException $e) {
232
-			throw new OCSException('Server does not support federated cloud sharing', 503);
233
-		} catch (ShareNotFound $e) {
234
-			$this->logger->debug('Share not found: ' . $e->getMessage());
235
-		} catch (\Exception $e) {
236
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
237
-		}
238
-
239
-		throw new OCSBadRequestException();
240
-	}
241
-
242
-
243
-	/**
244
-	 * @NoCSRFRequired
245
-	 * @PublicPage
246
-	 *
247
-	 * accept server-to-server share
248
-	 *
249
-	 * @param int $id
250
-	 * @return Http\DataResponse
251
-	 * @throws OCSException
252
-	 * @throws ShareNotFound
253
-	 * @throws \OC\HintException
254
-	 */
255
-	public function acceptShare($id) {
256
-
257
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
258
-
259
-		$notification = [
260
-			'sharedSecret' => $token,
261
-			'message' => 'Recipient accept the share'
262
-		];
263
-
264
-		try {
265
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
266
-			$provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
267
-		} catch (ProviderDoesNotExistsException $e) {
268
-			throw new OCSException('Server does not support federated cloud sharing', 503);
269
-		} catch (ShareNotFound $e) {
270
-			$this->logger->debug('Share not found: ' . $e->getMessage());
271
-		} catch (\Exception $e) {
272
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
273
-		}
274
-
275
-		return new Http\DataResponse();
276
-	}
277
-
278
-	/**
279
-	 * @NoCSRFRequired
280
-	 * @PublicPage
281
-	 *
282
-	 * decline server-to-server share
283
-	 *
284
-	 * @param int $id
285
-	 * @return Http\DataResponse
286
-	 * @throws OCSException
287
-	 */
288
-	public function declineShare($id) {
289
-
290
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
291
-
292
-		$notification = [
293
-			'sharedSecret' => $token,
294
-			'message' => 'Recipient declined the share'
295
-		];
296
-
297
-		try {
298
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
299
-			$provider->notificationReceived('SHARE_DECLINED', $id, $notification);
300
-		} catch (ProviderDoesNotExistsException $e) {
301
-			throw new OCSException('Server does not support federated cloud sharing', 503);
302
-		} catch (ShareNotFound $e) {
303
-			$this->logger->debug('Share not found: ' . $e->getMessage());
304
-		} catch (\Exception $e) {
305
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
306
-		}
307
-
308
-		return new Http\DataResponse();
309
-	}
310
-
311
-	/**
312
-	 * @NoCSRFRequired
313
-	 * @PublicPage
314
-	 *
315
-	 * remove server-to-server share if it was unshared by the owner
316
-	 *
317
-	 * @param int $id
318
-	 * @return Http\DataResponse
319
-	 * @throws OCSException
320
-	 */
321
-	public function unshare($id) {
322
-
323
-		if (!$this->isS2SEnabled()) {
324
-			throw new OCSException('Server does not support federated cloud sharing', 503);
325
-		}
326
-
327
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
328
-
329
-		try {
330
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
331
-			$notification = ['sharedSecret' => $token];
332
-			$provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
333
-		} catch (\Exception $e) {
334
-			$this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
335
-		}
336
-
337
-		return new Http\DataResponse();
338
-	}
339
-
340
-	private function cleanupRemote($remote) {
341
-		$remote = substr($remote, strpos($remote, '://') + 3);
342
-
343
-		return rtrim($remote, '/');
344
-	}
345
-
346
-
347
-	/**
348
-	 * @NoCSRFRequired
349
-	 * @PublicPage
350
-	 *
351
-	 * federated share was revoked, either by the owner or the re-sharer
352
-	 *
353
-	 * @param int $id
354
-	 * @return Http\DataResponse
355
-	 * @throws OCSBadRequestException
356
-	 */
357
-	public function revoke($id) {
358
-
359
-		$token = $this->request->getParam('token');
360
-
361
-		try {
362
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
363
-			$notification = ['sharedSecret' => $token];
364
-			$provider->notificationReceived('RESHARE_UNDO', $id, $notification);
365
-			return new Http\DataResponse();
366
-		} catch (\Exception $e) {
367
-			throw new OCSBadRequestException();
368
-		}
369
-
370
-	}
371
-
372
-	/**
373
-	 * check if server-to-server sharing is enabled
374
-	 *
375
-	 * @param bool $incoming
376
-	 * @return bool
377
-	 */
378
-	private function isS2SEnabled($incoming = false) {
379
-
380
-		$result = \OCP\App::isEnabled('files_sharing');
381
-
382
-		if ($incoming) {
383
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
384
-		} else {
385
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
386
-		}
387
-
388
-		return $result;
389
-	}
390
-
391
-	/**
392
-	 * @NoCSRFRequired
393
-	 * @PublicPage
394
-	 *
395
-	 * update share information to keep federated re-shares in sync
396
-	 *
397
-	 * @param int $id
398
-	 * @return Http\DataResponse
399
-	 * @throws OCSBadRequestException
400
-	 */
401
-	public function updatePermissions($id) {
402
-		$token = $this->request->getParam('token', null);
403
-		$ncPermissions = $this->request->getParam('permissions', null);
404
-
405
-		try {
406
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
407
-			$ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions);
408
-			$notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions];
409
-			$provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification);
410
-		} catch (\Exception $e) {
411
-			$this->logger->debug($e->getMessage());
412
-			throw new OCSBadRequestException();
413
-		}
414
-
415
-		return new Http\DataResponse();
416
-	}
417
-
418
-	/**
419
-	 * translate Nextcloud permissions to OCM Permissions
420
-	 *
421
-	 * @param $ncPermissions
422
-	 * @return array
423
-	 */
424
-	protected function ncPermissions2ocmPermissions($ncPermissions) {
425
-
426
-		$ocmPermissions = [];
427
-
428
-		if ($ncPermissions & Constants::PERMISSION_SHARE) {
429
-			$ocmPermissions[] = 'share';
430
-		}
431
-
432
-		if ($ncPermissions & Constants::PERMISSION_READ) {
433
-			$ocmPermissions[] = 'read';
434
-		}
435
-
436
-		if (($ncPermissions & Constants::PERMISSION_CREATE) ||
437
-			($ncPermissions & Constants::PERMISSION_UPDATE)) {
438
-			$ocmPermissions[] = 'write';
439
-		}
440
-
441
-		return $ocmPermissions;
442
-
443
-	}
444
-
445
-	/**
446
-	 * @NoCSRFRequired
447
-	 * @PublicPage
448
-	 *
449
-	 * change the owner of a server-to-server share
450
-	 *
451
-	 * @param int $id
452
-	 * @return Http\DataResponse
453
-	 * @throws \InvalidArgumentException
454
-	 * @throws OCSException
455
-	 */
456
-	public function move($id) {
457
-
458
-		if (!$this->isS2SEnabled()) {
459
-			throw new OCSException('Server does not support federated cloud sharing', 503);
460
-		}
461
-
462
-		$token = $this->request->getParam('token');
463
-		$remote = $this->request->getParam('remote');
464
-		$newRemoteId = $this->request->getParam('remote_id', $id);
465
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
466
-
467
-		$qb = $this->connection->getQueryBuilder();
468
-		$query = $qb->update('share_external')
469
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
470
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
471
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
472
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
473
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
474
-		$affected = $query->execute();
475
-
476
-		if ($affected > 0) {
477
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
478
-		} else {
479
-			throw new OCSBadRequestException('Share not found or token invalid');
480
-		}
481
-	}
55
+    /** @var FederatedShareProvider */
56
+    private $federatedShareProvider;
57
+
58
+    /** @var IDBConnection */
59
+    private $connection;
60
+
61
+    /** @var Share\IManager */
62
+    private $shareManager;
63
+
64
+    /** @var Notifications */
65
+    private $notifications;
66
+
67
+    /** @var AddressHandler */
68
+    private $addressHandler;
69
+
70
+    /** @var  IUserManager */
71
+    private $userManager;
72
+
73
+    /** @var string */
74
+    private $shareTable = 'share';
75
+
76
+    /** @var ICloudIdManager */
77
+    private $cloudIdManager;
78
+
79
+    /** @var ILogger */
80
+    private $logger;
81
+
82
+    /** @var ICloudFederationFactory */
83
+    private $cloudFederationFactory;
84
+
85
+    /** @var ICloudFederationProviderManager */
86
+    private $cloudFederationProviderManager;
87
+
88
+    /**
89
+     * Server2Server constructor.
90
+     *
91
+     * @param string $appName
92
+     * @param IRequest $request
93
+     * @param FederatedShareProvider $federatedShareProvider
94
+     * @param IDBConnection $connection
95
+     * @param Share\IManager $shareManager
96
+     * @param Notifications $notifications
97
+     * @param AddressHandler $addressHandler
98
+     * @param IUserManager $userManager
99
+     * @param ICloudIdManager $cloudIdManager
100
+     * @param ILogger $logger
101
+     * @param ICloudFederationFactory $cloudFederationFactory
102
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
103
+     */
104
+    public function __construct($appName,
105
+                                IRequest $request,
106
+                                FederatedShareProvider $federatedShareProvider,
107
+                                IDBConnection $connection,
108
+                                Share\IManager $shareManager,
109
+                                Notifications $notifications,
110
+                                AddressHandler $addressHandler,
111
+                                IUserManager $userManager,
112
+                                ICloudIdManager $cloudIdManager,
113
+                                ILogger $logger,
114
+                                ICloudFederationFactory $cloudFederationFactory,
115
+                                ICloudFederationProviderManager $cloudFederationProviderManager
116
+    ) {
117
+        parent::__construct($appName, $request);
118
+
119
+        $this->federatedShareProvider = $federatedShareProvider;
120
+        $this->connection = $connection;
121
+        $this->shareManager = $shareManager;
122
+        $this->notifications = $notifications;
123
+        $this->addressHandler = $addressHandler;
124
+        $this->userManager = $userManager;
125
+        $this->cloudIdManager = $cloudIdManager;
126
+        $this->logger = $logger;
127
+        $this->cloudFederationFactory = $cloudFederationFactory;
128
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
129
+    }
130
+
131
+    /**
132
+     * @NoCSRFRequired
133
+     * @PublicPage
134
+     *
135
+     * create a new share
136
+     *
137
+     * @return Http\DataResponse
138
+     * @throws OCSException
139
+     */
140
+    public function createShare() {
141
+
142
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
143
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
144
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
145
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
146
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
147
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
148
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
149
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
150
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
151
+
152
+        if ($ownerFederatedId === null) {
153
+            $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
154
+        }
155
+        // if the owner of the share and the initiator are the same user
156
+        // we also complete the federated share ID for the initiator
157
+        if ($sharedByFederatedId === null && $owner === $sharedBy) {
158
+            $sharedByFederatedId = $ownerFederatedId;
159
+        }
160
+
161
+        $share = $this->cloudFederationFactory->getCloudFederationShare(
162
+            $shareWith,
163
+            $name,
164
+            '',
165
+            $remoteId,
166
+            $ownerFederatedId,
167
+            $owner,
168
+            $sharedByFederatedId,
169
+            $sharedBy,
170
+            $token,
171
+            'user',
172
+            'file'
173
+        );
174
+
175
+        try {
176
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
177
+            $provider->shareReceived($share);
178
+        } catch (ProviderDoesNotExistsException $e) {
179
+            throw new OCSException('Server does not support federated cloud sharing', 503);
180
+        } catch (ProviderCouldNotAddShareException $e) {
181
+            throw new OCSException($e->getMessage(), 400);
182
+        } catch (\Exception $e) {
183
+            throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
184
+        }
185
+
186
+        return new Http\DataResponse();
187
+    }
188
+
189
+    /**
190
+     * @NoCSRFRequired
191
+     * @PublicPage
192
+     *
193
+     * create re-share on behalf of another user
194
+     *
195
+     * @param int $id
196
+     * @return Http\DataResponse
197
+     * @throws OCSBadRequestException
198
+     * @throws OCSException
199
+     * @throws OCSForbiddenException
200
+     */
201
+    public function reShare($id) {
202
+
203
+        $token = $this->request->getParam('token', null);
204
+        $shareWith = $this->request->getParam('shareWith', null);
205
+        $permission = (int)$this->request->getParam('permission', null);
206
+        $remoteId = (int)$this->request->getParam('remoteId', null);
207
+
208
+        if ($id === null ||
209
+            $token === null ||
210
+            $shareWith === null ||
211
+            $permission === null ||
212
+            $remoteId === null
213
+        ) {
214
+            throw new OCSBadRequestException();
215
+        }
216
+
217
+        $notification = [
218
+            'sharedSecret' => $token,
219
+            'shareWith' => $shareWith,
220
+            'senderId' => $remoteId,
221
+            'message' => 'Recipient of a share ask the owner to reshare the file'
222
+        ];
223
+
224
+        try {
225
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
226
+            list($newToken, $localId) = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
227
+            return new Http\DataResponse([
228
+                'token' => $newToken,
229
+                'remoteId' => $localId
230
+            ]);
231
+        } catch (ProviderDoesNotExistsException $e) {
232
+            throw new OCSException('Server does not support federated cloud sharing', 503);
233
+        } catch (ShareNotFound $e) {
234
+            $this->logger->debug('Share not found: ' . $e->getMessage());
235
+        } catch (\Exception $e) {
236
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
237
+        }
238
+
239
+        throw new OCSBadRequestException();
240
+    }
241
+
242
+
243
+    /**
244
+     * @NoCSRFRequired
245
+     * @PublicPage
246
+     *
247
+     * accept server-to-server share
248
+     *
249
+     * @param int $id
250
+     * @return Http\DataResponse
251
+     * @throws OCSException
252
+     * @throws ShareNotFound
253
+     * @throws \OC\HintException
254
+     */
255
+    public function acceptShare($id) {
256
+
257
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
258
+
259
+        $notification = [
260
+            'sharedSecret' => $token,
261
+            'message' => 'Recipient accept the share'
262
+        ];
263
+
264
+        try {
265
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
266
+            $provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
267
+        } catch (ProviderDoesNotExistsException $e) {
268
+            throw new OCSException('Server does not support federated cloud sharing', 503);
269
+        } catch (ShareNotFound $e) {
270
+            $this->logger->debug('Share not found: ' . $e->getMessage());
271
+        } catch (\Exception $e) {
272
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
273
+        }
274
+
275
+        return new Http\DataResponse();
276
+    }
277
+
278
+    /**
279
+     * @NoCSRFRequired
280
+     * @PublicPage
281
+     *
282
+     * decline server-to-server share
283
+     *
284
+     * @param int $id
285
+     * @return Http\DataResponse
286
+     * @throws OCSException
287
+     */
288
+    public function declineShare($id) {
289
+
290
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
291
+
292
+        $notification = [
293
+            'sharedSecret' => $token,
294
+            'message' => 'Recipient declined the share'
295
+        ];
296
+
297
+        try {
298
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
299
+            $provider->notificationReceived('SHARE_DECLINED', $id, $notification);
300
+        } catch (ProviderDoesNotExistsException $e) {
301
+            throw new OCSException('Server does not support federated cloud sharing', 503);
302
+        } catch (ShareNotFound $e) {
303
+            $this->logger->debug('Share not found: ' . $e->getMessage());
304
+        } catch (\Exception $e) {
305
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
306
+        }
307
+
308
+        return new Http\DataResponse();
309
+    }
310
+
311
+    /**
312
+     * @NoCSRFRequired
313
+     * @PublicPage
314
+     *
315
+     * remove server-to-server share if it was unshared by the owner
316
+     *
317
+     * @param int $id
318
+     * @return Http\DataResponse
319
+     * @throws OCSException
320
+     */
321
+    public function unshare($id) {
322
+
323
+        if (!$this->isS2SEnabled()) {
324
+            throw new OCSException('Server does not support federated cloud sharing', 503);
325
+        }
326
+
327
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
328
+
329
+        try {
330
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
331
+            $notification = ['sharedSecret' => $token];
332
+            $provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
333
+        } catch (\Exception $e) {
334
+            $this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
335
+        }
336
+
337
+        return new Http\DataResponse();
338
+    }
339
+
340
+    private function cleanupRemote($remote) {
341
+        $remote = substr($remote, strpos($remote, '://') + 3);
342
+
343
+        return rtrim($remote, '/');
344
+    }
345
+
346
+
347
+    /**
348
+     * @NoCSRFRequired
349
+     * @PublicPage
350
+     *
351
+     * federated share was revoked, either by the owner or the re-sharer
352
+     *
353
+     * @param int $id
354
+     * @return Http\DataResponse
355
+     * @throws OCSBadRequestException
356
+     */
357
+    public function revoke($id) {
358
+
359
+        $token = $this->request->getParam('token');
360
+
361
+        try {
362
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
363
+            $notification = ['sharedSecret' => $token];
364
+            $provider->notificationReceived('RESHARE_UNDO', $id, $notification);
365
+            return new Http\DataResponse();
366
+        } catch (\Exception $e) {
367
+            throw new OCSBadRequestException();
368
+        }
369
+
370
+    }
371
+
372
+    /**
373
+     * check if server-to-server sharing is enabled
374
+     *
375
+     * @param bool $incoming
376
+     * @return bool
377
+     */
378
+    private function isS2SEnabled($incoming = false) {
379
+
380
+        $result = \OCP\App::isEnabled('files_sharing');
381
+
382
+        if ($incoming) {
383
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
384
+        } else {
385
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
386
+        }
387
+
388
+        return $result;
389
+    }
390
+
391
+    /**
392
+     * @NoCSRFRequired
393
+     * @PublicPage
394
+     *
395
+     * update share information to keep federated re-shares in sync
396
+     *
397
+     * @param int $id
398
+     * @return Http\DataResponse
399
+     * @throws OCSBadRequestException
400
+     */
401
+    public function updatePermissions($id) {
402
+        $token = $this->request->getParam('token', null);
403
+        $ncPermissions = $this->request->getParam('permissions', null);
404
+
405
+        try {
406
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
407
+            $ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions);
408
+            $notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions];
409
+            $provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification);
410
+        } catch (\Exception $e) {
411
+            $this->logger->debug($e->getMessage());
412
+            throw new OCSBadRequestException();
413
+        }
414
+
415
+        return new Http\DataResponse();
416
+    }
417
+
418
+    /**
419
+     * translate Nextcloud permissions to OCM Permissions
420
+     *
421
+     * @param $ncPermissions
422
+     * @return array
423
+     */
424
+    protected function ncPermissions2ocmPermissions($ncPermissions) {
425
+
426
+        $ocmPermissions = [];
427
+
428
+        if ($ncPermissions & Constants::PERMISSION_SHARE) {
429
+            $ocmPermissions[] = 'share';
430
+        }
431
+
432
+        if ($ncPermissions & Constants::PERMISSION_READ) {
433
+            $ocmPermissions[] = 'read';
434
+        }
435
+
436
+        if (($ncPermissions & Constants::PERMISSION_CREATE) ||
437
+            ($ncPermissions & Constants::PERMISSION_UPDATE)) {
438
+            $ocmPermissions[] = 'write';
439
+        }
440
+
441
+        return $ocmPermissions;
442
+
443
+    }
444
+
445
+    /**
446
+     * @NoCSRFRequired
447
+     * @PublicPage
448
+     *
449
+     * change the owner of a server-to-server share
450
+     *
451
+     * @param int $id
452
+     * @return Http\DataResponse
453
+     * @throws \InvalidArgumentException
454
+     * @throws OCSException
455
+     */
456
+    public function move($id) {
457
+
458
+        if (!$this->isS2SEnabled()) {
459
+            throw new OCSException('Server does not support federated cloud sharing', 503);
460
+        }
461
+
462
+        $token = $this->request->getParam('token');
463
+        $remote = $this->request->getParam('remote');
464
+        $newRemoteId = $this->request->getParam('remote_id', $id);
465
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
466
+
467
+        $qb = $this->connection->getQueryBuilder();
468
+        $query = $qb->update('share_external')
469
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
470
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
471
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
472
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
473
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
474
+        $affected = $query->execute();
475
+
476
+        if ($affected > 0) {
477
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
478
+        } else {
479
+            throw new OCSBadRequestException('Share not found or token invalid');
480
+        }
481
+    }
482 482
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
146 146
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
147 147
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
148
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
148
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
149 149
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
150 150
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
151 151
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 		} catch (ProviderCouldNotAddShareException $e) {
181 181
 			throw new OCSException($e->getMessage(), 400);
182 182
 		} catch (\Exception $e) {
183
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
183
+			throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
184 184
 		}
185 185
 
186 186
 		return new Http\DataResponse();
@@ -202,8 +202,8 @@  discard block
 block discarded – undo
202 202
 
203 203
 		$token = $this->request->getParam('token', null);
204 204
 		$shareWith = $this->request->getParam('shareWith', null);
205
-		$permission = (int)$this->request->getParam('permission', null);
206
-		$remoteId = (int)$this->request->getParam('remoteId', null);
205
+		$permission = (int) $this->request->getParam('permission', null);
206
+		$remoteId = (int) $this->request->getParam('remoteId', null);
207 207
 
208 208
 		if ($id === null ||
209 209
 			$token === null ||
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
 		} catch (ProviderDoesNotExistsException $e) {
232 232
 			throw new OCSException('Server does not support federated cloud sharing', 503);
233 233
 		} catch (ShareNotFound $e) {
234
-			$this->logger->debug('Share not found: ' . $e->getMessage());
234
+			$this->logger->debug('Share not found: '.$e->getMessage());
235 235
 		} catch (\Exception $e) {
236
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
236
+			$this->logger->debug('internal server error, can not process notification: '.$e->getMessage());
237 237
 		}
238 238
 
239 239
 		throw new OCSBadRequestException();
@@ -267,9 +267,9 @@  discard block
 block discarded – undo
267 267
 		} catch (ProviderDoesNotExistsException $e) {
268 268
 			throw new OCSException('Server does not support federated cloud sharing', 503);
269 269
 		} catch (ShareNotFound $e) {
270
-			$this->logger->debug('Share not found: ' . $e->getMessage());
270
+			$this->logger->debug('Share not found: '.$e->getMessage());
271 271
 		} catch (\Exception $e) {
272
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
272
+			$this->logger->debug('internal server error, can not process notification: '.$e->getMessage());
273 273
 		}
274 274
 
275 275
 		return new Http\DataResponse();
@@ -300,9 +300,9 @@  discard block
 block discarded – undo
300 300
 		} catch (ProviderDoesNotExistsException $e) {
301 301
 			throw new OCSException('Server does not support federated cloud sharing', 503);
302 302
 		} catch (ShareNotFound $e) {
303
-			$this->logger->debug('Share not found: ' . $e->getMessage());
303
+			$this->logger->debug('Share not found: '.$e->getMessage());
304 304
 		} catch (\Exception $e) {
305
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
305
+			$this->logger->debug('internal server error, can not process notification: '.$e->getMessage());
306 306
 		}
307 307
 
308 308
 		return new Http\DataResponse();
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 			$notification = ['sharedSecret' => $token];
332 332
 			$provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
333 333
 		} catch (\Exception $e) {
334
-			$this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
334
+			$this->logger->debug('processing unshare notification failed: '.$e->getMessage());
335 335
 		}
336 336
 
337 337
 		return new Http\DataResponse();
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 
405 405
 		try {
406 406
 			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
407
-			$ocmPermissions = $this->ncPermissions2ocmPermissions((int)$ncPermissions);
407
+			$ocmPermissions = $this->ncPermissions2ocmPermissions((int) $ncPermissions);
408 408
 			$notification = ['sharedSecret' => $token, 'permission' => $ocmPermissions];
409 409
 			$provider->notificationReceived('RESHARE_CHANGE_PERMISSION', $id, $notification);
410 410
 		} catch (\Exception $e) {
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 2 patches
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 		if ($remoteShare) {
193 193
 			try {
194 194
 				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
195
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
195
+				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_'.time());
196 196
 				$share->setId($shareId);
197 197
 				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
198 198
 				// remote share was create successfully if we get a valid token as return
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 			$failure = true;
273 273
 		}
274 274
 
275
-		if($failure) {
275
+		if ($failure) {
276 276
 			$this->removeShareFromTableById($shareId);
277 277
 			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
278 278
 				[$share->getNode()->getName(), $share->getSharedWith()]);
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
325 325
 		$result = $query->execute()->fetchAll();
326 326
 
327
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
327
+		if (isset($result[0]) && (int) $result[0]['remote_id'] > 0) {
328 328
 			return $result[0];
329 329
 		}
330 330
 
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 		$qb->execute();
367 367
 		$id = $qb->getLastInsertId();
368 368
 
369
-		return (int)$id;
369
+		return (int) $id;
370 370
 	}
371 371
 
372 372
 	/**
@@ -456,14 +456,14 @@  discard block
 block discarded – undo
456 456
 	public function getRemoteId(IShare $share) {
457 457
 		$query = $this->dbConnection->getQueryBuilder();
458 458
 		$query->select('remote_id')->from('federated_reshares')
459
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
459
+			->where($query->expr()->eq('share_id', $query->createNamedParameter((int) $share->getId())));
460 460
 		$data = $query->execute()->fetch();
461 461
 
462 462
 		if (!is_array($data) || !isset($data['remote_id'])) {
463 463
 			throw new ShareNotFound();
464 464
 		}
465 465
 
466
-		return (int)$data['remote_id'];
466
+		return (int) $data['remote_id'];
467 467
 	}
468 468
 
469 469
 	/**
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 			->orderBy('id');
495 495
 
496 496
 		$cursor = $qb->execute();
497
-		while($data = $cursor->fetch()) {
497
+		while ($data = $cursor->fetch()) {
498 498
 			$children[] = $this->createShareObject($data);
499 499
 		}
500 500
 		$cursor->closeCursor();
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
 			);
613 613
 		}
614 614
 
615
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
615
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
616 616
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
617 617
 
618 618
 		$qb->orderBy('id');
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
 
676 676
 		$cursor = $qb->execute();
677 677
 		$shares = [];
678
-		while($data = $cursor->fetch()) {
678
+		while ($data = $cursor->fetch()) {
679 679
 			$shares[] = $this->createShareObject($data);
680 680
 		}
681 681
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 		$cursor->closeCursor();
700 700
 
701 701
 		if ($data === false) {
702
-			throw new ShareNotFound('Can not find share with ID: ' . $id);
702
+			throw new ShareNotFound('Can not find share with ID: '.$id);
703 703
 		}
704 704
 
705 705
 		try {
@@ -727,7 +727,7 @@  discard block
 block discarded – undo
727 727
 			->execute();
728 728
 
729 729
 		$shares = [];
730
-		while($data = $cursor->fetch()) {
730
+		while ($data = $cursor->fetch()) {
731 731
 			$shares[] = $this->createShareObject($data);
732 732
 		}
733 733
 		$cursor->closeCursor();
@@ -766,7 +766,7 @@  discard block
 block discarded – undo
766 766
 
767 767
 		$cursor = $qb->execute();
768 768
 
769
-		while($data = $cursor->fetch()) {
769
+		while ($data = $cursor->fetch()) {
770 770
 			$shares[] = $this->createShareObject($data);
771 771
 		}
772 772
 		$cursor->closeCursor();
@@ -843,15 +843,15 @@  discard block
 block discarded – undo
843 843
 	private function createShareObject($data) {
844 844
 
845 845
 		$share = new Share($this->rootFolder, $this->userManager);
846
-		$share->setId((int)$data['id'])
847
-			->setShareType((int)$data['share_type'])
848
-			->setPermissions((int)$data['permissions'])
846
+		$share->setId((int) $data['id'])
847
+			->setShareType((int) $data['share_type'])
848
+			->setPermissions((int) $data['permissions'])
849 849
 			->setTarget($data['file_target'])
850
-			->setMailSend((bool)$data['mail_send'])
850
+			->setMailSend((bool) $data['mail_send'])
851 851
 			->setToken($data['token']);
852 852
 
853 853
 		$shareTime = new \DateTime();
854
-		$shareTime->setTimestamp((int)$data['stime']);
854
+		$shareTime->setTimestamp((int) $data['stime']);
855 855
 		$share->setShareTime($shareTime);
856 856
 		$share->setSharedWith($data['share_with']);
857 857
 
@@ -861,13 +861,13 @@  discard block
 block discarded – undo
861 861
 		} else {
862 862
 			//OLD SHARE
863 863
 			$share->setSharedBy($data['uid_owner']);
864
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
864
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
865 865
 
866 866
 			$owner = $path->getOwner();
867 867
 			$share->setShareOwner($owner->getUID());
868 868
 		}
869 869
 
870
-		$share->setNodeId((int)$data['file_source']);
870
+		$share->setNodeId((int) $data['file_source']);
871 871
 		$share->setNodeType($data['item_type']);
872 872
 
873 873
 		$share->setProviderId($this->identifier());
Please login to merge, or discard this patch.
Indentation   +1019 added lines, -1019 removed lines patch added patch discarded remove patch
@@ -54,1033 +54,1033 @@
 block discarded – undo
54 54
  */
55 55
 class FederatedShareProvider implements IShareProvider {
56 56
 
57
-	const SHARE_TYPE_REMOTE = 6;
58
-
59
-	/** @var IDBConnection */
60
-	private $dbConnection;
61
-
62
-	/** @var AddressHandler */
63
-	private $addressHandler;
64
-
65
-	/** @var Notifications */
66
-	private $notifications;
67
-
68
-	/** @var TokenHandler */
69
-	private $tokenHandler;
70
-
71
-	/** @var IL10N */
72
-	private $l;
73
-
74
-	/** @var ILogger */
75
-	private $logger;
76
-
77
-	/** @var IRootFolder */
78
-	private $rootFolder;
79
-
80
-	/** @var IConfig */
81
-	private $config;
82
-
83
-	/** @var string */
84
-	private $externalShareTable = 'share_external';
85
-
86
-	/** @var IUserManager */
87
-	private $userManager;
88
-
89
-	/** @var ICloudIdManager */
90
-	private $cloudIdManager;
91
-
92
-	/** @var \OCP\GlobalScale\IConfig */
93
-	private $gsConfig;
94
-
95
-	/** @var ICloudFederationProviderManager */
96
-	private $cloudFederationProviderManager;
97
-
98
-	/**
99
-	 * DefaultShareProvider constructor.
100
-	 *
101
-	 * @param IDBConnection $connection
102
-	 * @param AddressHandler $addressHandler
103
-	 * @param Notifications $notifications
104
-	 * @param TokenHandler $tokenHandler
105
-	 * @param IL10N $l10n
106
-	 * @param ILogger $logger
107
-	 * @param IRootFolder $rootFolder
108
-	 * @param IConfig $config
109
-	 * @param IUserManager $userManager
110
-	 * @param ICloudIdManager $cloudIdManager
111
-	 * @param \OCP\GlobalScale\IConfig $globalScaleConfig
112
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
113
-	 */
114
-	public function __construct(
115
-			IDBConnection $connection,
116
-			AddressHandler $addressHandler,
117
-			Notifications $notifications,
118
-			TokenHandler $tokenHandler,
119
-			IL10N $l10n,
120
-			ILogger $logger,
121
-			IRootFolder $rootFolder,
122
-			IConfig $config,
123
-			IUserManager $userManager,
124
-			ICloudIdManager $cloudIdManager,
125
-			\OCP\GlobalScale\IConfig $globalScaleConfig,
126
-			ICloudFederationProviderManager $cloudFederationProviderManager
127
-	) {
128
-		$this->dbConnection = $connection;
129
-		$this->addressHandler = $addressHandler;
130
-		$this->notifications = $notifications;
131
-		$this->tokenHandler = $tokenHandler;
132
-		$this->l = $l10n;
133
-		$this->logger = $logger;
134
-		$this->rootFolder = $rootFolder;
135
-		$this->config = $config;
136
-		$this->userManager = $userManager;
137
-		$this->cloudIdManager = $cloudIdManager;
138
-		$this->gsConfig = $globalScaleConfig;
139
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
140
-	}
141
-
142
-	/**
143
-	 * Return the identifier of this provider.
144
-	 *
145
-	 * @return string Containing only [a-zA-Z0-9]
146
-	 */
147
-	public function identifier() {
148
-		return 'ocFederatedSharing';
149
-	}
150
-
151
-	/**
152
-	 * Share a path
153
-	 *
154
-	 * @param IShare $share
155
-	 * @return IShare The share object
156
-	 * @throws ShareNotFound
157
-	 * @throws \Exception
158
-	 */
159
-	public function create(IShare $share) {
160
-
161
-		$shareWith = $share->getSharedWith();
162
-		$itemSource = $share->getNodeId();
163
-		$itemType = $share->getNodeType();
164
-		$permissions = $share->getPermissions();
165
-		$sharedBy = $share->getSharedBy();
166
-		$shareType = $share->getShareType();
167
-
168
-		if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE_GROUP &&
169
-			!$this->isOutgoingServer2serverGroupShareEnabled()
170
-		) {
171
-			$message = 'It is not allowed to send federated group shares from this server.';
172
-			$message_t = $this->l->t('It is not allowed to send federated group shares from this server.');
173
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
174
-			throw new \Exception($message_t);
175
-		}
176
-
177
-		/*
57
+    const SHARE_TYPE_REMOTE = 6;
58
+
59
+    /** @var IDBConnection */
60
+    private $dbConnection;
61
+
62
+    /** @var AddressHandler */
63
+    private $addressHandler;
64
+
65
+    /** @var Notifications */
66
+    private $notifications;
67
+
68
+    /** @var TokenHandler */
69
+    private $tokenHandler;
70
+
71
+    /** @var IL10N */
72
+    private $l;
73
+
74
+    /** @var ILogger */
75
+    private $logger;
76
+
77
+    /** @var IRootFolder */
78
+    private $rootFolder;
79
+
80
+    /** @var IConfig */
81
+    private $config;
82
+
83
+    /** @var string */
84
+    private $externalShareTable = 'share_external';
85
+
86
+    /** @var IUserManager */
87
+    private $userManager;
88
+
89
+    /** @var ICloudIdManager */
90
+    private $cloudIdManager;
91
+
92
+    /** @var \OCP\GlobalScale\IConfig */
93
+    private $gsConfig;
94
+
95
+    /** @var ICloudFederationProviderManager */
96
+    private $cloudFederationProviderManager;
97
+
98
+    /**
99
+     * DefaultShareProvider constructor.
100
+     *
101
+     * @param IDBConnection $connection
102
+     * @param AddressHandler $addressHandler
103
+     * @param Notifications $notifications
104
+     * @param TokenHandler $tokenHandler
105
+     * @param IL10N $l10n
106
+     * @param ILogger $logger
107
+     * @param IRootFolder $rootFolder
108
+     * @param IConfig $config
109
+     * @param IUserManager $userManager
110
+     * @param ICloudIdManager $cloudIdManager
111
+     * @param \OCP\GlobalScale\IConfig $globalScaleConfig
112
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
113
+     */
114
+    public function __construct(
115
+            IDBConnection $connection,
116
+            AddressHandler $addressHandler,
117
+            Notifications $notifications,
118
+            TokenHandler $tokenHandler,
119
+            IL10N $l10n,
120
+            ILogger $logger,
121
+            IRootFolder $rootFolder,
122
+            IConfig $config,
123
+            IUserManager $userManager,
124
+            ICloudIdManager $cloudIdManager,
125
+            \OCP\GlobalScale\IConfig $globalScaleConfig,
126
+            ICloudFederationProviderManager $cloudFederationProviderManager
127
+    ) {
128
+        $this->dbConnection = $connection;
129
+        $this->addressHandler = $addressHandler;
130
+        $this->notifications = $notifications;
131
+        $this->tokenHandler = $tokenHandler;
132
+        $this->l = $l10n;
133
+        $this->logger = $logger;
134
+        $this->rootFolder = $rootFolder;
135
+        $this->config = $config;
136
+        $this->userManager = $userManager;
137
+        $this->cloudIdManager = $cloudIdManager;
138
+        $this->gsConfig = $globalScaleConfig;
139
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
140
+    }
141
+
142
+    /**
143
+     * Return the identifier of this provider.
144
+     *
145
+     * @return string Containing only [a-zA-Z0-9]
146
+     */
147
+    public function identifier() {
148
+        return 'ocFederatedSharing';
149
+    }
150
+
151
+    /**
152
+     * Share a path
153
+     *
154
+     * @param IShare $share
155
+     * @return IShare The share object
156
+     * @throws ShareNotFound
157
+     * @throws \Exception
158
+     */
159
+    public function create(IShare $share) {
160
+
161
+        $shareWith = $share->getSharedWith();
162
+        $itemSource = $share->getNodeId();
163
+        $itemType = $share->getNodeType();
164
+        $permissions = $share->getPermissions();
165
+        $sharedBy = $share->getSharedBy();
166
+        $shareType = $share->getShareType();
167
+
168
+        if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE_GROUP &&
169
+            !$this->isOutgoingServer2serverGroupShareEnabled()
170
+        ) {
171
+            $message = 'It is not allowed to send federated group shares from this server.';
172
+            $message_t = $this->l->t('It is not allowed to send federated group shares from this server.');
173
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
174
+            throw new \Exception($message_t);
175
+        }
176
+
177
+        /*
178 178
 		 * Check if file is not already shared with the remote user
179 179
 		 */
180
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
181
-		if (!empty($alreadyShared)) {
182
-			$message = 'Sharing %s failed, because this item is already shared with %s';
183
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
184
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
185
-			throw new \Exception($message_t);
186
-		}
187
-
188
-
189
-		// don't allow federated shares if source and target server are the same
190
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
191
-		$currentServer = $this->addressHandler->generateRemoteURL();
192
-		$currentUser = $sharedBy;
193
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
194
-			$message = 'Not allowed to create a federated share with the same user.';
195
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
196
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
197
-			throw new \Exception($message_t);
198
-		}
199
-
200
-
201
-		$share->setSharedWith($cloudId->getId());
202
-
203
-		try {
204
-			$remoteShare = $this->getShareFromExternalShareTable($share);
205
-		} catch (ShareNotFound $e) {
206
-			$remoteShare = null;
207
-		}
208
-
209
-		if ($remoteShare) {
210
-			try {
211
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
212
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
213
-				$share->setId($shareId);
214
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
215
-				// remote share was create successfully if we get a valid token as return
216
-				$send = is_string($token) && $token !== '';
217
-			} catch (\Exception $e) {
218
-				// fall back to old re-share behavior if the remote server
219
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
220
-				$this->removeShareFromTable($share);
221
-				$shareId = $this->createFederatedShare($share);
222
-			}
223
-			if ($send) {
224
-				$this->updateSuccessfulReshare($shareId, $token);
225
-				$this->storeRemoteId($shareId, $remoteId);
226
-			} else {
227
-				$this->removeShareFromTable($share);
228
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
229
-				throw new \Exception($message_t);
230
-			}
231
-
232
-		} else {
233
-			$shareId = $this->createFederatedShare($share);
234
-		}
235
-
236
-		$data = $this->getRawShare($shareId);
237
-		return $this->createShareObject($data);
238
-	}
239
-
240
-	/**
241
-	 * create federated share and inform the recipient
242
-	 *
243
-	 * @param IShare $share
244
-	 * @return int
245
-	 * @throws ShareNotFound
246
-	 * @throws \Exception
247
-	 */
248
-	protected function createFederatedShare(IShare $share) {
249
-		$token = $this->tokenHandler->generateToken();
250
-		$shareId = $this->addShareToDB(
251
-			$share->getNodeId(),
252
-			$share->getNodeType(),
253
-			$share->getSharedWith(),
254
-			$share->getSharedBy(),
255
-			$share->getShareOwner(),
256
-			$share->getPermissions(),
257
-			$token
258
-		);
259
-
260
-		$failure = false;
261
-
262
-		try {
263
-			$sharedByFederatedId = $share->getSharedBy();
264
-			if ($this->userManager->userExists($sharedByFederatedId)) {
265
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
266
-				$sharedByFederatedId = $cloudId->getId();
267
-			}
268
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
269
-			$send = $this->notifications->sendRemoteShare(
270
-				$token,
271
-				$share->getSharedWith(),
272
-				$share->getNode()->getName(),
273
-				$shareId,
274
-				$share->getShareOwner(),
275
-				$ownerCloudId->getId(),
276
-				$share->getSharedBy(),
277
-				$sharedByFederatedId,
278
-				$share->getShareType()
279
-			);
280
-
281
-			if ($send === false) {
282
-				$failure = true;
283
-			}
284
-		} catch (\Exception $e) {
285
-			$this->logger->logException($e, [
286
-				'message' => 'Failed to notify remote server of federated share, removing share.',
287
-				'level' => ILogger::ERROR,
288
-				'app' => 'federatedfilesharing',
289
-			]);
290
-			$failure = true;
291
-		}
292
-
293
-		if($failure) {
294
-			$this->removeShareFromTableById($shareId);
295
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
296
-				[$share->getNode()->getName(), $share->getSharedWith()]);
297
-			throw new \Exception($message_t);
298
-		}
299
-
300
-		return $shareId;
301
-
302
-	}
303
-
304
-	/**
305
-	 * @param string $shareWith
306
-	 * @param IShare $share
307
-	 * @param string $shareId internal share Id
308
-	 * @return array
309
-	 * @throws \Exception
310
-	 */
311
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
312
-
313
-		$remoteShare = $this->getShareFromExternalShareTable($share);
314
-		$token = $remoteShare['share_token'];
315
-		$remoteId = $remoteShare['remote_id'];
316
-		$remote = $remoteShare['remote'];
317
-
318
-		list($token, $remoteId) = $this->notifications->requestReShare(
319
-			$token,
320
-			$remoteId,
321
-			$shareId,
322
-			$remote,
323
-			$shareWith,
324
-			$share->getPermissions(),
325
-			$share->getNode()->getName()
326
-		);
327
-
328
-		return [$token, $remoteId];
329
-	}
330
-
331
-	/**
332
-	 * get federated share from the share_external table but exclude mounted link shares
333
-	 *
334
-	 * @param IShare $share
335
-	 * @return array
336
-	 * @throws ShareNotFound
337
-	 */
338
-	protected function getShareFromExternalShareTable(IShare $share) {
339
-		$query = $this->dbConnection->getQueryBuilder();
340
-		$query->select('*')->from($this->externalShareTable)
341
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
342
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
343
-		$result = $query->execute()->fetchAll();
344
-
345
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
346
-			return $result[0];
347
-		}
348
-
349
-		throw new ShareNotFound('share not found in share_external table');
350
-	}
351
-
352
-	/**
353
-	 * add share to the database and return the ID
354
-	 *
355
-	 * @param int $itemSource
356
-	 * @param string $itemType
357
-	 * @param string $shareWith
358
-	 * @param string $sharedBy
359
-	 * @param string $uidOwner
360
-	 * @param int $permissions
361
-	 * @param string $token
362
-	 * @return int
363
-	 */
364
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
365
-		$qb = $this->dbConnection->getQueryBuilder();
366
-		$qb->insert('share')
367
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
368
-			->setValue('item_type', $qb->createNamedParameter($itemType))
369
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
370
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
371
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
372
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
373
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
374
-			->setValue('permissions', $qb->createNamedParameter($permissions))
375
-			->setValue('token', $qb->createNamedParameter($token))
376
-			->setValue('stime', $qb->createNamedParameter(time()));
377
-
378
-		/*
180
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
181
+        if (!empty($alreadyShared)) {
182
+            $message = 'Sharing %s failed, because this item is already shared with %s';
183
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
184
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
185
+            throw new \Exception($message_t);
186
+        }
187
+
188
+
189
+        // don't allow federated shares if source and target server are the same
190
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
191
+        $currentServer = $this->addressHandler->generateRemoteURL();
192
+        $currentUser = $sharedBy;
193
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
194
+            $message = 'Not allowed to create a federated share with the same user.';
195
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
196
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
197
+            throw new \Exception($message_t);
198
+        }
199
+
200
+
201
+        $share->setSharedWith($cloudId->getId());
202
+
203
+        try {
204
+            $remoteShare = $this->getShareFromExternalShareTable($share);
205
+        } catch (ShareNotFound $e) {
206
+            $remoteShare = null;
207
+        }
208
+
209
+        if ($remoteShare) {
210
+            try {
211
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
212
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
213
+                $share->setId($shareId);
214
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
215
+                // remote share was create successfully if we get a valid token as return
216
+                $send = is_string($token) && $token !== '';
217
+            } catch (\Exception $e) {
218
+                // fall back to old re-share behavior if the remote server
219
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
220
+                $this->removeShareFromTable($share);
221
+                $shareId = $this->createFederatedShare($share);
222
+            }
223
+            if ($send) {
224
+                $this->updateSuccessfulReshare($shareId, $token);
225
+                $this->storeRemoteId($shareId, $remoteId);
226
+            } else {
227
+                $this->removeShareFromTable($share);
228
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
229
+                throw new \Exception($message_t);
230
+            }
231
+
232
+        } else {
233
+            $shareId = $this->createFederatedShare($share);
234
+        }
235
+
236
+        $data = $this->getRawShare($shareId);
237
+        return $this->createShareObject($data);
238
+    }
239
+
240
+    /**
241
+     * create federated share and inform the recipient
242
+     *
243
+     * @param IShare $share
244
+     * @return int
245
+     * @throws ShareNotFound
246
+     * @throws \Exception
247
+     */
248
+    protected function createFederatedShare(IShare $share) {
249
+        $token = $this->tokenHandler->generateToken();
250
+        $shareId = $this->addShareToDB(
251
+            $share->getNodeId(),
252
+            $share->getNodeType(),
253
+            $share->getSharedWith(),
254
+            $share->getSharedBy(),
255
+            $share->getShareOwner(),
256
+            $share->getPermissions(),
257
+            $token
258
+        );
259
+
260
+        $failure = false;
261
+
262
+        try {
263
+            $sharedByFederatedId = $share->getSharedBy();
264
+            if ($this->userManager->userExists($sharedByFederatedId)) {
265
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
266
+                $sharedByFederatedId = $cloudId->getId();
267
+            }
268
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
269
+            $send = $this->notifications->sendRemoteShare(
270
+                $token,
271
+                $share->getSharedWith(),
272
+                $share->getNode()->getName(),
273
+                $shareId,
274
+                $share->getShareOwner(),
275
+                $ownerCloudId->getId(),
276
+                $share->getSharedBy(),
277
+                $sharedByFederatedId,
278
+                $share->getShareType()
279
+            );
280
+
281
+            if ($send === false) {
282
+                $failure = true;
283
+            }
284
+        } catch (\Exception $e) {
285
+            $this->logger->logException($e, [
286
+                'message' => 'Failed to notify remote server of federated share, removing share.',
287
+                'level' => ILogger::ERROR,
288
+                'app' => 'federatedfilesharing',
289
+            ]);
290
+            $failure = true;
291
+        }
292
+
293
+        if($failure) {
294
+            $this->removeShareFromTableById($shareId);
295
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
296
+                [$share->getNode()->getName(), $share->getSharedWith()]);
297
+            throw new \Exception($message_t);
298
+        }
299
+
300
+        return $shareId;
301
+
302
+    }
303
+
304
+    /**
305
+     * @param string $shareWith
306
+     * @param IShare $share
307
+     * @param string $shareId internal share Id
308
+     * @return array
309
+     * @throws \Exception
310
+     */
311
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
312
+
313
+        $remoteShare = $this->getShareFromExternalShareTable($share);
314
+        $token = $remoteShare['share_token'];
315
+        $remoteId = $remoteShare['remote_id'];
316
+        $remote = $remoteShare['remote'];
317
+
318
+        list($token, $remoteId) = $this->notifications->requestReShare(
319
+            $token,
320
+            $remoteId,
321
+            $shareId,
322
+            $remote,
323
+            $shareWith,
324
+            $share->getPermissions(),
325
+            $share->getNode()->getName()
326
+        );
327
+
328
+        return [$token, $remoteId];
329
+    }
330
+
331
+    /**
332
+     * get federated share from the share_external table but exclude mounted link shares
333
+     *
334
+     * @param IShare $share
335
+     * @return array
336
+     * @throws ShareNotFound
337
+     */
338
+    protected function getShareFromExternalShareTable(IShare $share) {
339
+        $query = $this->dbConnection->getQueryBuilder();
340
+        $query->select('*')->from($this->externalShareTable)
341
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
342
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
343
+        $result = $query->execute()->fetchAll();
344
+
345
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
346
+            return $result[0];
347
+        }
348
+
349
+        throw new ShareNotFound('share not found in share_external table');
350
+    }
351
+
352
+    /**
353
+     * add share to the database and return the ID
354
+     *
355
+     * @param int $itemSource
356
+     * @param string $itemType
357
+     * @param string $shareWith
358
+     * @param string $sharedBy
359
+     * @param string $uidOwner
360
+     * @param int $permissions
361
+     * @param string $token
362
+     * @return int
363
+     */
364
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
365
+        $qb = $this->dbConnection->getQueryBuilder();
366
+        $qb->insert('share')
367
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
368
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
369
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
370
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
371
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
372
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
373
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
374
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
375
+            ->setValue('token', $qb->createNamedParameter($token))
376
+            ->setValue('stime', $qb->createNamedParameter(time()));
377
+
378
+        /*
379 379
 		 * Added to fix https://github.com/owncloud/core/issues/22215
380 380
 		 * Can be removed once we get rid of ajax/share.php
381 381
 		 */
382
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
383
-
384
-		$qb->execute();
385
-		$id = $qb->getLastInsertId();
386
-
387
-		return (int)$id;
388
-	}
389
-
390
-	/**
391
-	 * Update a share
392
-	 *
393
-	 * @param IShare $share
394
-	 * @return IShare The share object
395
-	 */
396
-	public function update(IShare $share) {
397
-		/*
382
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
383
+
384
+        $qb->execute();
385
+        $id = $qb->getLastInsertId();
386
+
387
+        return (int)$id;
388
+    }
389
+
390
+    /**
391
+     * Update a share
392
+     *
393
+     * @param IShare $share
394
+     * @return IShare The share object
395
+     */
396
+    public function update(IShare $share) {
397
+        /*
398 398
 		 * We allow updating the permissions of federated shares
399 399
 		 */
400
-		$qb = $this->dbConnection->getQueryBuilder();
401
-			$qb->update('share')
402
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
403
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
404
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
405
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
406
-				->execute();
407
-
408
-		// send the updated permission to the owner/initiator, if they are not the same
409
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
410
-			$this->sendPermissionUpdate($share);
411
-		}
412
-
413
-		return $share;
414
-	}
415
-
416
-	/**
417
-	 * send the updated permission to the owner/initiator, if they are not the same
418
-	 *
419
-	 * @param IShare $share
420
-	 * @throws ShareNotFound
421
-	 * @throws \OC\HintException
422
-	 */
423
-	protected function sendPermissionUpdate(IShare $share) {
424
-		$remoteId = $this->getRemoteId($share);
425
-		// if the local user is the owner we send the permission change to the initiator
426
-		if ($this->userManager->userExists($share->getShareOwner())) {
427
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
428
-		} else { // ... if not we send the permission change to the owner
429
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
430
-		}
431
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
432
-	}
433
-
434
-
435
-	/**
436
-	 * update successful reShare with the correct token
437
-	 *
438
-	 * @param int $shareId
439
-	 * @param string $token
440
-	 */
441
-	protected function updateSuccessfulReShare($shareId, $token) {
442
-		$query = $this->dbConnection->getQueryBuilder();
443
-		$query->update('share')
444
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
445
-			->set('token', $query->createNamedParameter($token))
446
-			->execute();
447
-	}
448
-
449
-	/**
450
-	 * store remote ID in federated reShare table
451
-	 *
452
-	 * @param $shareId
453
-	 * @param $remoteId
454
-	 */
455
-	public function storeRemoteId($shareId, $remoteId) {
456
-		$query = $this->dbConnection->getQueryBuilder();
457
-		$query->insert('federated_reshares')
458
-			->values(
459
-				[
460
-					'share_id' =>  $query->createNamedParameter($shareId),
461
-					'remote_id' => $query->createNamedParameter($remoteId),
462
-				]
463
-			);
464
-		$query->execute();
465
-	}
466
-
467
-	/**
468
-	 * get share ID on remote server for federated re-shares
469
-	 *
470
-	 * @param IShare $share
471
-	 * @return int
472
-	 * @throws ShareNotFound
473
-	 */
474
-	public function getRemoteId(IShare $share) {
475
-		$query = $this->dbConnection->getQueryBuilder();
476
-		$query->select('remote_id')->from('federated_reshares')
477
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
478
-		$data = $query->execute()->fetch();
479
-
480
-		if (!is_array($data) || !isset($data['remote_id'])) {
481
-			throw new ShareNotFound();
482
-		}
483
-
484
-		return (int)$data['remote_id'];
485
-	}
486
-
487
-	/**
488
-	 * @inheritdoc
489
-	 */
490
-	public function move(IShare $share, $recipient) {
491
-		/*
400
+        $qb = $this->dbConnection->getQueryBuilder();
401
+            $qb->update('share')
402
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
403
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
404
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
405
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
406
+                ->execute();
407
+
408
+        // send the updated permission to the owner/initiator, if they are not the same
409
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
410
+            $this->sendPermissionUpdate($share);
411
+        }
412
+
413
+        return $share;
414
+    }
415
+
416
+    /**
417
+     * send the updated permission to the owner/initiator, if they are not the same
418
+     *
419
+     * @param IShare $share
420
+     * @throws ShareNotFound
421
+     * @throws \OC\HintException
422
+     */
423
+    protected function sendPermissionUpdate(IShare $share) {
424
+        $remoteId = $this->getRemoteId($share);
425
+        // if the local user is the owner we send the permission change to the initiator
426
+        if ($this->userManager->userExists($share->getShareOwner())) {
427
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
428
+        } else { // ... if not we send the permission change to the owner
429
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
430
+        }
431
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
432
+    }
433
+
434
+
435
+    /**
436
+     * update successful reShare with the correct token
437
+     *
438
+     * @param int $shareId
439
+     * @param string $token
440
+     */
441
+    protected function updateSuccessfulReShare($shareId, $token) {
442
+        $query = $this->dbConnection->getQueryBuilder();
443
+        $query->update('share')
444
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
445
+            ->set('token', $query->createNamedParameter($token))
446
+            ->execute();
447
+    }
448
+
449
+    /**
450
+     * store remote ID in federated reShare table
451
+     *
452
+     * @param $shareId
453
+     * @param $remoteId
454
+     */
455
+    public function storeRemoteId($shareId, $remoteId) {
456
+        $query = $this->dbConnection->getQueryBuilder();
457
+        $query->insert('federated_reshares')
458
+            ->values(
459
+                [
460
+                    'share_id' =>  $query->createNamedParameter($shareId),
461
+                    'remote_id' => $query->createNamedParameter($remoteId),
462
+                ]
463
+            );
464
+        $query->execute();
465
+    }
466
+
467
+    /**
468
+     * get share ID on remote server for federated re-shares
469
+     *
470
+     * @param IShare $share
471
+     * @return int
472
+     * @throws ShareNotFound
473
+     */
474
+    public function getRemoteId(IShare $share) {
475
+        $query = $this->dbConnection->getQueryBuilder();
476
+        $query->select('remote_id')->from('federated_reshares')
477
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
478
+        $data = $query->execute()->fetch();
479
+
480
+        if (!is_array($data) || !isset($data['remote_id'])) {
481
+            throw new ShareNotFound();
482
+        }
483
+
484
+        return (int)$data['remote_id'];
485
+    }
486
+
487
+    /**
488
+     * @inheritdoc
489
+     */
490
+    public function move(IShare $share, $recipient) {
491
+        /*
492 492
 		 * This function does nothing yet as it is just for outgoing
493 493
 		 * federated shares.
494 494
 		 */
495
-		return $share;
496
-	}
497
-
498
-	/**
499
-	 * Get all children of this share
500
-	 *
501
-	 * @param IShare $parent
502
-	 * @return IShare[]
503
-	 */
504
-	public function getChildren(IShare $parent) {
505
-		$children = [];
506
-
507
-		$qb = $this->dbConnection->getQueryBuilder();
508
-		$qb->select('*')
509
-			->from('share')
510
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
511
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
512
-			->orderBy('id');
513
-
514
-		$cursor = $qb->execute();
515
-		while($data = $cursor->fetch()) {
516
-			$children[] = $this->createShareObject($data);
517
-		}
518
-		$cursor->closeCursor();
519
-
520
-		return $children;
521
-	}
522
-
523
-	/**
524
-	 * Delete a share (owner unShares the file)
525
-	 *
526
-	 * @param IShare $share
527
-	 * @throws ShareNotFound
528
-	 * @throws \OC\HintException
529
-	 */
530
-	public function delete(IShare $share) {
531
-
532
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
533
-
534
-		// if the local user is the owner we can send the unShare request directly...
535
-		if ($this->userManager->userExists($share->getShareOwner())) {
536
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
537
-			$this->revokeShare($share, true);
538
-		} else { // ... if not we need to correct ID for the unShare request
539
-			$remoteId = $this->getRemoteId($share);
540
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
541
-			$this->revokeShare($share, false);
542
-		}
543
-
544
-		// only remove the share when all messages are send to not lose information
545
-		// about the share to early
546
-		$this->removeShareFromTable($share);
547
-	}
548
-
549
-	/**
550
-	 * in case of a re-share we need to send the other use (initiator or owner)
551
-	 * a message that the file was unshared
552
-	 *
553
-	 * @param IShare $share
554
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
555
-	 * @throws ShareNotFound
556
-	 * @throws \OC\HintException
557
-	 */
558
-	protected function revokeShare($share, $isOwner) {
559
-		// also send a unShare request to the initiator, if this is a different user than the owner
560
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
561
-			if ($isOwner) {
562
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
563
-			} else {
564
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
565
-			}
566
-			$remoteId = $this->getRemoteId($share);
567
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
568
-		}
569
-	}
570
-
571
-	/**
572
-	 * remove share from table
573
-	 *
574
-	 * @param IShare $share
575
-	 */
576
-	public function removeShareFromTable(IShare $share) {
577
-		$this->removeShareFromTableById($share->getId());
578
-	}
579
-
580
-	/**
581
-	 * remove share from table
582
-	 *
583
-	 * @param string $shareId
584
-	 */
585
-	private function removeShareFromTableById($shareId) {
586
-		$qb = $this->dbConnection->getQueryBuilder();
587
-		$qb->delete('share')
588
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
589
-		$qb->execute();
590
-
591
-		$qb->delete('federated_reshares')
592
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
593
-		$qb->execute();
594
-	}
595
-
596
-	/**
597
-	 * @inheritdoc
598
-	 */
599
-	public function deleteFromSelf(IShare $share, $recipient) {
600
-		// nothing to do here. Technically deleteFromSelf in the context of federated
601
-		// shares is a umount of a external storage. This is handled here
602
-		// apps/files_sharing/lib/external/manager.php
603
-		// TODO move this code over to this app
604
-	}
605
-
606
-
607
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
608
-		$qb = $this->dbConnection->getQueryBuilder();
609
-		$qb->select('*')
610
-			->from('share', 's')
611
-			->andWhere($qb->expr()->orX(
612
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
613
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
614
-			))
615
-			->andWhere(
616
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
617
-			);
618
-
619
-		/**
620
-		 * Reshares for this user are shares where they are the owner.
621
-		 */
622
-		if ($reshares === false) {
623
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
624
-		} else {
625
-			$qb->andWhere(
626
-				$qb->expr()->orX(
627
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
628
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
629
-				)
630
-			);
631
-		}
632
-
633
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
634
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
635
-
636
-		$qb->orderBy('id');
637
-
638
-		$cursor = $qb->execute();
639
-		$shares = [];
640
-		while ($data = $cursor->fetch()) {
641
-			$shares[$data['fileid']][] = $this->createShareObject($data);
642
-		}
643
-		$cursor->closeCursor();
644
-
645
-		return $shares;
646
-	}
647
-
648
-	/**
649
-	 * @inheritdoc
650
-	 */
651
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
652
-		$qb = $this->dbConnection->getQueryBuilder();
653
-		$qb->select('*')
654
-			->from('share');
655
-
656
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
657
-
658
-		/**
659
-		 * Reshares for this user are shares where they are the owner.
660
-		 */
661
-		if ($reshares === false) {
662
-			//Special case for old shares created via the web UI
663
-			$or1 = $qb->expr()->andX(
664
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
665
-				$qb->expr()->isNull('uid_initiator')
666
-			);
667
-
668
-			$qb->andWhere(
669
-				$qb->expr()->orX(
670
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
671
-					$or1
672
-				)
673
-			);
674
-		} else {
675
-			$qb->andWhere(
676
-				$qb->expr()->orX(
677
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
678
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
679
-				)
680
-			);
681
-		}
682
-
683
-		if ($node !== null) {
684
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
685
-		}
686
-
687
-		if ($limit !== -1) {
688
-			$qb->setMaxResults($limit);
689
-		}
690
-
691
-		$qb->setFirstResult($offset);
692
-		$qb->orderBy('id');
693
-
694
-		$cursor = $qb->execute();
695
-		$shares = [];
696
-		while($data = $cursor->fetch()) {
697
-			$shares[] = $this->createShareObject($data);
698
-		}
699
-		$cursor->closeCursor();
700
-
701
-		return $shares;
702
-	}
703
-
704
-	/**
705
-	 * @inheritdoc
706
-	 */
707
-	public function getShareById($id, $recipientId = null) {
708
-		$qb = $this->dbConnection->getQueryBuilder();
709
-
710
-		$qb->select('*')
711
-			->from('share')
712
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
713
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
714
-
715
-		$cursor = $qb->execute();
716
-		$data = $cursor->fetch();
717
-		$cursor->closeCursor();
718
-
719
-		if ($data === false) {
720
-			throw new ShareNotFound('Can not find share with ID: ' . $id);
721
-		}
722
-
723
-		try {
724
-			$share = $this->createShareObject($data);
725
-		} catch (InvalidShare $e) {
726
-			throw new ShareNotFound();
727
-		}
728
-
729
-		return $share;
730
-	}
731
-
732
-	/**
733
-	 * Get shares for a given path
734
-	 *
735
-	 * @param \OCP\Files\Node $path
736
-	 * @return IShare[]
737
-	 */
738
-	public function getSharesByPath(Node $path) {
739
-		$qb = $this->dbConnection->getQueryBuilder();
740
-
741
-		$cursor = $qb->select('*')
742
-			->from('share')
743
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
744
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
745
-			->execute();
746
-
747
-		$shares = [];
748
-		while($data = $cursor->fetch()) {
749
-			$shares[] = $this->createShareObject($data);
750
-		}
751
-		$cursor->closeCursor();
752
-
753
-		return $shares;
754
-	}
755
-
756
-	/**
757
-	 * @inheritdoc
758
-	 */
759
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
760
-		/** @var IShare[] $shares */
761
-		$shares = [];
762
-
763
-		//Get shares directly with this user
764
-		$qb = $this->dbConnection->getQueryBuilder();
765
-		$qb->select('*')
766
-			->from('share');
767
-
768
-		// Order by id
769
-		$qb->orderBy('id');
770
-
771
-		// Set limit and offset
772
-		if ($limit !== -1) {
773
-			$qb->setMaxResults($limit);
774
-		}
775
-		$qb->setFirstResult($offset);
776
-
777
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
778
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
779
-
780
-		// Filter by node if provided
781
-		if ($node !== null) {
782
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
783
-		}
784
-
785
-		$cursor = $qb->execute();
786
-
787
-		while($data = $cursor->fetch()) {
788
-			$shares[] = $this->createShareObject($data);
789
-		}
790
-		$cursor->closeCursor();
791
-
792
-
793
-		return $shares;
794
-	}
795
-
796
-	/**
797
-	 * Get a share by token
798
-	 *
799
-	 * @param string $token
800
-	 * @return IShare
801
-	 * @throws ShareNotFound
802
-	 */
803
-	public function getShareByToken($token) {
804
-		$qb = $this->dbConnection->getQueryBuilder();
805
-
806
-		$cursor = $qb->select('*')
807
-			->from('share')
808
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
809
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
810
-			->execute();
811
-
812
-		$data = $cursor->fetch();
813
-
814
-		if ($data === false) {
815
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
816
-		}
817
-
818
-		try {
819
-			$share = $this->createShareObject($data);
820
-		} catch (InvalidShare $e) {
821
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
822
-		}
823
-
824
-		return $share;
825
-	}
826
-
827
-	/**
828
-	 * get database row of a give share
829
-	 *
830
-	 * @param $id
831
-	 * @return array
832
-	 * @throws ShareNotFound
833
-	 */
834
-	private function getRawShare($id) {
835
-
836
-		// Now fetch the inserted share and create a complete share object
837
-		$qb = $this->dbConnection->getQueryBuilder();
838
-		$qb->select('*')
839
-			->from('share')
840
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
841
-
842
-		$cursor = $qb->execute();
843
-		$data = $cursor->fetch();
844
-		$cursor->closeCursor();
845
-
846
-		if ($data === false) {
847
-			throw new ShareNotFound;
848
-		}
849
-
850
-		return $data;
851
-	}
852
-
853
-	/**
854
-	 * Create a share object from an database row
855
-	 *
856
-	 * @param array $data
857
-	 * @return IShare
858
-	 * @throws InvalidShare
859
-	 * @throws ShareNotFound
860
-	 */
861
-	private function createShareObject($data) {
862
-
863
-		$share = new Share($this->rootFolder, $this->userManager);
864
-		$share->setId((int)$data['id'])
865
-			->setShareType((int)$data['share_type'])
866
-			->setPermissions((int)$data['permissions'])
867
-			->setTarget($data['file_target'])
868
-			->setMailSend((bool)$data['mail_send'])
869
-			->setToken($data['token']);
870
-
871
-		$shareTime = new \DateTime();
872
-		$shareTime->setTimestamp((int)$data['stime']);
873
-		$share->setShareTime($shareTime);
874
-		$share->setSharedWith($data['share_with']);
875
-
876
-		if ($data['uid_initiator'] !== null) {
877
-			$share->setShareOwner($data['uid_owner']);
878
-			$share->setSharedBy($data['uid_initiator']);
879
-		} else {
880
-			//OLD SHARE
881
-			$share->setSharedBy($data['uid_owner']);
882
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
883
-
884
-			$owner = $path->getOwner();
885
-			$share->setShareOwner($owner->getUID());
886
-		}
887
-
888
-		$share->setNodeId((int)$data['file_source']);
889
-		$share->setNodeType($data['item_type']);
890
-
891
-		$share->setProviderId($this->identifier());
892
-
893
-		return $share;
894
-	}
895
-
896
-	/**
897
-	 * Get the node with file $id for $user
898
-	 *
899
-	 * @param string $userId
900
-	 * @param int $id
901
-	 * @return \OCP\Files\File|\OCP\Files\Folder
902
-	 * @throws InvalidShare
903
-	 */
904
-	private function getNode($userId, $id) {
905
-		try {
906
-			$userFolder = $this->rootFolder->getUserFolder($userId);
907
-		} catch (NotFoundException $e) {
908
-			throw new InvalidShare();
909
-		}
910
-
911
-		$nodes = $userFolder->getById($id);
912
-
913
-		if (empty($nodes)) {
914
-			throw new InvalidShare();
915
-		}
916
-
917
-		return $nodes[0];
918
-	}
919
-
920
-	/**
921
-	 * A user is deleted from the system
922
-	 * So clean up the relevant shares.
923
-	 *
924
-	 * @param string $uid
925
-	 * @param int $shareType
926
-	 */
927
-	public function userDeleted($uid, $shareType) {
928
-		//TODO: probabaly a good idea to send unshare info to remote servers
929
-
930
-		$qb = $this->dbConnection->getQueryBuilder();
931
-
932
-		$qb->delete('share')
933
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
934
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
935
-			->execute();
936
-	}
937
-
938
-	/**
939
-	 * This provider does not handle groups
940
-	 *
941
-	 * @param string $gid
942
-	 */
943
-	public function groupDeleted($gid) {
944
-		// We don't handle groups here
945
-	}
946
-
947
-	/**
948
-	 * This provider does not handle groups
949
-	 *
950
-	 * @param string $uid
951
-	 * @param string $gid
952
-	 */
953
-	public function userDeletedFromGroup($uid, $gid) {
954
-		// We don't handle groups here
955
-	}
956
-
957
-	/**
958
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
959
-	 *
960
-	 * @return bool
961
-	 */
962
-	public function isOutgoingServer2serverShareEnabled() {
963
-		if ($this->gsConfig->onlyInternalFederation()) {
964
-			return false;
965
-		}
966
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
967
-		return ($result === 'yes');
968
-	}
969
-
970
-	/**
971
-	 * check if users are allowed to mount public links from other Nextclouds
972
-	 *
973
-	 * @return bool
974
-	 */
975
-	public function isIncomingServer2serverShareEnabled() {
976
-		if ($this->gsConfig->onlyInternalFederation()) {
977
-			return false;
978
-		}
979
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
980
-		return ($result === 'yes');
981
-	}
982
-
983
-
984
-	/**
985
-	 * check if users from other Nextcloud instances are allowed to send federated group shares
986
-	 *
987
-	 * @return bool
988
-	 */
989
-	public function isOutgoingServer2serverGroupShareEnabled() {
990
-		if ($this->gsConfig->onlyInternalFederation()) {
991
-			return false;
992
-		}
993
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no');
994
-		return ($result === 'yes');
995
-	}
996
-
997
-	/**
998
-	 * check if users are allowed to receive federated group shares
999
-	 *
1000
-	 * @return bool
1001
-	 */
1002
-	public function isIncomingServer2serverGroupShareEnabled() {
1003
-		if ($this->gsConfig->onlyInternalFederation()) {
1004
-			return false;
1005
-		}
1006
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_group_share_enabled', 'no');
1007
-		return ($result === 'yes');
1008
-	}
1009
-
1010
-	/**
1011
-	 * check if federated group sharing is supported, therefore the OCM API need to be enabled
1012
-	 *
1013
-	 * @return bool
1014
-	 */
1015
-	public function isFederatedGroupSharingSupported() {
1016
-		return $this->cloudFederationProviderManager->isReady();
1017
-	}
1018
-
1019
-	/**
1020
-	 * Check if querying sharees on the lookup server is enabled
1021
-	 *
1022
-	 * @return bool
1023
-	 */
1024
-	public function isLookupServerQueriesEnabled() {
1025
-		// in a global scale setup we should always query the lookup server
1026
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
1027
-			return true;
1028
-		}
1029
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
1030
-		return ($result === 'yes');
1031
-	}
1032
-
1033
-
1034
-	/**
1035
-	 * Check if it is allowed to publish user specific data to the lookup server
1036
-	 *
1037
-	 * @return bool
1038
-	 */
1039
-	public function isLookupServerUploadEnabled() {
1040
-		// in a global scale setup the admin is responsible to keep the lookup server up-to-date
1041
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
1042
-			return false;
1043
-		}
1044
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
1045
-		return ($result === 'yes');
1046
-	}
1047
-
1048
-	/**
1049
-	 * @inheritdoc
1050
-	 */
1051
-	public function getAccessList($nodes, $currentAccess) {
1052
-		$ids = [];
1053
-		foreach ($nodes as $node) {
1054
-			$ids[] = $node->getId();
1055
-		}
1056
-
1057
-		$qb = $this->dbConnection->getQueryBuilder();
1058
-		$qb->select('share_with', 'token', 'file_source')
1059
-			->from('share')
1060
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1061
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1062
-			->andWhere($qb->expr()->orX(
1063
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1064
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1065
-			));
1066
-		$cursor = $qb->execute();
1067
-
1068
-		if ($currentAccess === false) {
1069
-			$remote = $cursor->fetch() !== false;
1070
-			$cursor->closeCursor();
1071
-
1072
-			return ['remote' => $remote];
1073
-		}
1074
-
1075
-		$remote = [];
1076
-		while ($row = $cursor->fetch()) {
1077
-			$remote[$row['share_with']] = [
1078
-				'node_id' => $row['file_source'],
1079
-				'token' => $row['token'],
1080
-			];
1081
-		}
1082
-		$cursor->closeCursor();
1083
-
1084
-		return ['remote' => $remote];
1085
-	}
495
+        return $share;
496
+    }
497
+
498
+    /**
499
+     * Get all children of this share
500
+     *
501
+     * @param IShare $parent
502
+     * @return IShare[]
503
+     */
504
+    public function getChildren(IShare $parent) {
505
+        $children = [];
506
+
507
+        $qb = $this->dbConnection->getQueryBuilder();
508
+        $qb->select('*')
509
+            ->from('share')
510
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
511
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
512
+            ->orderBy('id');
513
+
514
+        $cursor = $qb->execute();
515
+        while($data = $cursor->fetch()) {
516
+            $children[] = $this->createShareObject($data);
517
+        }
518
+        $cursor->closeCursor();
519
+
520
+        return $children;
521
+    }
522
+
523
+    /**
524
+     * Delete a share (owner unShares the file)
525
+     *
526
+     * @param IShare $share
527
+     * @throws ShareNotFound
528
+     * @throws \OC\HintException
529
+     */
530
+    public function delete(IShare $share) {
531
+
532
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
533
+
534
+        // if the local user is the owner we can send the unShare request directly...
535
+        if ($this->userManager->userExists($share->getShareOwner())) {
536
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
537
+            $this->revokeShare($share, true);
538
+        } else { // ... if not we need to correct ID for the unShare request
539
+            $remoteId = $this->getRemoteId($share);
540
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
541
+            $this->revokeShare($share, false);
542
+        }
543
+
544
+        // only remove the share when all messages are send to not lose information
545
+        // about the share to early
546
+        $this->removeShareFromTable($share);
547
+    }
548
+
549
+    /**
550
+     * in case of a re-share we need to send the other use (initiator or owner)
551
+     * a message that the file was unshared
552
+     *
553
+     * @param IShare $share
554
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
555
+     * @throws ShareNotFound
556
+     * @throws \OC\HintException
557
+     */
558
+    protected function revokeShare($share, $isOwner) {
559
+        // also send a unShare request to the initiator, if this is a different user than the owner
560
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
561
+            if ($isOwner) {
562
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
563
+            } else {
564
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
565
+            }
566
+            $remoteId = $this->getRemoteId($share);
567
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
568
+        }
569
+    }
570
+
571
+    /**
572
+     * remove share from table
573
+     *
574
+     * @param IShare $share
575
+     */
576
+    public function removeShareFromTable(IShare $share) {
577
+        $this->removeShareFromTableById($share->getId());
578
+    }
579
+
580
+    /**
581
+     * remove share from table
582
+     *
583
+     * @param string $shareId
584
+     */
585
+    private function removeShareFromTableById($shareId) {
586
+        $qb = $this->dbConnection->getQueryBuilder();
587
+        $qb->delete('share')
588
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
589
+        $qb->execute();
590
+
591
+        $qb->delete('federated_reshares')
592
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
593
+        $qb->execute();
594
+    }
595
+
596
+    /**
597
+     * @inheritdoc
598
+     */
599
+    public function deleteFromSelf(IShare $share, $recipient) {
600
+        // nothing to do here. Technically deleteFromSelf in the context of federated
601
+        // shares is a umount of a external storage. This is handled here
602
+        // apps/files_sharing/lib/external/manager.php
603
+        // TODO move this code over to this app
604
+    }
605
+
606
+
607
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
608
+        $qb = $this->dbConnection->getQueryBuilder();
609
+        $qb->select('*')
610
+            ->from('share', 's')
611
+            ->andWhere($qb->expr()->orX(
612
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
613
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
614
+            ))
615
+            ->andWhere(
616
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
617
+            );
618
+
619
+        /**
620
+         * Reshares for this user are shares where they are the owner.
621
+         */
622
+        if ($reshares === false) {
623
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
624
+        } else {
625
+            $qb->andWhere(
626
+                $qb->expr()->orX(
627
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
628
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
629
+                )
630
+            );
631
+        }
632
+
633
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
634
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
635
+
636
+        $qb->orderBy('id');
637
+
638
+        $cursor = $qb->execute();
639
+        $shares = [];
640
+        while ($data = $cursor->fetch()) {
641
+            $shares[$data['fileid']][] = $this->createShareObject($data);
642
+        }
643
+        $cursor->closeCursor();
644
+
645
+        return $shares;
646
+    }
647
+
648
+    /**
649
+     * @inheritdoc
650
+     */
651
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
652
+        $qb = $this->dbConnection->getQueryBuilder();
653
+        $qb->select('*')
654
+            ->from('share');
655
+
656
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
657
+
658
+        /**
659
+         * Reshares for this user are shares where they are the owner.
660
+         */
661
+        if ($reshares === false) {
662
+            //Special case for old shares created via the web UI
663
+            $or1 = $qb->expr()->andX(
664
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
665
+                $qb->expr()->isNull('uid_initiator')
666
+            );
667
+
668
+            $qb->andWhere(
669
+                $qb->expr()->orX(
670
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
671
+                    $or1
672
+                )
673
+            );
674
+        } else {
675
+            $qb->andWhere(
676
+                $qb->expr()->orX(
677
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
678
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
679
+                )
680
+            );
681
+        }
682
+
683
+        if ($node !== null) {
684
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
685
+        }
686
+
687
+        if ($limit !== -1) {
688
+            $qb->setMaxResults($limit);
689
+        }
690
+
691
+        $qb->setFirstResult($offset);
692
+        $qb->orderBy('id');
693
+
694
+        $cursor = $qb->execute();
695
+        $shares = [];
696
+        while($data = $cursor->fetch()) {
697
+            $shares[] = $this->createShareObject($data);
698
+        }
699
+        $cursor->closeCursor();
700
+
701
+        return $shares;
702
+    }
703
+
704
+    /**
705
+     * @inheritdoc
706
+     */
707
+    public function getShareById($id, $recipientId = null) {
708
+        $qb = $this->dbConnection->getQueryBuilder();
709
+
710
+        $qb->select('*')
711
+            ->from('share')
712
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
713
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
714
+
715
+        $cursor = $qb->execute();
716
+        $data = $cursor->fetch();
717
+        $cursor->closeCursor();
718
+
719
+        if ($data === false) {
720
+            throw new ShareNotFound('Can not find share with ID: ' . $id);
721
+        }
722
+
723
+        try {
724
+            $share = $this->createShareObject($data);
725
+        } catch (InvalidShare $e) {
726
+            throw new ShareNotFound();
727
+        }
728
+
729
+        return $share;
730
+    }
731
+
732
+    /**
733
+     * Get shares for a given path
734
+     *
735
+     * @param \OCP\Files\Node $path
736
+     * @return IShare[]
737
+     */
738
+    public function getSharesByPath(Node $path) {
739
+        $qb = $this->dbConnection->getQueryBuilder();
740
+
741
+        $cursor = $qb->select('*')
742
+            ->from('share')
743
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
744
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
745
+            ->execute();
746
+
747
+        $shares = [];
748
+        while($data = $cursor->fetch()) {
749
+            $shares[] = $this->createShareObject($data);
750
+        }
751
+        $cursor->closeCursor();
752
+
753
+        return $shares;
754
+    }
755
+
756
+    /**
757
+     * @inheritdoc
758
+     */
759
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
760
+        /** @var IShare[] $shares */
761
+        $shares = [];
762
+
763
+        //Get shares directly with this user
764
+        $qb = $this->dbConnection->getQueryBuilder();
765
+        $qb->select('*')
766
+            ->from('share');
767
+
768
+        // Order by id
769
+        $qb->orderBy('id');
770
+
771
+        // Set limit and offset
772
+        if ($limit !== -1) {
773
+            $qb->setMaxResults($limit);
774
+        }
775
+        $qb->setFirstResult($offset);
776
+
777
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
778
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
779
+
780
+        // Filter by node if provided
781
+        if ($node !== null) {
782
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
783
+        }
784
+
785
+        $cursor = $qb->execute();
786
+
787
+        while($data = $cursor->fetch()) {
788
+            $shares[] = $this->createShareObject($data);
789
+        }
790
+        $cursor->closeCursor();
791
+
792
+
793
+        return $shares;
794
+    }
795
+
796
+    /**
797
+     * Get a share by token
798
+     *
799
+     * @param string $token
800
+     * @return IShare
801
+     * @throws ShareNotFound
802
+     */
803
+    public function getShareByToken($token) {
804
+        $qb = $this->dbConnection->getQueryBuilder();
805
+
806
+        $cursor = $qb->select('*')
807
+            ->from('share')
808
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
809
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
810
+            ->execute();
811
+
812
+        $data = $cursor->fetch();
813
+
814
+        if ($data === false) {
815
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
816
+        }
817
+
818
+        try {
819
+            $share = $this->createShareObject($data);
820
+        } catch (InvalidShare $e) {
821
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
822
+        }
823
+
824
+        return $share;
825
+    }
826
+
827
+    /**
828
+     * get database row of a give share
829
+     *
830
+     * @param $id
831
+     * @return array
832
+     * @throws ShareNotFound
833
+     */
834
+    private function getRawShare($id) {
835
+
836
+        // Now fetch the inserted share and create a complete share object
837
+        $qb = $this->dbConnection->getQueryBuilder();
838
+        $qb->select('*')
839
+            ->from('share')
840
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
841
+
842
+        $cursor = $qb->execute();
843
+        $data = $cursor->fetch();
844
+        $cursor->closeCursor();
845
+
846
+        if ($data === false) {
847
+            throw new ShareNotFound;
848
+        }
849
+
850
+        return $data;
851
+    }
852
+
853
+    /**
854
+     * Create a share object from an database row
855
+     *
856
+     * @param array $data
857
+     * @return IShare
858
+     * @throws InvalidShare
859
+     * @throws ShareNotFound
860
+     */
861
+    private function createShareObject($data) {
862
+
863
+        $share = new Share($this->rootFolder, $this->userManager);
864
+        $share->setId((int)$data['id'])
865
+            ->setShareType((int)$data['share_type'])
866
+            ->setPermissions((int)$data['permissions'])
867
+            ->setTarget($data['file_target'])
868
+            ->setMailSend((bool)$data['mail_send'])
869
+            ->setToken($data['token']);
870
+
871
+        $shareTime = new \DateTime();
872
+        $shareTime->setTimestamp((int)$data['stime']);
873
+        $share->setShareTime($shareTime);
874
+        $share->setSharedWith($data['share_with']);
875
+
876
+        if ($data['uid_initiator'] !== null) {
877
+            $share->setShareOwner($data['uid_owner']);
878
+            $share->setSharedBy($data['uid_initiator']);
879
+        } else {
880
+            //OLD SHARE
881
+            $share->setSharedBy($data['uid_owner']);
882
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
883
+
884
+            $owner = $path->getOwner();
885
+            $share->setShareOwner($owner->getUID());
886
+        }
887
+
888
+        $share->setNodeId((int)$data['file_source']);
889
+        $share->setNodeType($data['item_type']);
890
+
891
+        $share->setProviderId($this->identifier());
892
+
893
+        return $share;
894
+    }
895
+
896
+    /**
897
+     * Get the node with file $id for $user
898
+     *
899
+     * @param string $userId
900
+     * @param int $id
901
+     * @return \OCP\Files\File|\OCP\Files\Folder
902
+     * @throws InvalidShare
903
+     */
904
+    private function getNode($userId, $id) {
905
+        try {
906
+            $userFolder = $this->rootFolder->getUserFolder($userId);
907
+        } catch (NotFoundException $e) {
908
+            throw new InvalidShare();
909
+        }
910
+
911
+        $nodes = $userFolder->getById($id);
912
+
913
+        if (empty($nodes)) {
914
+            throw new InvalidShare();
915
+        }
916
+
917
+        return $nodes[0];
918
+    }
919
+
920
+    /**
921
+     * A user is deleted from the system
922
+     * So clean up the relevant shares.
923
+     *
924
+     * @param string $uid
925
+     * @param int $shareType
926
+     */
927
+    public function userDeleted($uid, $shareType) {
928
+        //TODO: probabaly a good idea to send unshare info to remote servers
929
+
930
+        $qb = $this->dbConnection->getQueryBuilder();
931
+
932
+        $qb->delete('share')
933
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
934
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
935
+            ->execute();
936
+    }
937
+
938
+    /**
939
+     * This provider does not handle groups
940
+     *
941
+     * @param string $gid
942
+     */
943
+    public function groupDeleted($gid) {
944
+        // We don't handle groups here
945
+    }
946
+
947
+    /**
948
+     * This provider does not handle groups
949
+     *
950
+     * @param string $uid
951
+     * @param string $gid
952
+     */
953
+    public function userDeletedFromGroup($uid, $gid) {
954
+        // We don't handle groups here
955
+    }
956
+
957
+    /**
958
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
959
+     *
960
+     * @return bool
961
+     */
962
+    public function isOutgoingServer2serverShareEnabled() {
963
+        if ($this->gsConfig->onlyInternalFederation()) {
964
+            return false;
965
+        }
966
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
967
+        return ($result === 'yes');
968
+    }
969
+
970
+    /**
971
+     * check if users are allowed to mount public links from other Nextclouds
972
+     *
973
+     * @return bool
974
+     */
975
+    public function isIncomingServer2serverShareEnabled() {
976
+        if ($this->gsConfig->onlyInternalFederation()) {
977
+            return false;
978
+        }
979
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
980
+        return ($result === 'yes');
981
+    }
982
+
983
+
984
+    /**
985
+     * check if users from other Nextcloud instances are allowed to send federated group shares
986
+     *
987
+     * @return bool
988
+     */
989
+    public function isOutgoingServer2serverGroupShareEnabled() {
990
+        if ($this->gsConfig->onlyInternalFederation()) {
991
+            return false;
992
+        }
993
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no');
994
+        return ($result === 'yes');
995
+    }
996
+
997
+    /**
998
+     * check if users are allowed to receive federated group shares
999
+     *
1000
+     * @return bool
1001
+     */
1002
+    public function isIncomingServer2serverGroupShareEnabled() {
1003
+        if ($this->gsConfig->onlyInternalFederation()) {
1004
+            return false;
1005
+        }
1006
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_group_share_enabled', 'no');
1007
+        return ($result === 'yes');
1008
+    }
1009
+
1010
+    /**
1011
+     * check if federated group sharing is supported, therefore the OCM API need to be enabled
1012
+     *
1013
+     * @return bool
1014
+     */
1015
+    public function isFederatedGroupSharingSupported() {
1016
+        return $this->cloudFederationProviderManager->isReady();
1017
+    }
1018
+
1019
+    /**
1020
+     * Check if querying sharees on the lookup server is enabled
1021
+     *
1022
+     * @return bool
1023
+     */
1024
+    public function isLookupServerQueriesEnabled() {
1025
+        // in a global scale setup we should always query the lookup server
1026
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
1027
+            return true;
1028
+        }
1029
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
1030
+        return ($result === 'yes');
1031
+    }
1032
+
1033
+
1034
+    /**
1035
+     * Check if it is allowed to publish user specific data to the lookup server
1036
+     *
1037
+     * @return bool
1038
+     */
1039
+    public function isLookupServerUploadEnabled() {
1040
+        // in a global scale setup the admin is responsible to keep the lookup server up-to-date
1041
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
1042
+            return false;
1043
+        }
1044
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
1045
+        return ($result === 'yes');
1046
+    }
1047
+
1048
+    /**
1049
+     * @inheritdoc
1050
+     */
1051
+    public function getAccessList($nodes, $currentAccess) {
1052
+        $ids = [];
1053
+        foreach ($nodes as $node) {
1054
+            $ids[] = $node->getId();
1055
+        }
1056
+
1057
+        $qb = $this->dbConnection->getQueryBuilder();
1058
+        $qb->select('share_with', 'token', 'file_source')
1059
+            ->from('share')
1060
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1061
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1062
+            ->andWhere($qb->expr()->orX(
1063
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1064
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1065
+            ));
1066
+        $cursor = $qb->execute();
1067
+
1068
+        if ($currentAccess === false) {
1069
+            $remote = $cursor->fetch() !== false;
1070
+            $cursor->closeCursor();
1071
+
1072
+            return ['remote' => $remote];
1073
+        }
1074
+
1075
+        $remote = [];
1076
+        while ($row = $cursor->fetch()) {
1077
+            $remote[$row['share_with']] = [
1078
+                'node_id' => $row['file_source'],
1079
+                'token' => $row['token'],
1080
+            ];
1081
+        }
1082
+        $cursor->closeCursor();
1083
+
1084
+        return ['remote' => $remote];
1085
+    }
1086 1086
 }
Please login to merge, or discard this patch.