Completed
Pull Request — master (#9895)
by Björn
168:09 queued 150:46
created
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -48,236 +48,236 @@
 block discarded – undo
48 48
  */
49 49
 class ProviderFactory implements IProviderFactory {
50 50
 
51
-	/** @var IServerContainer */
52
-	private $serverContainer;
53
-	/** @var DefaultShareProvider */
54
-	private $defaultProvider = null;
55
-	/** @var FederatedShareProvider */
56
-	private $federatedProvider = null;
57
-	/** @var  ShareByMailProvider */
58
-	private $shareByMailProvider;
59
-	/** @var  \OCA\Circles\ShareByCircleProvider */
60
-	private $shareByCircleProvider = null;
61
-	/** @var bool */
62
-	private $circlesAreNotAvailable = false;
63
-
64
-	/**
65
-	 * IProviderFactory constructor.
66
-	 *
67
-	 * @param IServerContainer $serverContainer
68
-	 */
69
-	public function __construct(IServerContainer $serverContainer) {
70
-		$this->serverContainer = $serverContainer;
71
-	}
72
-
73
-	/**
74
-	 * Create the default share provider.
75
-	 *
76
-	 * @return DefaultShareProvider
77
-	 */
78
-	protected function defaultShareProvider() {
79
-		if ($this->defaultProvider === null) {
80
-			$this->defaultProvider = new DefaultShareProvider(
81
-				$this->serverContainer->getDatabaseConnection(),
82
-				$this->serverContainer->getUserManager(),
83
-				$this->serverContainer->getGroupManager(),
84
-				$this->serverContainer->getLazyRootFolder()
85
-			);
86
-		}
87
-
88
-		return $this->defaultProvider;
89
-	}
90
-
91
-	/**
92
-	 * Create the federated share provider
93
-	 *
94
-	 * @return FederatedShareProvider
95
-	 */
96
-	protected function federatedShareProvider() {
97
-		if ($this->federatedProvider === null) {
98
-			/*
51
+    /** @var IServerContainer */
52
+    private $serverContainer;
53
+    /** @var DefaultShareProvider */
54
+    private $defaultProvider = null;
55
+    /** @var FederatedShareProvider */
56
+    private $federatedProvider = null;
57
+    /** @var  ShareByMailProvider */
58
+    private $shareByMailProvider;
59
+    /** @var  \OCA\Circles\ShareByCircleProvider */
60
+    private $shareByCircleProvider = null;
61
+    /** @var bool */
62
+    private $circlesAreNotAvailable = false;
63
+
64
+    /**
65
+     * IProviderFactory constructor.
66
+     *
67
+     * @param IServerContainer $serverContainer
68
+     */
69
+    public function __construct(IServerContainer $serverContainer) {
70
+        $this->serverContainer = $serverContainer;
71
+    }
72
+
73
+    /**
74
+     * Create the default share provider.
75
+     *
76
+     * @return DefaultShareProvider
77
+     */
78
+    protected function defaultShareProvider() {
79
+        if ($this->defaultProvider === null) {
80
+            $this->defaultProvider = new DefaultShareProvider(
81
+                $this->serverContainer->getDatabaseConnection(),
82
+                $this->serverContainer->getUserManager(),
83
+                $this->serverContainer->getGroupManager(),
84
+                $this->serverContainer->getLazyRootFolder()
85
+            );
86
+        }
87
+
88
+        return $this->defaultProvider;
89
+    }
90
+
91
+    /**
92
+     * Create the federated share provider
93
+     *
94
+     * @return FederatedShareProvider
95
+     */
96
+    protected function federatedShareProvider() {
97
+        if ($this->federatedProvider === null) {
98
+            /*
99 99
 			 * Check if the app is enabled
100 100
 			 */
101
-			$appManager = $this->serverContainer->getAppManager();
102
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
103
-				return null;
104
-			}
101
+            $appManager = $this->serverContainer->getAppManager();
102
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
103
+                return null;
104
+            }
105 105
 
106
-			/*
106
+            /*
107 107
 			 * TODO: add factory to federated sharing app
108 108
 			 */
109
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
110
-			$addressHandler = new AddressHandler(
111
-				$this->serverContainer->getURLGenerator(),
112
-				$l,
113
-				$this->serverContainer->getCloudIdManager()
114
-			);
115
-			$notifications = new Notifications(
116
-				$addressHandler,
117
-				$this->serverContainer->getHTTPClientService(),
118
-				$this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
119
-				$this->serverContainer->getJobList(),
120
-				\OC::$server->getCloudFederationProviderManager(),
121
-				\OC::$server->getCloudFederationFactory()
122
-			);
123
-			$tokenHandler = new TokenHandler(
124
-				$this->serverContainer->getSecureRandom()
125
-			);
126
-
127
-			$this->federatedProvider = new FederatedShareProvider(
128
-				$this->serverContainer->getDatabaseConnection(),
129
-				$addressHandler,
130
-				$notifications,
131
-				$tokenHandler,
132
-				$l,
133
-				$this->serverContainer->getLogger(),
134
-				$this->serverContainer->getLazyRootFolder(),
135
-				$this->serverContainer->getConfig(),
136
-				$this->serverContainer->getUserManager(),
137
-				$this->serverContainer->getCloudIdManager(),
138
-				$this->serverContainer->getGlobalScaleConfig(),
139
-				$this->serverContainer->getCloudFederationProviderManager()
140
-			);
141
-		}
142
-
143
-		return $this->federatedProvider;
144
-	}
145
-
146
-	/**
147
-	 * Create the federated share provider
148
-	 *
149
-	 * @return ShareByMailProvider
150
-	 */
151
-	protected function getShareByMailProvider() {
152
-		if ($this->shareByMailProvider === null) {
153
-			/*
109
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
110
+            $addressHandler = new AddressHandler(
111
+                $this->serverContainer->getURLGenerator(),
112
+                $l,
113
+                $this->serverContainer->getCloudIdManager()
114
+            );
115
+            $notifications = new Notifications(
116
+                $addressHandler,
117
+                $this->serverContainer->getHTTPClientService(),
118
+                $this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
119
+                $this->serverContainer->getJobList(),
120
+                \OC::$server->getCloudFederationProviderManager(),
121
+                \OC::$server->getCloudFederationFactory()
122
+            );
123
+            $tokenHandler = new TokenHandler(
124
+                $this->serverContainer->getSecureRandom()
125
+            );
126
+
127
+            $this->federatedProvider = new FederatedShareProvider(
128
+                $this->serverContainer->getDatabaseConnection(),
129
+                $addressHandler,
130
+                $notifications,
131
+                $tokenHandler,
132
+                $l,
133
+                $this->serverContainer->getLogger(),
134
+                $this->serverContainer->getLazyRootFolder(),
135
+                $this->serverContainer->getConfig(),
136
+                $this->serverContainer->getUserManager(),
137
+                $this->serverContainer->getCloudIdManager(),
138
+                $this->serverContainer->getGlobalScaleConfig(),
139
+                $this->serverContainer->getCloudFederationProviderManager()
140
+            );
141
+        }
142
+
143
+        return $this->federatedProvider;
144
+    }
145
+
146
+    /**
147
+     * Create the federated share provider
148
+     *
149
+     * @return ShareByMailProvider
150
+     */
151
+    protected function getShareByMailProvider() {
152
+        if ($this->shareByMailProvider === null) {
153
+            /*
154 154
 			 * Check if the app is enabled
155 155
 			 */
156
-			$appManager = $this->serverContainer->getAppManager();
157
-			if (!$appManager->isEnabledForUser('sharebymail')) {
158
-				return null;
159
-			}
160
-
161
-			$settingsManager = new SettingsManager($this->serverContainer->getConfig());
162
-
163
-			$this->shareByMailProvider = new ShareByMailProvider(
164
-				$this->serverContainer->getDatabaseConnection(),
165
-				$this->serverContainer->getSecureRandom(),
166
-				$this->serverContainer->getUserManager(),
167
-				$this->serverContainer->getLazyRootFolder(),
168
-				$this->serverContainer->getL10N('sharebymail'),
169
-				$this->serverContainer->getLogger(),
170
-				$this->serverContainer->getMailer(),
171
-				$this->serverContainer->getURLGenerator(),
172
-				$this->serverContainer->getActivityManager(),
173
-				$settingsManager,
174
-				$this->serverContainer->query(Defaults::class),
175
-				$this->serverContainer->getHasher(),
176
-				$this->serverContainer->query(CapabilitiesManager::class)
177
-			);
178
-		}
179
-
180
-		return $this->shareByMailProvider;
181
-	}
182
-
183
-
184
-	/**
185
-	 * Create the circle share provider
186
-	 *
187
-	 * @return FederatedShareProvider
188
-	 *
189
-	 * @suppress PhanUndeclaredClassMethod
190
-	 */
191
-	protected function getShareByCircleProvider() {
192
-
193
-		if ($this->circlesAreNotAvailable) {
194
-			return null;
195
-		}
196
-
197
-		if (!$this->serverContainer->getAppManager()->isEnabledForUser('circles') ||
198
-			!class_exists('\OCA\Circles\ShareByCircleProvider')
199
-		) {
200
-			$this->circlesAreNotAvailable = true;
201
-			return null;
202
-		}
203
-
204
-		if ($this->shareByCircleProvider === null) {
205
-
206
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
207
-				$this->serverContainer->getDatabaseConnection(),
208
-				$this->serverContainer->getSecureRandom(),
209
-				$this->serverContainer->getUserManager(),
210
-				$this->serverContainer->getLazyRootFolder(),
211
-				$this->serverContainer->getL10N('circles'),
212
-				$this->serverContainer->getLogger(),
213
-				$this->serverContainer->getURLGenerator()
214
-			);
215
-		}
216
-
217
-		return $this->shareByCircleProvider;
218
-	}
219
-
220
-
221
-	/**
222
-	 * @inheritdoc
223
-	 */
224
-	public function getProvider($id) {
225
-		$provider = null;
226
-		if ($id === 'ocinternal') {
227
-			$provider = $this->defaultShareProvider();
228
-		} else if ($id === 'ocFederatedSharing') {
229
-			$provider = $this->federatedShareProvider();
230
-		} else if ($id === 'ocMailShare') {
231
-			$provider = $this->getShareByMailProvider();
232
-		} else if ($id === 'ocCircleShare') {
233
-			$provider = $this->getShareByCircleProvider();
234
-		}
235
-
236
-		if ($provider === null) {
237
-			throw new ProviderException('No provider with id .' . $id . ' found.');
238
-		}
239
-
240
-		return $provider;
241
-	}
242
-
243
-	/**
244
-	 * @inheritdoc
245
-	 */
246
-	public function getProviderForType($shareType) {
247
-		$provider = null;
248
-
249
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
250
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
251
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
252
-		) {
253
-			$provider = $this->defaultShareProvider();
254
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
255
-			$provider = $this->federatedShareProvider();
256
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
257
-			$provider = $this->getShareByMailProvider();
258
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
259
-			$provider = $this->getShareByCircleProvider();
260
-		}
261
-
262
-
263
-		if ($provider === null) {
264
-			throw new ProviderException('No share provider for share type ' . $shareType);
265
-		}
266
-
267
-		return $provider;
268
-	}
269
-
270
-	public function getAllProviders() {
271
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
272
-		$shareByMail = $this->getShareByMailProvider();
273
-		if ($shareByMail !== null) {
274
-			$shares[] = $shareByMail;
275
-		}
276
-		$shareByCircle = $this->getShareByCircleProvider();
277
-		if ($shareByCircle !== null) {
278
-			$shares[] = $shareByCircle;
279
-		}
280
-
281
-		return $shares;
282
-	}
156
+            $appManager = $this->serverContainer->getAppManager();
157
+            if (!$appManager->isEnabledForUser('sharebymail')) {
158
+                return null;
159
+            }
160
+
161
+            $settingsManager = new SettingsManager($this->serverContainer->getConfig());
162
+
163
+            $this->shareByMailProvider = new ShareByMailProvider(
164
+                $this->serverContainer->getDatabaseConnection(),
165
+                $this->serverContainer->getSecureRandom(),
166
+                $this->serverContainer->getUserManager(),
167
+                $this->serverContainer->getLazyRootFolder(),
168
+                $this->serverContainer->getL10N('sharebymail'),
169
+                $this->serverContainer->getLogger(),
170
+                $this->serverContainer->getMailer(),
171
+                $this->serverContainer->getURLGenerator(),
172
+                $this->serverContainer->getActivityManager(),
173
+                $settingsManager,
174
+                $this->serverContainer->query(Defaults::class),
175
+                $this->serverContainer->getHasher(),
176
+                $this->serverContainer->query(CapabilitiesManager::class)
177
+            );
178
+        }
179
+
180
+        return $this->shareByMailProvider;
181
+    }
182
+
183
+
184
+    /**
185
+     * Create the circle share provider
186
+     *
187
+     * @return FederatedShareProvider
188
+     *
189
+     * @suppress PhanUndeclaredClassMethod
190
+     */
191
+    protected function getShareByCircleProvider() {
192
+
193
+        if ($this->circlesAreNotAvailable) {
194
+            return null;
195
+        }
196
+
197
+        if (!$this->serverContainer->getAppManager()->isEnabledForUser('circles') ||
198
+            !class_exists('\OCA\Circles\ShareByCircleProvider')
199
+        ) {
200
+            $this->circlesAreNotAvailable = true;
201
+            return null;
202
+        }
203
+
204
+        if ($this->shareByCircleProvider === null) {
205
+
206
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
207
+                $this->serverContainer->getDatabaseConnection(),
208
+                $this->serverContainer->getSecureRandom(),
209
+                $this->serverContainer->getUserManager(),
210
+                $this->serverContainer->getLazyRootFolder(),
211
+                $this->serverContainer->getL10N('circles'),
212
+                $this->serverContainer->getLogger(),
213
+                $this->serverContainer->getURLGenerator()
214
+            );
215
+        }
216
+
217
+        return $this->shareByCircleProvider;
218
+    }
219
+
220
+
221
+    /**
222
+     * @inheritdoc
223
+     */
224
+    public function getProvider($id) {
225
+        $provider = null;
226
+        if ($id === 'ocinternal') {
227
+            $provider = $this->defaultShareProvider();
228
+        } else if ($id === 'ocFederatedSharing') {
229
+            $provider = $this->federatedShareProvider();
230
+        } else if ($id === 'ocMailShare') {
231
+            $provider = $this->getShareByMailProvider();
232
+        } else if ($id === 'ocCircleShare') {
233
+            $provider = $this->getShareByCircleProvider();
234
+        }
235
+
236
+        if ($provider === null) {
237
+            throw new ProviderException('No provider with id .' . $id . ' found.');
238
+        }
239
+
240
+        return $provider;
241
+    }
242
+
243
+    /**
244
+     * @inheritdoc
245
+     */
246
+    public function getProviderForType($shareType) {
247
+        $provider = null;
248
+
249
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
250
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
251
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
252
+        ) {
253
+            $provider = $this->defaultShareProvider();
254
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
255
+            $provider = $this->federatedShareProvider();
256
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
257
+            $provider = $this->getShareByMailProvider();
258
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
259
+            $provider = $this->getShareByCircleProvider();
260
+        }
261
+
262
+
263
+        if ($provider === null) {
264
+            throw new ProviderException('No share provider for share type ' . $shareType);
265
+        }
266
+
267
+        return $provider;
268
+    }
269
+
270
+    public function getAllProviders() {
271
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
272
+        $shareByMail = $this->getShareByMailProvider();
273
+        if ($shareByMail !== null) {
274
+            $shares[] = $shareByMail;
275
+        }
276
+        $shareByCircle = $this->getShareByCircleProvider();
277
+        if ($shareByCircle !== null) {
278
+            $shares[] = $shareByCircle;
279
+        }
280
+
281
+        return $shares;
282
+    }
283 283
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 1 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.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -39,117 +39,117 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/** @var FederatedShareProvider */
43
-	protected $federatedShareProvider;
42
+    /** @var FederatedShareProvider */
43
+    protected $federatedShareProvider;
44 44
 
45
-	public function __construct() {
46
-		parent::__construct('federatedfilesharing');
45
+    public function __construct() {
46
+        parent::__construct('federatedfilesharing');
47 47
 
48
-		$container = $this->getContainer();
49
-		$server = $container->getServer();
48
+        $container = $this->getContainer();
49
+        $server = $container->getServer();
50 50
 
51
-		$cloudFederationManager = $server->getCloudFederationProviderManager();
52
-		$cloudFederationManager->addCloudFederationProvider('file',
53
-			'Federated Files Sharing',
54
-			function() use ($container) {
55
-				$server = $container->getServer();
56
-				return new CloudFederationProviderFiles(
57
-					$server->getAppManager(),
58
-					$server->query(FederatedShareProvider::class),
59
-					$server->query(AddressHandler::class),
60
-					$server->getLogger(),
61
-					$server->getUserManager(),
62
-					$server->getCloudIdManager(),
63
-					$server->getActivityManager(),
64
-					$server->getNotificationManager(),
65
-					$server->getURLGenerator(),
66
-					$server->getCloudFederationFactory(),
67
-					$server->getCloudFederationProviderManager(),
68
-					$server->getDatabaseConnection(),
69
-					$server->getGroupManager()
70
-				);
71
-			});
51
+        $cloudFederationManager = $server->getCloudFederationProviderManager();
52
+        $cloudFederationManager->addCloudFederationProvider('file',
53
+            'Federated Files Sharing',
54
+            function() use ($container) {
55
+                $server = $container->getServer();
56
+                return new CloudFederationProviderFiles(
57
+                    $server->getAppManager(),
58
+                    $server->query(FederatedShareProvider::class),
59
+                    $server->query(AddressHandler::class),
60
+                    $server->getLogger(),
61
+                    $server->getUserManager(),
62
+                    $server->getCloudIdManager(),
63
+                    $server->getActivityManager(),
64
+                    $server->getNotificationManager(),
65
+                    $server->getURLGenerator(),
66
+                    $server->getCloudFederationFactory(),
67
+                    $server->getCloudFederationProviderManager(),
68
+                    $server->getDatabaseConnection(),
69
+                    $server->getGroupManager()
70
+                );
71
+            });
72 72
 
73
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
74
-			$addressHandler = new AddressHandler(
75
-				$server->getURLGenerator(),
76
-				$server->getL10N('federatedfilesharing'),
77
-				$server->getCloudIdManager()
78
-			);
79
-			$notification = new Notifications(
80
-				$addressHandler,
81
-				$server->getHTTPClientService(),
82
-				$server->query(\OCP\OCS\IDiscoveryService::class),
83
-				\OC::$server->getJobList(),
84
-				\OC::$server->getCloudFederationProviderManager(),
85
-				\OC::$server->getCloudFederationFactory()
86
-			);
87
-			return new RequestHandlerController(
88
-				$c->query('AppName'),
89
-				$server->getRequest(),
90
-				$this->getFederatedShareProvider(),
91
-				$server->getDatabaseConnection(),
92
-				$server->getShareManager(),
93
-				$notification,
94
-				$addressHandler,
95
-				$server->getUserManager(),
96
-				$server->getCloudIdManager(),
97
-				$server->getLogger(),
98
-				$server->getCloudFederationFactory(),
99
-				$server->getCloudFederationProviderManager()
100
-			);
101
-		});
102
-	}
73
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
74
+            $addressHandler = new AddressHandler(
75
+                $server->getURLGenerator(),
76
+                $server->getL10N('federatedfilesharing'),
77
+                $server->getCloudIdManager()
78
+            );
79
+            $notification = new Notifications(
80
+                $addressHandler,
81
+                $server->getHTTPClientService(),
82
+                $server->query(\OCP\OCS\IDiscoveryService::class),
83
+                \OC::$server->getJobList(),
84
+                \OC::$server->getCloudFederationProviderManager(),
85
+                \OC::$server->getCloudFederationFactory()
86
+            );
87
+            return new RequestHandlerController(
88
+                $c->query('AppName'),
89
+                $server->getRequest(),
90
+                $this->getFederatedShareProvider(),
91
+                $server->getDatabaseConnection(),
92
+                $server->getShareManager(),
93
+                $notification,
94
+                $addressHandler,
95
+                $server->getUserManager(),
96
+                $server->getCloudIdManager(),
97
+                $server->getLogger(),
98
+                $server->getCloudFederationFactory(),
99
+                $server->getCloudFederationProviderManager()
100
+            );
101
+        });
102
+    }
103 103
 
104
-	/**
105
-	 * get instance of federated share provider
106
-	 *
107
-	 * @return FederatedShareProvider
108
-	 */
109
-	public function getFederatedShareProvider() {
110
-		if ($this->federatedShareProvider === null) {
111
-			$this->initFederatedShareProvider();
112
-		}
113
-		return $this->federatedShareProvider;
114
-	}
104
+    /**
105
+     * get instance of federated share provider
106
+     *
107
+     * @return FederatedShareProvider
108
+     */
109
+    public function getFederatedShareProvider() {
110
+        if ($this->federatedShareProvider === null) {
111
+            $this->initFederatedShareProvider();
112
+        }
113
+        return $this->federatedShareProvider;
114
+    }
115 115
 
116
-	/**
117
-	 * initialize federated share provider
118
-	 */
119
-	protected function initFederatedShareProvider() {
120
-		$c = $this->getContainer();
121
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
122
-			\OC::$server->getURLGenerator(),
123
-			\OC::$server->getL10N('federatedfilesharing'),
124
-			\OC::$server->getCloudIdManager()
125
-		);
126
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
127
-			$addressHandler,
128
-			\OC::$server->getHTTPClientService(),
129
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
130
-			\OC::$server->getJobList(),
131
-			\OC::$server->getCloudFederationProviderManager(),
132
-			\OC::$server->getCloudFederationFactory()
133
-		);
134
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
135
-			\OC::$server->getSecureRandom()
136
-		);
116
+    /**
117
+     * initialize federated share provider
118
+     */
119
+    protected function initFederatedShareProvider() {
120
+        $c = $this->getContainer();
121
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
122
+            \OC::$server->getURLGenerator(),
123
+            \OC::$server->getL10N('federatedfilesharing'),
124
+            \OC::$server->getCloudIdManager()
125
+        );
126
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
127
+            $addressHandler,
128
+            \OC::$server->getHTTPClientService(),
129
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
130
+            \OC::$server->getJobList(),
131
+            \OC::$server->getCloudFederationProviderManager(),
132
+            \OC::$server->getCloudFederationFactory()
133
+        );
134
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
135
+            \OC::$server->getSecureRandom()
136
+        );
137 137
 
138
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
139
-			\OC::$server->getDatabaseConnection(),
140
-			$addressHandler,
141
-			$notifications,
142
-			$tokenHandler,
143
-			\OC::$server->getL10N('federatedfilesharing'),
144
-			\OC::$server->getLogger(),
145
-			\OC::$server->getLazyRootFolder(),
146
-			\OC::$server->getConfig(),
147
-			\OC::$server->getUserManager(),
148
-			\OC::$server->getCloudIdManager(),
149
-			$c->query(IConfig::class),
150
-			\OC::$server->getCloudFederationProviderManager()
138
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
139
+            \OC::$server->getDatabaseConnection(),
140
+            $addressHandler,
141
+            $notifications,
142
+            $tokenHandler,
143
+            \OC::$server->getL10N('federatedfilesharing'),
144
+            \OC::$server->getLogger(),
145
+            \OC::$server->getLazyRootFolder(),
146
+            \OC::$server->getConfig(),
147
+            \OC::$server->getUserManager(),
148
+            \OC::$server->getCloudIdManager(),
149
+            $c->query(IConfig::class),
150
+            \OC::$server->getCloudFederationProviderManager()
151 151
 
152
-		);
153
-	}
152
+        );
153
+    }
154 154
 
155 155
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 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.
apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php 1 patch
Indentation   +778 added lines, -778 removed lines patch added patch discarded remove patch
@@ -52,782 +52,782 @@
 block discarded – undo
52 52
 
53 53
 class CloudFederationProviderFiles implements ICloudFederationProvider {
54 54
 
55
-	/** @var IAppManager */
56
-	private $appManager;
57
-
58
-	/** @var FederatedShareProvider */
59
-	private $federatedShareProvider;
60
-
61
-	/** @var AddressHandler */
62
-	private $addressHandler;
63
-
64
-	/** @var ILogger */
65
-	private $logger;
66
-
67
-	/** @var IUserManager */
68
-	private $userManager;
69
-
70
-	/** @var ICloudIdManager */
71
-	private $cloudIdManager;
72
-
73
-	/** @var IActivityManager */
74
-	private $activityManager;
75
-
76
-	/** @var INotificationManager */
77
-	private $notificationManager;
78
-
79
-	/** @var IURLGenerator */
80
-	private $urlGenerator;
81
-
82
-	/** @var ICloudFederationFactory */
83
-	private $cloudFederationFactory;
84
-
85
-	/** @var ICloudFederationProviderManager */
86
-	private $cloudFederationProviderManager;
87
-
88
-	/** @var IDBConnection */
89
-	private $connection;
90
-
91
-	/** @var IGroupManager */
92
-	private $groupManager;
93
-
94
-	/**
95
-	 * CloudFederationProvider constructor.
96
-	 *
97
-	 * @param IAppManager $appManager
98
-	 * @param FederatedShareProvider $federatedShareProvider
99
-	 * @param AddressHandler $addressHandler
100
-	 * @param ILogger $logger
101
-	 * @param IUserManager $userManager
102
-	 * @param ICloudIdManager $cloudIdManager
103
-	 * @param IActivityManager $activityManager
104
-	 * @param INotificationManager $notificationManager
105
-	 * @param IURLGenerator $urlGenerator
106
-	 * @param ICloudFederationFactory $cloudFederationFactory
107
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
108
-	 * @param IDBConnection $connection
109
-	 * @param IGroupManager $groupManager
110
-	 */
111
-	public function __construct(IAppManager $appManager,
112
-								FederatedShareProvider $federatedShareProvider,
113
-								AddressHandler $addressHandler,
114
-								ILogger $logger,
115
-								IUserManager $userManager,
116
-								ICloudIdManager $cloudIdManager,
117
-								IActivityManager $activityManager,
118
-								INotificationManager $notificationManager,
119
-								IURLGenerator $urlGenerator,
120
-								ICloudFederationFactory $cloudFederationFactory,
121
-								ICloudFederationProviderManager $cloudFederationProviderManager,
122
-								IDBConnection $connection,
123
-								IGroupManager $groupManager
124
-	) {
125
-		$this->appManager = $appManager;
126
-		$this->federatedShareProvider = $federatedShareProvider;
127
-		$this->addressHandler = $addressHandler;
128
-		$this->logger = $logger;
129
-		$this->userManager = $userManager;
130
-		$this->cloudIdManager = $cloudIdManager;
131
-		$this->activityManager = $activityManager;
132
-		$this->notificationManager = $notificationManager;
133
-		$this->urlGenerator = $urlGenerator;
134
-		$this->cloudFederationFactory = $cloudFederationFactory;
135
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
136
-		$this->connection = $connection;
137
-		$this->groupManager = $groupManager;
138
-	}
139
-
140
-
141
-
142
-	/**
143
-	 * @return string
144
-	 */
145
-	public function getShareType() {
146
-		return 'file';
147
-	}
148
-
149
-	/**
150
-	 * share received from another server
151
-	 *
152
-	 * @param ICloudFederationShare $share
153
-	 * @return string provider specific unique ID of the share
154
-	 *
155
-	 * @throws ProviderCouldNotAddShareException
156
-	 * @throws \OCP\AppFramework\QueryException
157
-	 * @throws \OC\HintException
158
-	 * @since 14.0.0
159
-	 */
160
-	public function shareReceived(ICloudFederationShare $share) {
161
-
162
-		if (!$this->isS2SEnabled(true)) {
163
-			throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
164
-		}
165
-
166
-		$protocol = $share->getProtocol();
167
-		if ($protocol['name'] !== 'webdav') {
168
-			throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
169
-		}
170
-
171
-		list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
172
-		// for backward compatibility make sure that the remote url stored in the
173
-		// database ends with a trailing slash
174
-		if (substr($remote, -1) !== '/') {
175
-			$remote = $remote . '/';
176
-		}
177
-
178
-		$token = $share->getShareSecret();
179
-		$name = $share->getResourceName();
180
-		$owner = $share->getOwnerDisplayName();
181
-		$sharedBy = $share->getSharedByDisplayName();
182
-		$shareWith = $share->getShareWith();
183
-		$remoteId = $share->getProviderId();
184
-		$sharedByFederatedId = $share->getSharedBy();
185
-		$ownerFederatedId = $share->getOwner();
186
-		$shareType = $this->mapShareTypeToNextcloud($share->getShareType());
187
-
188
-		// if no explicit information about the person who created the share was send
189
-		// we assume that the share comes from the owner
190
-		if ($sharedByFederatedId === null) {
191
-			$sharedBy = $owner;
192
-			$sharedByFederatedId = $ownerFederatedId;
193
-		}
194
-
195
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
196
-
197
-			if (!Util::isValidFileName($name)) {
198
-				throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
199
-			}
200
-
201
-			// FIXME this should be a method in the user management instead
202
-			if ($shareType === Share::SHARE_TYPE_USER) {
203
-				$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
204
-				Util::emitHook(
205
-					'\OCA\Files_Sharing\API\Server2Server',
206
-					'preLoginNameUsedAsUserName',
207
-					array('uid' => &$shareWith)
208
-				);
209
-				$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
210
-
211
-				if (!$this->userManager->userExists($shareWith)) {
212
-					throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
213
-				}
214
-
215
-				\OC_Util::setupFS($shareWith);
216
-			}
217
-
218
-			if ($shareType === Share::SHARE_TYPE_GROUP && !$this->groupManager->groupExists($shareWith)) {
219
-				throw new ProviderCouldNotAddShareException('Group does not exists', '',Http::STATUS_BAD_REQUEST);
220
-			}
221
-
222
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
223
-				\OC::$server->getDatabaseConnection(),
224
-				Filesystem::getMountManager(),
225
-				Filesystem::getLoader(),
226
-				\OC::$server->getHTTPClientService(),
227
-				\OC::$server->getNotificationManager(),
228
-				\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
229
-				\OC::$server->getCloudFederationProviderManager(),
230
-				\OC::$server->getCloudFederationFactory(),
231
-				\OC::$server->getGroupManager(),
232
-				\OC::$server->getUserManager(),
233
-				$shareWith
234
-			);
235
-
236
-			try {
237
-				$externalManager->addShare($remote, $token, '', $name, $owner, $shareType,false, $shareWith, $remoteId);
238
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
239
-
240
-				if ($shareType === Share::SHARE_TYPE_USER) {
241
-					$event = $this->activityManager->generateEvent();
242
-					$event->setApp('files_sharing')
243
-						->setType('remote_share')
244
-						->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
245
-						->setAffectedUser($shareWith)
246
-						->setObject('remote_share', (int)$shareId, $name);
247
-					\OC::$server->getActivityManager()->publish($event);
248
-					$this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
249
-				} else {
250
-					$groupMembers = $this->groupManager->get($shareWith)->getUsers();
251
-					foreach ($groupMembers as $user) {
252
-						$event = $this->activityManager->generateEvent();
253
-						$event->setApp('files_sharing')
254
-							->setType('remote_share')
255
-							->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
256
-							->setAffectedUser($user->getUID())
257
-							->setObject('remote_share', (int)$shareId, $name);
258
-						\OC::$server->getActivityManager()->publish($event);
259
-						$this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
260
-					}
261
-				}
262
-				return $shareId;
263
-			} catch (\Exception $e) {
264
-				$this->logger->logException($e, [
265
-					'message' => 'Server can not add remote share.',
266
-					'level' => ILogger::ERROR,
267
-					'app' => 'files_sharing'
268
-				]);
269
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
270
-			}
271
-		}
272
-
273
-		throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
274
-
275
-	}
276
-
277
-	/**
278
-	 * notification received from another server
279
-	 *
280
-	 * @param string $notificationType (e.g. SHARE_ACCEPTED)
281
-	 * @param string $providerId id of the share
282
-	 * @param array $notification payload of the notification
283
-	 * @return array data send back to the sender
284
-	 *
285
-	 * @throws ActionNotSupportedException
286
-	 * @throws AuthenticationFailedException
287
-	 * @throws BadRequestException
288
-	 * @throws \OC\HintException
289
-	 * @since 14.0.0
290
-	 */
291
-	public function notificationReceived($notificationType, $providerId, array $notification) {
292
-
293
-		switch ($notificationType) {
294
-			case 'SHARE_ACCEPTED':
295
-				return $this->shareAccepted($providerId, $notification);
296
-			case 'SHARE_DECLINED':
297
-				return $this->shareDeclined($providerId, $notification);
298
-			case 'SHARE_UNSHARED':
299
-				return $this->unshare($providerId, $notification);
300
-			case 'REQUEST_RESHARE':
301
-				return $this->reshareRequested($providerId, $notification);
302
-			case 'RESHARE_UNDO':
303
-				return $this->undoReshare($providerId, $notification);
304
-			case 'RESHARE_CHANGE_PERMISSION':
305
-				return $this->updateResharePermissions($providerId, $notification);
306
-		}
307
-
308
-
309
-		throw new BadRequestException([$notificationType]);
310
-	}
311
-
312
-	/**
313
-	 * map OCM share type (strings) to Nextcloud internal share types (integer)
314
-	 *
315
-	 * @param string $shareType
316
-	 * @return int
317
-	 */
318
-	private function mapShareTypeToNextcloud($shareType) {
319
-		$result = Share::SHARE_TYPE_USER;
320
-		if ($shareType === 'group') {
321
-			$result = Share::SHARE_TYPE_GROUP;
322
-		}
323
-
324
-		return $result;
325
-	}
326
-
327
-	/**
328
-	 * notify user about new federated share
329
-	 *
330
-	 * @param $shareWith
331
-	 * @param $shareId
332
-	 * @param $ownerFederatedId
333
-	 * @param $sharedByFederatedId
334
-	 * @param $name
335
-	 */
336
-	private function notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name) {
337
-		$notification = $this->notificationManager->createNotification();
338
-		$notification->setApp('files_sharing')
339
-			->setUser($shareWith)
340
-			->setDateTime(new \DateTime())
341
-			->setObject('remote_share', $shareId)
342
-			->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
343
-
344
-		$declineAction = $notification->createAction();
345
-		$declineAction->setLabel('decline')
346
-			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
347
-		$notification->addAction($declineAction);
348
-
349
-		$acceptAction = $notification->createAction();
350
-		$acceptAction->setLabel('accept')
351
-			->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
352
-		$notification->addAction($acceptAction);
353
-
354
-		$this->notificationManager->notify($notification);
355
-	}
356
-
357
-	/**
358
-	 * process notification that the recipient accepted a share
359
-	 *
360
-	 * @param string $id
361
-	 * @param array $notification
362
-	 * @return array
363
-	 * @throws ActionNotSupportedException
364
-	 * @throws AuthenticationFailedException
365
-	 * @throws BadRequestException
366
-	 * @throws \OC\HintException
367
-	 */
368
-	private function shareAccepted($id, array $notification) {
369
-
370
-		if (!$this->isS2SEnabled()) {
371
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
372
-		}
373
-
374
-		if (!isset($notification['sharedSecret'])) {
375
-			throw new BadRequestException(['sharedSecret']);
376
-		}
377
-
378
-		$token = $notification['sharedSecret'];
379
-
380
-		$share = $this->federatedShareProvider->getShareById($id);
381
-
382
-		$this->verifyShare($share, $token);
383
-		$this->executeAcceptShare($share);
384
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
385
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
386
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
387
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
388
-			$notification->setMessage(
389
-				'SHARE_ACCEPTED',
390
-				'file',
391
-				$remoteId,
392
-				[
393
-					'sharedSecret' => $token,
394
-					'message' => 'Recipient accepted the re-share'
395
-				]
396
-
397
-			);
398
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
399
-
400
-		}
401
-
402
-		return [];
403
-	}
404
-
405
-	/**
406
-	 * @param IShare $share
407
-	 * @throws ShareNotFound
408
-	 */
409
-	protected function executeAcceptShare(IShare $share) {
410
-		try {
411
-			$fileId = (int)$share->getNode()->getId();
412
-			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
413
-		} catch (\Exception $e) {
414
-			throw new ShareNotFound();
415
-		}
416
-
417
-		$event = $this->activityManager->generateEvent();
418
-		$event->setApp('files_sharing')
419
-			->setType('remote_share')
420
-			->setAffectedUser($this->getCorrectUid($share))
421
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
422
-			->setObject('files', $fileId, $file)
423
-			->setLink($link);
424
-		$this->activityManager->publish($event);
425
-	}
426
-
427
-	/**
428
-	 * process notification that the recipient declined a share
429
-	 *
430
-	 * @param string $id
431
-	 * @param array $notification
432
-	 * @return array
433
-	 * @throws ActionNotSupportedException
434
-	 * @throws AuthenticationFailedException
435
-	 * @throws BadRequestException
436
-	 * @throws ShareNotFound
437
-	 * @throws \OC\HintException
438
-	 *
439
-	 */
440
-	protected function shareDeclined($id, array $notification) {
441
-
442
-		if (!$this->isS2SEnabled()) {
443
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
444
-		}
445
-
446
-		if (!isset($notification['sharedSecret'])) {
447
-			throw new BadRequestException(['sharedSecret']);
448
-		}
449
-
450
-		$token = $notification['sharedSecret'];
451
-
452
-		$share = $this->federatedShareProvider->getShareById($id);
453
-
454
-		$this->verifyShare($share, $token);
455
-
456
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
457
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
458
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
459
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
460
-			$notification->setMessage(
461
-				'SHARE_DECLINED',
462
-				'file',
463
-				$remoteId,
464
-				[
465
-					'sharedSecret' => $token,
466
-					'message' => 'Recipient declined the re-share'
467
-				]
468
-
469
-			);
470
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
471
-		}
472
-
473
-		$this->executeDeclineShare($share);
474
-
475
-		return [];
476
-
477
-	}
478
-
479
-	/**
480
-	 * delete declined share and create a activity
481
-	 *
482
-	 * @param IShare $share
483
-	 * @throws ShareNotFound
484
-	 */
485
-	protected function executeDeclineShare(IShare $share) {
486
-		$this->federatedShareProvider->removeShareFromTable($share);
487
-
488
-		try {
489
-			$fileId = (int)$share->getNode()->getId();
490
-			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
491
-		} catch (\Exception $e) {
492
-			throw new ShareNotFound();
493
-		}
494
-
495
-		$event = $this->activityManager->generateEvent();
496
-		$event->setApp('files_sharing')
497
-			->setType('remote_share')
498
-			->setAffectedUser($this->getCorrectUid($share))
499
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
500
-			->setObject('files', $fileId, $file)
501
-			->setLink($link);
502
-		$this->activityManager->publish($event);
503
-
504
-	}
505
-
506
-	/**
507
-	 * received the notification that the owner unshared a file from you
508
-	 *
509
-	 * @param string $id
510
-	 * @param array $notification
511
-	 * @return array
512
-	 * @throws AuthenticationFailedException
513
-	 * @throws BadRequestException
514
-	 */
515
-	private function undoReshare($id, array $notification) {
516
-		if (!isset($notification['sharedSecret'])) {
517
-			throw new BadRequestException(['sharedSecret']);
518
-		}
519
-		$token = $notification['sharedSecret'];
520
-
521
-		$share = $this->federatedShareProvider->getShareById($id);
522
-
523
-		$this->verifyShare($share, $token);
524
-		$this->federatedShareProvider->removeShareFromTable($share);
525
-		return [];
526
-	}
527
-
528
-	/**
529
-	 * unshare file from self
530
-	 *
531
-	 * @param string $id
532
-	 * @param array $notification
533
-	 * @return array
534
-	 * @throws ActionNotSupportedException
535
-	 * @throws BadRequestException
536
-	 */
537
-	private function unshare($id, array $notification) {
538
-
539
-		if (!$this->isS2SEnabled(true)) {
540
-			throw new ActionNotSupportedException("incoming shares disabled!");
541
-		}
542
-
543
-		if (!isset($notification['sharedSecret'])) {
544
-			throw new BadRequestException(['sharedSecret']);
545
-		}
546
-		$token = $notification['sharedSecret'];
547
-
548
-		$qb = $this->connection->getQueryBuilder();
549
-		$qb->select('*')
550
-			->from('share_external')
551
-			->where(
552
-				$qb->expr()->andX(
553
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
554
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
555
-				)
556
-			);
557
-
558
-		$result = $qb->execute();
559
-		$share = $result->fetch();
560
-		$result->closeCursor();
561
-
562
-		if ($token && $id && !empty($share)) {
563
-
564
-			$remote = $this->cleanupRemote($share['remote']);
565
-
566
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
567
-			$mountpoint = $share['mountpoint'];
568
-			$user = $share['user'];
569
-
570
-			$qb = $this->connection->getQueryBuilder();
571
-			$qb->delete('share_external')
572
-				->where(
573
-					$qb->expr()->andX(
574
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
575
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
576
-					)
577
-				);
578
-
579
-			$qb->execute();
580
-
581
-			if ($share['accepted']) {
582
-				$path = trim($mountpoint, '/');
583
-			} else {
584
-				$path = trim($share['name'], '/');
585
-			}
586
-
587
-			$notification = $this->notificationManager->createNotification();
588
-			$notification->setApp('files_sharing')
589
-				->setUser($share['user'])
590
-				->setObject('remote_share', (int)$share['id']);
591
-			$this->notificationManager->markProcessed($notification);
592
-
593
-			$event = $this->activityManager->generateEvent();
594
-			$event->setApp('files_sharing')
595
-				->setType('remote_share')
596
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
597
-				->setAffectedUser($user)
598
-				->setObject('remote_share', (int)$share['id'], $path);
599
-			\OC::$server->getActivityManager()->publish($event);
600
-		}
601
-
602
-		return [];
603
-	}
604
-
605
-	private function cleanupRemote($remote) {
606
-		$remote = substr($remote, strpos($remote, '://') + 3);
607
-
608
-		return rtrim($remote, '/');
609
-	}
610
-
611
-	/**
612
-	 * recipient of a share request to re-share the file with another user
613
-	 *
614
-	 * @param string $id
615
-	 * @param array $notification
616
-	 * @return array
617
-	 * @throws AuthenticationFailedException
618
-	 * @throws BadRequestException
619
-	 * @throws ProviderCouldNotAddShareException
620
-	 * @throws ShareNotFound
621
-	 */
622
-	protected function reshareRequested($id, array $notification) {
623
-
624
-		if (!isset($notification['sharedSecret'])) {
625
-			throw new BadRequestException(['sharedSecret']);
626
-		}
627
-		$token = $notification['sharedSecret'];
628
-
629
-		if (!isset($notification['shareWith'])) {
630
-			throw new BadRequestException(['shareWith']);
631
-		}
632
-		$shareWith = $notification['shareWith'];
633
-
634
-		if (!isset($notification['senderId'])) {
635
-			throw new BadRequestException(['senderId']);
636
-		}
637
-		$senderId = $notification['senderId'];
638
-
639
-		$share = $this->federatedShareProvider->getShareById($id);
640
-		// don't allow to share a file back to the owner
641
-		try {
642
-			list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
643
-			$owner = $share->getShareOwner();
644
-			$currentServer = $this->addressHandler->generateRemoteURL();
645
-			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
646
-				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
647
-			}
648
-		} catch (\Exception $e) {
649
-			throw new ProviderCouldNotAddShareException($e->getMessage());
650
-		}
651
-
652
-		$this->verifyShare($share, $token);
653
-
654
-		// check if re-sharing is allowed
655
-		if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
656
-			// the recipient of the initial share is now the initiator for the re-share
657
-			$share->setSharedBy($share->getSharedWith());
658
-			$share->setSharedWith($shareWith);
659
-			$result = $this->federatedShareProvider->create($share);
660
-			$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
661
-			return ['token' => $result->getToken(), 'providerId' => $result->getId()];
662
-		} else {
663
-			throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
664
-		}
665
-
666
-	}
667
-
668
-	/**
669
-	 * update permission of a re-share so that the share dialog shows the right
670
-	 * permission if the owner or the sender changes the permission
671
-	 *
672
-	 * @param string $id
673
-	 * @param array $notification
674
-	 * @return array
675
-	 * @throws AuthenticationFailedException
676
-	 * @throws BadRequestException
677
-	 */
678
-	protected function updateResharePermissions($id, array $notification) {
679
-
680
-		if (!isset($notification['sharedSecret'])) {
681
-			throw new BadRequestException(['sharedSecret']);
682
-		}
683
-		$token = $notification['sharedSecret'];
684
-
685
-		if (!isset($notification['permission'])) {
686
-			throw new BadRequestException(['permission']);
687
-		}
688
-		$ocmPermissions = $notification['permission'];
689
-
690
-		$share = $this->federatedShareProvider->getShareById($id);
691
-
692
-		$ncPermission = $this->ocmPermissions2ncPermissions($ocmPermissions);
693
-
694
-		$this->verifyShare($share, $token);
695
-		$this->updatePermissionsInDatabase($share, $ncPermission);
696
-
697
-		return [];
698
-	}
699
-
700
-	/**
701
-	 * translate OCM Permissions to Nextcloud permissions
702
-	 *
703
-	 * @param array $ocmPermissions
704
-	 * @return int
705
-	 * @throws BadRequestException
706
-	 */
707
-	protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
708
-		$ncPermissions = 0;
709
-		foreach($ocmPermissions as $permission) {
710
-			switch (strtolower($permission)) {
711
-				case 'read':
712
-					$ncPermissions += Constants::PERMISSION_READ;
713
-					break;
714
-				case 'write':
715
-					$ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
716
-					break;
717
-				case 'share':
718
-					$ncPermissions += Constants::PERMISSION_SHARE;
719
-					break;
720
-				default:
721
-					throw new BadRequestException(['permission']);
722
-			}
723
-
724
-		}
725
-
726
-		return $ncPermissions;
727
-	}
728
-
729
-	/**
730
-	 * update permissions in database
731
-	 *
732
-	 * @param IShare $share
733
-	 * @param int $permissions
734
-	 */
735
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
736
-		$query = $this->connection->getQueryBuilder();
737
-		$query->update('share')
738
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
739
-			->set('permissions', $query->createNamedParameter($permissions))
740
-			->execute();
741
-	}
742
-
743
-
744
-	/**
745
-	 * get file
746
-	 *
747
-	 * @param string $user
748
-	 * @param int $fileSource
749
-	 * @return array with internal path of the file and a absolute link to it
750
-	 */
751
-	private function getFile($user, $fileSource) {
752
-		\OC_Util::setupFS($user);
753
-
754
-		try {
755
-			$file = Filesystem::getPath($fileSource);
756
-		} catch (NotFoundException $e) {
757
-			$file = null;
758
-		}
759
-		$args = Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
760
-		$link = Util::linkToAbsolute('files', 'index.php', $args);
761
-
762
-		return [$file, $link];
763
-
764
-	}
765
-
766
-	/**
767
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
768
-	 *
769
-	 * @param IShare $share
770
-	 * @return string
771
-	 */
772
-	protected function getCorrectUid(IShare $share) {
773
-		if ($this->userManager->userExists($share->getShareOwner())) {
774
-			return $share->getShareOwner();
775
-		}
776
-
777
-		return $share->getSharedBy();
778
-	}
779
-
780
-
781
-
782
-	/**
783
-	 * check if we got the right share
784
-	 *
785
-	 * @param IShare $share
786
-	 * @param string $token
787
-	 * @return bool
788
-	 * @throws AuthenticationFailedException
789
-	 */
790
-	protected function verifyShare(IShare $share, $token) {
791
-		if (
792
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
793
-			$share->getToken() === $token
794
-		) {
795
-			return true;
796
-		}
797
-
798
-		throw new AuthenticationFailedException();
799
-	}
800
-
801
-
802
-
803
-	/**
804
-	 * check if server-to-server sharing is enabled
805
-	 *
806
-	 * @param bool $incoming
807
-	 * @return bool
808
-	 */
809
-	private function isS2SEnabled($incoming = false) {
810
-
811
-		$result = $this->appManager->isEnabledForUser('files_sharing');
812
-
813
-		if ($incoming) {
814
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
815
-		} else {
816
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
817
-		}
818
-
819
-		return $result;
820
-	}
821
-
822
-
823
-	/**
824
-	 * get the supported share types, e.g. "user", "group", etc.
825
-	 *
826
-	 * @return array
827
-	 *
828
-	 * @since 14.0.0
829
-	 */
830
-	public function getSupportedShareTypes() {
831
-		return ['user', 'group'];
832
-	}
55
+    /** @var IAppManager */
56
+    private $appManager;
57
+
58
+    /** @var FederatedShareProvider */
59
+    private $federatedShareProvider;
60
+
61
+    /** @var AddressHandler */
62
+    private $addressHandler;
63
+
64
+    /** @var ILogger */
65
+    private $logger;
66
+
67
+    /** @var IUserManager */
68
+    private $userManager;
69
+
70
+    /** @var ICloudIdManager */
71
+    private $cloudIdManager;
72
+
73
+    /** @var IActivityManager */
74
+    private $activityManager;
75
+
76
+    /** @var INotificationManager */
77
+    private $notificationManager;
78
+
79
+    /** @var IURLGenerator */
80
+    private $urlGenerator;
81
+
82
+    /** @var ICloudFederationFactory */
83
+    private $cloudFederationFactory;
84
+
85
+    /** @var ICloudFederationProviderManager */
86
+    private $cloudFederationProviderManager;
87
+
88
+    /** @var IDBConnection */
89
+    private $connection;
90
+
91
+    /** @var IGroupManager */
92
+    private $groupManager;
93
+
94
+    /**
95
+     * CloudFederationProvider constructor.
96
+     *
97
+     * @param IAppManager $appManager
98
+     * @param FederatedShareProvider $federatedShareProvider
99
+     * @param AddressHandler $addressHandler
100
+     * @param ILogger $logger
101
+     * @param IUserManager $userManager
102
+     * @param ICloudIdManager $cloudIdManager
103
+     * @param IActivityManager $activityManager
104
+     * @param INotificationManager $notificationManager
105
+     * @param IURLGenerator $urlGenerator
106
+     * @param ICloudFederationFactory $cloudFederationFactory
107
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
108
+     * @param IDBConnection $connection
109
+     * @param IGroupManager $groupManager
110
+     */
111
+    public function __construct(IAppManager $appManager,
112
+                                FederatedShareProvider $federatedShareProvider,
113
+                                AddressHandler $addressHandler,
114
+                                ILogger $logger,
115
+                                IUserManager $userManager,
116
+                                ICloudIdManager $cloudIdManager,
117
+                                IActivityManager $activityManager,
118
+                                INotificationManager $notificationManager,
119
+                                IURLGenerator $urlGenerator,
120
+                                ICloudFederationFactory $cloudFederationFactory,
121
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
122
+                                IDBConnection $connection,
123
+                                IGroupManager $groupManager
124
+    ) {
125
+        $this->appManager = $appManager;
126
+        $this->federatedShareProvider = $federatedShareProvider;
127
+        $this->addressHandler = $addressHandler;
128
+        $this->logger = $logger;
129
+        $this->userManager = $userManager;
130
+        $this->cloudIdManager = $cloudIdManager;
131
+        $this->activityManager = $activityManager;
132
+        $this->notificationManager = $notificationManager;
133
+        $this->urlGenerator = $urlGenerator;
134
+        $this->cloudFederationFactory = $cloudFederationFactory;
135
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
136
+        $this->connection = $connection;
137
+        $this->groupManager = $groupManager;
138
+    }
139
+
140
+
141
+
142
+    /**
143
+     * @return string
144
+     */
145
+    public function getShareType() {
146
+        return 'file';
147
+    }
148
+
149
+    /**
150
+     * share received from another server
151
+     *
152
+     * @param ICloudFederationShare $share
153
+     * @return string provider specific unique ID of the share
154
+     *
155
+     * @throws ProviderCouldNotAddShareException
156
+     * @throws \OCP\AppFramework\QueryException
157
+     * @throws \OC\HintException
158
+     * @since 14.0.0
159
+     */
160
+    public function shareReceived(ICloudFederationShare $share) {
161
+
162
+        if (!$this->isS2SEnabled(true)) {
163
+            throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
164
+        }
165
+
166
+        $protocol = $share->getProtocol();
167
+        if ($protocol['name'] !== 'webdav') {
168
+            throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
169
+        }
170
+
171
+        list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
172
+        // for backward compatibility make sure that the remote url stored in the
173
+        // database ends with a trailing slash
174
+        if (substr($remote, -1) !== '/') {
175
+            $remote = $remote . '/';
176
+        }
177
+
178
+        $token = $share->getShareSecret();
179
+        $name = $share->getResourceName();
180
+        $owner = $share->getOwnerDisplayName();
181
+        $sharedBy = $share->getSharedByDisplayName();
182
+        $shareWith = $share->getShareWith();
183
+        $remoteId = $share->getProviderId();
184
+        $sharedByFederatedId = $share->getSharedBy();
185
+        $ownerFederatedId = $share->getOwner();
186
+        $shareType = $this->mapShareTypeToNextcloud($share->getShareType());
187
+
188
+        // if no explicit information about the person who created the share was send
189
+        // we assume that the share comes from the owner
190
+        if ($sharedByFederatedId === null) {
191
+            $sharedBy = $owner;
192
+            $sharedByFederatedId = $ownerFederatedId;
193
+        }
194
+
195
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
196
+
197
+            if (!Util::isValidFileName($name)) {
198
+                throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
199
+            }
200
+
201
+            // FIXME this should be a method in the user management instead
202
+            if ($shareType === Share::SHARE_TYPE_USER) {
203
+                $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
204
+                Util::emitHook(
205
+                    '\OCA\Files_Sharing\API\Server2Server',
206
+                    'preLoginNameUsedAsUserName',
207
+                    array('uid' => &$shareWith)
208
+                );
209
+                $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
210
+
211
+                if (!$this->userManager->userExists($shareWith)) {
212
+                    throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
213
+                }
214
+
215
+                \OC_Util::setupFS($shareWith);
216
+            }
217
+
218
+            if ($shareType === Share::SHARE_TYPE_GROUP && !$this->groupManager->groupExists($shareWith)) {
219
+                throw new ProviderCouldNotAddShareException('Group does not exists', '',Http::STATUS_BAD_REQUEST);
220
+            }
221
+
222
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
223
+                \OC::$server->getDatabaseConnection(),
224
+                Filesystem::getMountManager(),
225
+                Filesystem::getLoader(),
226
+                \OC::$server->getHTTPClientService(),
227
+                \OC::$server->getNotificationManager(),
228
+                \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
229
+                \OC::$server->getCloudFederationProviderManager(),
230
+                \OC::$server->getCloudFederationFactory(),
231
+                \OC::$server->getGroupManager(),
232
+                \OC::$server->getUserManager(),
233
+                $shareWith
234
+            );
235
+
236
+            try {
237
+                $externalManager->addShare($remote, $token, '', $name, $owner, $shareType,false, $shareWith, $remoteId);
238
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
239
+
240
+                if ($shareType === Share::SHARE_TYPE_USER) {
241
+                    $event = $this->activityManager->generateEvent();
242
+                    $event->setApp('files_sharing')
243
+                        ->setType('remote_share')
244
+                        ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
245
+                        ->setAffectedUser($shareWith)
246
+                        ->setObject('remote_share', (int)$shareId, $name);
247
+                    \OC::$server->getActivityManager()->publish($event);
248
+                    $this->notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
249
+                } else {
250
+                    $groupMembers = $this->groupManager->get($shareWith)->getUsers();
251
+                    foreach ($groupMembers as $user) {
252
+                        $event = $this->activityManager->generateEvent();
253
+                        $event->setApp('files_sharing')
254
+                            ->setType('remote_share')
255
+                            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
256
+                            ->setAffectedUser($user->getUID())
257
+                            ->setObject('remote_share', (int)$shareId, $name);
258
+                        \OC::$server->getActivityManager()->publish($event);
259
+                        $this->notifyAboutNewShare($user->getUID(), $shareId, $ownerFederatedId, $sharedByFederatedId, $name);
260
+                    }
261
+                }
262
+                return $shareId;
263
+            } catch (\Exception $e) {
264
+                $this->logger->logException($e, [
265
+                    'message' => 'Server can not add remote share.',
266
+                    'level' => ILogger::ERROR,
267
+                    'app' => 'files_sharing'
268
+                ]);
269
+                throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
270
+            }
271
+        }
272
+
273
+        throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
274
+
275
+    }
276
+
277
+    /**
278
+     * notification received from another server
279
+     *
280
+     * @param string $notificationType (e.g. SHARE_ACCEPTED)
281
+     * @param string $providerId id of the share
282
+     * @param array $notification payload of the notification
283
+     * @return array data send back to the sender
284
+     *
285
+     * @throws ActionNotSupportedException
286
+     * @throws AuthenticationFailedException
287
+     * @throws BadRequestException
288
+     * @throws \OC\HintException
289
+     * @since 14.0.0
290
+     */
291
+    public function notificationReceived($notificationType, $providerId, array $notification) {
292
+
293
+        switch ($notificationType) {
294
+            case 'SHARE_ACCEPTED':
295
+                return $this->shareAccepted($providerId, $notification);
296
+            case 'SHARE_DECLINED':
297
+                return $this->shareDeclined($providerId, $notification);
298
+            case 'SHARE_UNSHARED':
299
+                return $this->unshare($providerId, $notification);
300
+            case 'REQUEST_RESHARE':
301
+                return $this->reshareRequested($providerId, $notification);
302
+            case 'RESHARE_UNDO':
303
+                return $this->undoReshare($providerId, $notification);
304
+            case 'RESHARE_CHANGE_PERMISSION':
305
+                return $this->updateResharePermissions($providerId, $notification);
306
+        }
307
+
308
+
309
+        throw new BadRequestException([$notificationType]);
310
+    }
311
+
312
+    /**
313
+     * map OCM share type (strings) to Nextcloud internal share types (integer)
314
+     *
315
+     * @param string $shareType
316
+     * @return int
317
+     */
318
+    private function mapShareTypeToNextcloud($shareType) {
319
+        $result = Share::SHARE_TYPE_USER;
320
+        if ($shareType === 'group') {
321
+            $result = Share::SHARE_TYPE_GROUP;
322
+        }
323
+
324
+        return $result;
325
+    }
326
+
327
+    /**
328
+     * notify user about new federated share
329
+     *
330
+     * @param $shareWith
331
+     * @param $shareId
332
+     * @param $ownerFederatedId
333
+     * @param $sharedByFederatedId
334
+     * @param $name
335
+     */
336
+    private function notifyAboutNewShare($shareWith, $shareId, $ownerFederatedId, $sharedByFederatedId, $name) {
337
+        $notification = $this->notificationManager->createNotification();
338
+        $notification->setApp('files_sharing')
339
+            ->setUser($shareWith)
340
+            ->setDateTime(new \DateTime())
341
+            ->setObject('remote_share', $shareId)
342
+            ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
343
+
344
+        $declineAction = $notification->createAction();
345
+        $declineAction->setLabel('decline')
346
+            ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
347
+        $notification->addAction($declineAction);
348
+
349
+        $acceptAction = $notification->createAction();
350
+        $acceptAction->setLabel('accept')
351
+            ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
352
+        $notification->addAction($acceptAction);
353
+
354
+        $this->notificationManager->notify($notification);
355
+    }
356
+
357
+    /**
358
+     * process notification that the recipient accepted a share
359
+     *
360
+     * @param string $id
361
+     * @param array $notification
362
+     * @return array
363
+     * @throws ActionNotSupportedException
364
+     * @throws AuthenticationFailedException
365
+     * @throws BadRequestException
366
+     * @throws \OC\HintException
367
+     */
368
+    private function shareAccepted($id, array $notification) {
369
+
370
+        if (!$this->isS2SEnabled()) {
371
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
372
+        }
373
+
374
+        if (!isset($notification['sharedSecret'])) {
375
+            throw new BadRequestException(['sharedSecret']);
376
+        }
377
+
378
+        $token = $notification['sharedSecret'];
379
+
380
+        $share = $this->federatedShareProvider->getShareById($id);
381
+
382
+        $this->verifyShare($share, $token);
383
+        $this->executeAcceptShare($share);
384
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
385
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
386
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
387
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
388
+            $notification->setMessage(
389
+                'SHARE_ACCEPTED',
390
+                'file',
391
+                $remoteId,
392
+                [
393
+                    'sharedSecret' => $token,
394
+                    'message' => 'Recipient accepted the re-share'
395
+                ]
396
+
397
+            );
398
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
399
+
400
+        }
401
+
402
+        return [];
403
+    }
404
+
405
+    /**
406
+     * @param IShare $share
407
+     * @throws ShareNotFound
408
+     */
409
+    protected function executeAcceptShare(IShare $share) {
410
+        try {
411
+            $fileId = (int)$share->getNode()->getId();
412
+            list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
413
+        } catch (\Exception $e) {
414
+            throw new ShareNotFound();
415
+        }
416
+
417
+        $event = $this->activityManager->generateEvent();
418
+        $event->setApp('files_sharing')
419
+            ->setType('remote_share')
420
+            ->setAffectedUser($this->getCorrectUid($share))
421
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
422
+            ->setObject('files', $fileId, $file)
423
+            ->setLink($link);
424
+        $this->activityManager->publish($event);
425
+    }
426
+
427
+    /**
428
+     * process notification that the recipient declined a share
429
+     *
430
+     * @param string $id
431
+     * @param array $notification
432
+     * @return array
433
+     * @throws ActionNotSupportedException
434
+     * @throws AuthenticationFailedException
435
+     * @throws BadRequestException
436
+     * @throws ShareNotFound
437
+     * @throws \OC\HintException
438
+     *
439
+     */
440
+    protected function shareDeclined($id, array $notification) {
441
+
442
+        if (!$this->isS2SEnabled()) {
443
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
444
+        }
445
+
446
+        if (!isset($notification['sharedSecret'])) {
447
+            throw new BadRequestException(['sharedSecret']);
448
+        }
449
+
450
+        $token = $notification['sharedSecret'];
451
+
452
+        $share = $this->federatedShareProvider->getShareById($id);
453
+
454
+        $this->verifyShare($share, $token);
455
+
456
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
457
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
458
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
459
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
460
+            $notification->setMessage(
461
+                'SHARE_DECLINED',
462
+                'file',
463
+                $remoteId,
464
+                [
465
+                    'sharedSecret' => $token,
466
+                    'message' => 'Recipient declined the re-share'
467
+                ]
468
+
469
+            );
470
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
471
+        }
472
+
473
+        $this->executeDeclineShare($share);
474
+
475
+        return [];
476
+
477
+    }
478
+
479
+    /**
480
+     * delete declined share and create a activity
481
+     *
482
+     * @param IShare $share
483
+     * @throws ShareNotFound
484
+     */
485
+    protected function executeDeclineShare(IShare $share) {
486
+        $this->federatedShareProvider->removeShareFromTable($share);
487
+
488
+        try {
489
+            $fileId = (int)$share->getNode()->getId();
490
+            list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
491
+        } catch (\Exception $e) {
492
+            throw new ShareNotFound();
493
+        }
494
+
495
+        $event = $this->activityManager->generateEvent();
496
+        $event->setApp('files_sharing')
497
+            ->setType('remote_share')
498
+            ->setAffectedUser($this->getCorrectUid($share))
499
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
500
+            ->setObject('files', $fileId, $file)
501
+            ->setLink($link);
502
+        $this->activityManager->publish($event);
503
+
504
+    }
505
+
506
+    /**
507
+     * received the notification that the owner unshared a file from you
508
+     *
509
+     * @param string $id
510
+     * @param array $notification
511
+     * @return array
512
+     * @throws AuthenticationFailedException
513
+     * @throws BadRequestException
514
+     */
515
+    private function undoReshare($id, array $notification) {
516
+        if (!isset($notification['sharedSecret'])) {
517
+            throw new BadRequestException(['sharedSecret']);
518
+        }
519
+        $token = $notification['sharedSecret'];
520
+
521
+        $share = $this->federatedShareProvider->getShareById($id);
522
+
523
+        $this->verifyShare($share, $token);
524
+        $this->federatedShareProvider->removeShareFromTable($share);
525
+        return [];
526
+    }
527
+
528
+    /**
529
+     * unshare file from self
530
+     *
531
+     * @param string $id
532
+     * @param array $notification
533
+     * @return array
534
+     * @throws ActionNotSupportedException
535
+     * @throws BadRequestException
536
+     */
537
+    private function unshare($id, array $notification) {
538
+
539
+        if (!$this->isS2SEnabled(true)) {
540
+            throw new ActionNotSupportedException("incoming shares disabled!");
541
+        }
542
+
543
+        if (!isset($notification['sharedSecret'])) {
544
+            throw new BadRequestException(['sharedSecret']);
545
+        }
546
+        $token = $notification['sharedSecret'];
547
+
548
+        $qb = $this->connection->getQueryBuilder();
549
+        $qb->select('*')
550
+            ->from('share_external')
551
+            ->where(
552
+                $qb->expr()->andX(
553
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
554
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
555
+                )
556
+            );
557
+
558
+        $result = $qb->execute();
559
+        $share = $result->fetch();
560
+        $result->closeCursor();
561
+
562
+        if ($token && $id && !empty($share)) {
563
+
564
+            $remote = $this->cleanupRemote($share['remote']);
565
+
566
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
567
+            $mountpoint = $share['mountpoint'];
568
+            $user = $share['user'];
569
+
570
+            $qb = $this->connection->getQueryBuilder();
571
+            $qb->delete('share_external')
572
+                ->where(
573
+                    $qb->expr()->andX(
574
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
575
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
576
+                    )
577
+                );
578
+
579
+            $qb->execute();
580
+
581
+            if ($share['accepted']) {
582
+                $path = trim($mountpoint, '/');
583
+            } else {
584
+                $path = trim($share['name'], '/');
585
+            }
586
+
587
+            $notification = $this->notificationManager->createNotification();
588
+            $notification->setApp('files_sharing')
589
+                ->setUser($share['user'])
590
+                ->setObject('remote_share', (int)$share['id']);
591
+            $this->notificationManager->markProcessed($notification);
592
+
593
+            $event = $this->activityManager->generateEvent();
594
+            $event->setApp('files_sharing')
595
+                ->setType('remote_share')
596
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
597
+                ->setAffectedUser($user)
598
+                ->setObject('remote_share', (int)$share['id'], $path);
599
+            \OC::$server->getActivityManager()->publish($event);
600
+        }
601
+
602
+        return [];
603
+    }
604
+
605
+    private function cleanupRemote($remote) {
606
+        $remote = substr($remote, strpos($remote, '://') + 3);
607
+
608
+        return rtrim($remote, '/');
609
+    }
610
+
611
+    /**
612
+     * recipient of a share request to re-share the file with another user
613
+     *
614
+     * @param string $id
615
+     * @param array $notification
616
+     * @return array
617
+     * @throws AuthenticationFailedException
618
+     * @throws BadRequestException
619
+     * @throws ProviderCouldNotAddShareException
620
+     * @throws ShareNotFound
621
+     */
622
+    protected function reshareRequested($id, array $notification) {
623
+
624
+        if (!isset($notification['sharedSecret'])) {
625
+            throw new BadRequestException(['sharedSecret']);
626
+        }
627
+        $token = $notification['sharedSecret'];
628
+
629
+        if (!isset($notification['shareWith'])) {
630
+            throw new BadRequestException(['shareWith']);
631
+        }
632
+        $shareWith = $notification['shareWith'];
633
+
634
+        if (!isset($notification['senderId'])) {
635
+            throw new BadRequestException(['senderId']);
636
+        }
637
+        $senderId = $notification['senderId'];
638
+
639
+        $share = $this->federatedShareProvider->getShareById($id);
640
+        // don't allow to share a file back to the owner
641
+        try {
642
+            list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
643
+            $owner = $share->getShareOwner();
644
+            $currentServer = $this->addressHandler->generateRemoteURL();
645
+            if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
646
+                throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
647
+            }
648
+        } catch (\Exception $e) {
649
+            throw new ProviderCouldNotAddShareException($e->getMessage());
650
+        }
651
+
652
+        $this->verifyShare($share, $token);
653
+
654
+        // check if re-sharing is allowed
655
+        if ($share->getPermissions() & Constants::PERMISSION_SHARE) {
656
+            // the recipient of the initial share is now the initiator for the re-share
657
+            $share->setSharedBy($share->getSharedWith());
658
+            $share->setSharedWith($shareWith);
659
+            $result = $this->federatedShareProvider->create($share);
660
+            $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
661
+            return ['token' => $result->getToken(), 'providerId' => $result->getId()];
662
+        } else {
663
+            throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
664
+        }
665
+
666
+    }
667
+
668
+    /**
669
+     * update permission of a re-share so that the share dialog shows the right
670
+     * permission if the owner or the sender changes the permission
671
+     *
672
+     * @param string $id
673
+     * @param array $notification
674
+     * @return array
675
+     * @throws AuthenticationFailedException
676
+     * @throws BadRequestException
677
+     */
678
+    protected function updateResharePermissions($id, array $notification) {
679
+
680
+        if (!isset($notification['sharedSecret'])) {
681
+            throw new BadRequestException(['sharedSecret']);
682
+        }
683
+        $token = $notification['sharedSecret'];
684
+
685
+        if (!isset($notification['permission'])) {
686
+            throw new BadRequestException(['permission']);
687
+        }
688
+        $ocmPermissions = $notification['permission'];
689
+
690
+        $share = $this->federatedShareProvider->getShareById($id);
691
+
692
+        $ncPermission = $this->ocmPermissions2ncPermissions($ocmPermissions);
693
+
694
+        $this->verifyShare($share, $token);
695
+        $this->updatePermissionsInDatabase($share, $ncPermission);
696
+
697
+        return [];
698
+    }
699
+
700
+    /**
701
+     * translate OCM Permissions to Nextcloud permissions
702
+     *
703
+     * @param array $ocmPermissions
704
+     * @return int
705
+     * @throws BadRequestException
706
+     */
707
+    protected function ocmPermissions2ncPermissions(array $ocmPermissions) {
708
+        $ncPermissions = 0;
709
+        foreach($ocmPermissions as $permission) {
710
+            switch (strtolower($permission)) {
711
+                case 'read':
712
+                    $ncPermissions += Constants::PERMISSION_READ;
713
+                    break;
714
+                case 'write':
715
+                    $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
716
+                    break;
717
+                case 'share':
718
+                    $ncPermissions += Constants::PERMISSION_SHARE;
719
+                    break;
720
+                default:
721
+                    throw new BadRequestException(['permission']);
722
+            }
723
+
724
+        }
725
+
726
+        return $ncPermissions;
727
+    }
728
+
729
+    /**
730
+     * update permissions in database
731
+     *
732
+     * @param IShare $share
733
+     * @param int $permissions
734
+     */
735
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
736
+        $query = $this->connection->getQueryBuilder();
737
+        $query->update('share')
738
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
739
+            ->set('permissions', $query->createNamedParameter($permissions))
740
+            ->execute();
741
+    }
742
+
743
+
744
+    /**
745
+     * get file
746
+     *
747
+     * @param string $user
748
+     * @param int $fileSource
749
+     * @return array with internal path of the file and a absolute link to it
750
+     */
751
+    private function getFile($user, $fileSource) {
752
+        \OC_Util::setupFS($user);
753
+
754
+        try {
755
+            $file = Filesystem::getPath($fileSource);
756
+        } catch (NotFoundException $e) {
757
+            $file = null;
758
+        }
759
+        $args = Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
760
+        $link = Util::linkToAbsolute('files', 'index.php', $args);
761
+
762
+        return [$file, $link];
763
+
764
+    }
765
+
766
+    /**
767
+     * check if we are the initiator or the owner of a re-share and return the correct UID
768
+     *
769
+     * @param IShare $share
770
+     * @return string
771
+     */
772
+    protected function getCorrectUid(IShare $share) {
773
+        if ($this->userManager->userExists($share->getShareOwner())) {
774
+            return $share->getShareOwner();
775
+        }
776
+
777
+        return $share->getSharedBy();
778
+    }
779
+
780
+
781
+
782
+    /**
783
+     * check if we got the right share
784
+     *
785
+     * @param IShare $share
786
+     * @param string $token
787
+     * @return bool
788
+     * @throws AuthenticationFailedException
789
+     */
790
+    protected function verifyShare(IShare $share, $token) {
791
+        if (
792
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
793
+            $share->getToken() === $token
794
+        ) {
795
+            return true;
796
+        }
797
+
798
+        throw new AuthenticationFailedException();
799
+    }
800
+
801
+
802
+
803
+    /**
804
+     * check if server-to-server sharing is enabled
805
+     *
806
+     * @param bool $incoming
807
+     * @return bool
808
+     */
809
+    private function isS2SEnabled($incoming = false) {
810
+
811
+        $result = $this->appManager->isEnabledForUser('files_sharing');
812
+
813
+        if ($incoming) {
814
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
815
+        } else {
816
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
817
+        }
818
+
819
+        return $result;
820
+    }
821
+
822
+
823
+    /**
824
+     * get the supported share types, e.g. "user", "group", etc.
825
+     *
826
+     * @return array
827
+     *
828
+     * @since 14.0.0
829
+     */
830
+    public function getSupportedShareTypes() {
831
+        return ['user', 'group'];
832
+    }
833 833
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/AppInfo/Application.php 1 patch
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -45,138 +45,138 @@
 block discarded – undo
45 45
 use OCA\Files_Sharing\External\Manager;
46 46
 
47 47
 class Application extends App {
48
-	public function __construct(array $urlParams = array()) {
49
-		parent::__construct('files_sharing', $urlParams);
48
+    public function __construct(array $urlParams = array()) {
49
+        parent::__construct('files_sharing', $urlParams);
50 50
 
51
-		$container = $this->getContainer();
52
-		/** @var IServerContainer $server */
53
-		$server = $container->getServer();
51
+        $container = $this->getContainer();
52
+        /** @var IServerContainer $server */
53
+        $server = $container->getServer();
54 54
 
55
-		/**
56
-		 * Controllers
57
-		 */
58
-		$container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
59
-			$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
60
-			return new ShareController(
61
-				$c->query('AppName'),
62
-				$c->query('Request'),
63
-				$server->getConfig(),
64
-				$server->getURLGenerator(),
65
-				$server->getUserManager(),
66
-				$server->getLogger(),
67
-				$server->getActivityManager(),
68
-				$server->getShareManager(),
69
-				$server->getSession(),
70
-				$server->getPreviewManager(),
71
-				$server->getRootFolder(),
72
-				$federatedSharingApp->getFederatedShareProvider(),
73
-				$server->getEventDispatcher(),
74
-				$server->getL10N($c->query('AppName')),
75
-				$server->query(Defaults::class)
76
-			);
77
-		});
78
-		$container->registerService('ExternalSharesController', function (SimpleContainer $c) {
79
-			return new ExternalSharesController(
80
-				$c->query('AppName'),
81
-				$c->query('Request'),
82
-				$c->query('ExternalManager'),
83
-				$c->query('HttpClientService')
84
-			);
85
-		});
55
+        /**
56
+         * Controllers
57
+         */
58
+        $container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
59
+            $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
60
+            return new ShareController(
61
+                $c->query('AppName'),
62
+                $c->query('Request'),
63
+                $server->getConfig(),
64
+                $server->getURLGenerator(),
65
+                $server->getUserManager(),
66
+                $server->getLogger(),
67
+                $server->getActivityManager(),
68
+                $server->getShareManager(),
69
+                $server->getSession(),
70
+                $server->getPreviewManager(),
71
+                $server->getRootFolder(),
72
+                $federatedSharingApp->getFederatedShareProvider(),
73
+                $server->getEventDispatcher(),
74
+                $server->getL10N($c->query('AppName')),
75
+                $server->query(Defaults::class)
76
+            );
77
+        });
78
+        $container->registerService('ExternalSharesController', function (SimpleContainer $c) {
79
+            return new ExternalSharesController(
80
+                $c->query('AppName'),
81
+                $c->query('Request'),
82
+                $c->query('ExternalManager'),
83
+                $c->query('HttpClientService')
84
+            );
85
+        });
86 86
 
87
-		/**
88
-		 * Core class wrappers
89
-		 */
90
-		$container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
91
-			return $server->getHTTPClientService();
92
-		});
93
-		$container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
94
-			return $server->getCloudIdManager();
95
-		});
96
-		$container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
97
-			$user = $server->getUserSession()->getUser();
98
-			$uid = $user ? $user->getUID() : null;
99
-			return new \OCA\Files_Sharing\External\Manager(
100
-				$server->getDatabaseConnection(),
101
-				\OC\Files\Filesystem::getMountManager(),
102
-				\OC\Files\Filesystem::getLoader(),
103
-				$server->getHTTPClientService(),
104
-				$server->getNotificationManager(),
105
-				$server->query(\OCP\OCS\IDiscoveryService::class),
106
-				$server->getCloudFederationProviderManager(),
107
-				$server->getCloudFederationFactory(),
108
-				$server->getGroupManager(),
109
-				$server->getUserManager(),
110
-				$uid
111
-			);
112
-		});
113
-		$container->registerAlias(Manager::class, 'ExternalManager');
87
+        /**
88
+         * Core class wrappers
89
+         */
90
+        $container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
91
+            return $server->getHTTPClientService();
92
+        });
93
+        $container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
94
+            return $server->getCloudIdManager();
95
+        });
96
+        $container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
97
+            $user = $server->getUserSession()->getUser();
98
+            $uid = $user ? $user->getUID() : null;
99
+            return new \OCA\Files_Sharing\External\Manager(
100
+                $server->getDatabaseConnection(),
101
+                \OC\Files\Filesystem::getMountManager(),
102
+                \OC\Files\Filesystem::getLoader(),
103
+                $server->getHTTPClientService(),
104
+                $server->getNotificationManager(),
105
+                $server->query(\OCP\OCS\IDiscoveryService::class),
106
+                $server->getCloudFederationProviderManager(),
107
+                $server->getCloudFederationFactory(),
108
+                $server->getGroupManager(),
109
+                $server->getUserManager(),
110
+                $uid
111
+            );
112
+        });
113
+        $container->registerAlias(Manager::class, 'ExternalManager');
114 114
 
115
-		/**
116
-		 * Middleware
117
-		 */
118
-		$container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
119
-			return new SharingCheckMiddleware(
120
-				$c->query('AppName'),
121
-				$server->getConfig(),
122
-				$server->getAppManager(),
123
-				$c['ControllerMethodReflector'],
124
-				$server->getShareManager(),
125
-				$server->getRequest()
126
-			);
127
-		});
115
+        /**
116
+         * Middleware
117
+         */
118
+        $container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
119
+            return new SharingCheckMiddleware(
120
+                $c->query('AppName'),
121
+                $server->getConfig(),
122
+                $server->getAppManager(),
123
+                $c['ControllerMethodReflector'],
124
+                $server->getShareManager(),
125
+                $server->getRequest()
126
+            );
127
+        });
128 128
 
129
-		$container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
130
-			return new OCSShareAPIMiddleware(
131
-				$server->getShareManager(),
132
-				$server->getL10N($c->query('AppName'))
133
-			);
134
-		});
129
+        $container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
130
+            return new OCSShareAPIMiddleware(
131
+                $server->getShareManager(),
132
+                $server->getL10N($c->query('AppName'))
133
+            );
134
+        });
135 135
 
136
-		$container->registerService(ShareInfoMiddleware::class, function () use ($server) {
137
-			return new ShareInfoMiddleware(
138
-				$server->getShareManager()
139
-			);
140
-		});
136
+        $container->registerService(ShareInfoMiddleware::class, function () use ($server) {
137
+            return new ShareInfoMiddleware(
138
+                $server->getShareManager()
139
+            );
140
+        });
141 141
 
142
-		// Execute middlewares
143
-		$container->registerMiddleWare('SharingCheckMiddleware');
144
-		$container->registerMiddleWare('OCSShareAPIMiddleware');
145
-		$container->registerMiddleWare(ShareInfoMiddleware::class);
142
+        // Execute middlewares
143
+        $container->registerMiddleWare('SharingCheckMiddleware');
144
+        $container->registerMiddleWare('OCSShareAPIMiddleware');
145
+        $container->registerMiddleWare(ShareInfoMiddleware::class);
146 146
 
147
-		$container->registerService('MountProvider', function (IContainer $c) {
148
-			/** @var \OCP\IServerContainer $server */
149
-			$server = $c->query('ServerContainer');
150
-			return new MountProvider(
151
-				$server->getConfig(),
152
-				$server->getShareManager(),
153
-				$server->getLogger()
154
-			);
155
-		});
147
+        $container->registerService('MountProvider', function (IContainer $c) {
148
+            /** @var \OCP\IServerContainer $server */
149
+            $server = $c->query('ServerContainer');
150
+            return new MountProvider(
151
+                $server->getConfig(),
152
+                $server->getShareManager(),
153
+                $server->getLogger()
154
+            );
155
+        });
156 156
 
157
-		$container->registerService('ExternalMountProvider', function (IContainer $c) {
158
-			/** @var \OCP\IServerContainer $server */
159
-			$server = $c->query('ServerContainer');
160
-			return new \OCA\Files_Sharing\External\MountProvider(
161
-				$server->getDatabaseConnection(),
162
-				function() use ($c) {
163
-					return $c->query('ExternalManager');
164
-				},
165
-				$server->getCloudIdManager()
166
-			);
167
-		});
157
+        $container->registerService('ExternalMountProvider', function (IContainer $c) {
158
+            /** @var \OCP\IServerContainer $server */
159
+            $server = $c->query('ServerContainer');
160
+            return new \OCA\Files_Sharing\External\MountProvider(
161
+                $server->getDatabaseConnection(),
162
+                function() use ($c) {
163
+                    return $c->query('ExternalManager');
164
+                },
165
+                $server->getCloudIdManager()
166
+            );
167
+        });
168 168
 
169
-		/*
169
+        /*
170 170
 		 * Register capabilities
171 171
 		 */
172
-		$container->registerCapability(Capabilities::class);
173
-	}
172
+        $container->registerCapability(Capabilities::class);
173
+    }
174 174
 
175
-	public function registerMountProviders() {
176
-		/** @var \OCP\IServerContainer $server */
177
-		$server = $this->getContainer()->query('ServerContainer');
178
-		$mountProviderCollection = $server->getMountProviderCollection();
179
-		$mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
180
-		$mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
181
-	}
175
+    public function registerMountProviders() {
176
+        /** @var \OCP\IServerContainer $server */
177
+        $server = $this->getContainer()->query('ServerContainer');
178
+        $mountProviderCollection = $server->getMountProviderCollection();
179
+        $mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
180
+        $mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
181
+    }
182 182
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -46,594 +46,594 @@
 block discarded – undo
46 46
 use OCP\Share;
47 47
 
48 48
 class Manager {
49
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
50
-
51
-	/**
52
-	 * @var string
53
-	 */
54
-	private $uid;
55
-
56
-	/**
57
-	 * @var IDBConnection
58
-	 */
59
-	private $connection;
60
-
61
-	/**
62
-	 * @var \OC\Files\Mount\Manager
63
-	 */
64
-	private $mountManager;
65
-
66
-	/**
67
-	 * @var IStorageFactory
68
-	 */
69
-	private $storageLoader;
70
-
71
-	/**
72
-	 * @var IClientService
73
-	 */
74
-	private $clientService;
75
-
76
-	/**
77
-	 * @var IManager
78
-	 */
79
-	private $notificationManager;
80
-
81
-	/**
82
-	 * @var IDiscoveryService
83
-	 */
84
-	private $discoveryService;
85
-
86
-	/** @var ICloudFederationProviderManager */
87
-	private $cloudFederationProviderManager;
88
-
89
-	/** @var ICloudFederationFactory */
90
-	private $cloudFederationFactory;
91
-
92
-	/** @var IGroupManager  */
93
-	private $groupManager;
94
-
95
-	/** @var IUserManager */
96
-	private $userManager;
97
-
98
-	/**
99
-	 * @param IDBConnection $connection
100
-	 * @param \OC\Files\Mount\Manager $mountManager
101
-	 * @param IStorageFactory $storageLoader
102
-	 * @param IClientService $clientService
103
-	 * @param IManager $notificationManager
104
-	 * @param IDiscoveryService $discoveryService
105
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
106
-	 * @param ICloudFederationFactory $cloudFederationFactory
107
-	 * @param IGroupManager $groupManager
108
-	 * @param IUserManager $userManager
109
-	 * @param string $uid
110
-	 */
111
-	public function __construct(IDBConnection $connection,
112
-								\OC\Files\Mount\Manager $mountManager,
113
-								IStorageFactory $storageLoader,
114
-								IClientService $clientService,
115
-								IManager $notificationManager,
116
-								IDiscoveryService $discoveryService,
117
-								ICloudFederationProviderManager $cloudFederationProviderManager,
118
-								ICloudFederationFactory $cloudFederationFactory,
119
-								IGroupManager $groupManager,
120
-								IUserManager $userManager,
121
-								$uid) {
122
-		$this->connection = $connection;
123
-		$this->mountManager = $mountManager;
124
-		$this->storageLoader = $storageLoader;
125
-		$this->clientService = $clientService;
126
-		$this->uid = $uid;
127
-		$this->notificationManager = $notificationManager;
128
-		$this->discoveryService = $discoveryService;
129
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
130
-		$this->cloudFederationFactory = $cloudFederationFactory;
131
-		$this->groupManager = $groupManager;
132
-		$this->userManager = $userManager;
133
-	}
134
-
135
-	/**
136
-	 * add new server-to-server share
137
-	 *
138
-	 * @param string $remote
139
-	 * @param string $token
140
-	 * @param string $password
141
-	 * @param string $name
142
-	 * @param string $owner
143
-	 * @param int $shareType
144
-	 * @param boolean $accepted
145
-	 * @param string $user
146
-	 * @param int $remoteId
147
-	 * @param int $parent
148
-	 * @return Mount|null
149
-	 * @throws \Doctrine\DBAL\DBALException
150
-	 */
151
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
152
-
153
-		$user = $user ? $user : $this->uid;
154
-		$accepted = $accepted ? 1 : 0;
155
-		$name = Filesystem::normalizePath('/' . $name);
156
-
157
-		if (!$accepted) {
158
-			// To avoid conflicts with the mount point generation later,
159
-			// we only use a temporary mount point name here. The real
160
-			// mount point name will be generated when accepting the share,
161
-			// using the original share item name.
162
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
163
-			$mountPoint = $tmpMountPointName;
164
-			$hash = md5($tmpMountPointName);
165
-			$data = [
166
-				'remote'		=> $remote,
167
-				'share_token'	=> $token,
168
-				'password'		=> $password,
169
-				'name'			=> $name,
170
-				'owner'			=> $owner,
171
-				'user'			=> $user,
172
-				'mountpoint'	=> $mountPoint,
173
-				'mountpoint_hash'	=> $hash,
174
-				'accepted'		=> $accepted,
175
-				'remote_id'		=> $remoteId,
176
-				'share_type'    => $shareType,
177
-			];
178
-
179
-			$i = 1;
180
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
181
-				// The external share already exists for the user
182
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
183
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
184
-				$i++;
185
-			}
186
-			return null;
187
-		}
188
-
189
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
190
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
191
-		$hash = md5($mountPoint);
192
-
193
-		$this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
194
-
195
-		$options = array(
196
-			'remote'	=> $remote,
197
-			'token'		=> $token,
198
-			'password'	=> $password,
199
-			'mountpoint'	=> $mountPoint,
200
-			'owner'		=> $owner
201
-		);
202
-		return $this->mountShare($options);
203
-	}
204
-
205
-	/**
206
-	 * write remote share to the database
207
-	 *
208
-	 * @param $remote
209
-	 * @param $token
210
-	 * @param $password
211
-	 * @param $name
212
-	 * @param $owner
213
-	 * @param $user
214
-	 * @param $mountPoint
215
-	 * @param $hash
216
-	 * @param $accepted
217
-	 * @param $remoteId
218
-	 * @param $parent
219
-	 * @param $shareType
220
-	 */
221
-	private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType) {
222
-		$query = $this->connection->prepare('
49
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
50
+
51
+    /**
52
+     * @var string
53
+     */
54
+    private $uid;
55
+
56
+    /**
57
+     * @var IDBConnection
58
+     */
59
+    private $connection;
60
+
61
+    /**
62
+     * @var \OC\Files\Mount\Manager
63
+     */
64
+    private $mountManager;
65
+
66
+    /**
67
+     * @var IStorageFactory
68
+     */
69
+    private $storageLoader;
70
+
71
+    /**
72
+     * @var IClientService
73
+     */
74
+    private $clientService;
75
+
76
+    /**
77
+     * @var IManager
78
+     */
79
+    private $notificationManager;
80
+
81
+    /**
82
+     * @var IDiscoveryService
83
+     */
84
+    private $discoveryService;
85
+
86
+    /** @var ICloudFederationProviderManager */
87
+    private $cloudFederationProviderManager;
88
+
89
+    /** @var ICloudFederationFactory */
90
+    private $cloudFederationFactory;
91
+
92
+    /** @var IGroupManager  */
93
+    private $groupManager;
94
+
95
+    /** @var IUserManager */
96
+    private $userManager;
97
+
98
+    /**
99
+     * @param IDBConnection $connection
100
+     * @param \OC\Files\Mount\Manager $mountManager
101
+     * @param IStorageFactory $storageLoader
102
+     * @param IClientService $clientService
103
+     * @param IManager $notificationManager
104
+     * @param IDiscoveryService $discoveryService
105
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
106
+     * @param ICloudFederationFactory $cloudFederationFactory
107
+     * @param IGroupManager $groupManager
108
+     * @param IUserManager $userManager
109
+     * @param string $uid
110
+     */
111
+    public function __construct(IDBConnection $connection,
112
+                                \OC\Files\Mount\Manager $mountManager,
113
+                                IStorageFactory $storageLoader,
114
+                                IClientService $clientService,
115
+                                IManager $notificationManager,
116
+                                IDiscoveryService $discoveryService,
117
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
118
+                                ICloudFederationFactory $cloudFederationFactory,
119
+                                IGroupManager $groupManager,
120
+                                IUserManager $userManager,
121
+                                $uid) {
122
+        $this->connection = $connection;
123
+        $this->mountManager = $mountManager;
124
+        $this->storageLoader = $storageLoader;
125
+        $this->clientService = $clientService;
126
+        $this->uid = $uid;
127
+        $this->notificationManager = $notificationManager;
128
+        $this->discoveryService = $discoveryService;
129
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
130
+        $this->cloudFederationFactory = $cloudFederationFactory;
131
+        $this->groupManager = $groupManager;
132
+        $this->userManager = $userManager;
133
+    }
134
+
135
+    /**
136
+     * add new server-to-server share
137
+     *
138
+     * @param string $remote
139
+     * @param string $token
140
+     * @param string $password
141
+     * @param string $name
142
+     * @param string $owner
143
+     * @param int $shareType
144
+     * @param boolean $accepted
145
+     * @param string $user
146
+     * @param int $remoteId
147
+     * @param int $parent
148
+     * @return Mount|null
149
+     * @throws \Doctrine\DBAL\DBALException
150
+     */
151
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
152
+
153
+        $user = $user ? $user : $this->uid;
154
+        $accepted = $accepted ? 1 : 0;
155
+        $name = Filesystem::normalizePath('/' . $name);
156
+
157
+        if (!$accepted) {
158
+            // To avoid conflicts with the mount point generation later,
159
+            // we only use a temporary mount point name here. The real
160
+            // mount point name will be generated when accepting the share,
161
+            // using the original share item name.
162
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
163
+            $mountPoint = $tmpMountPointName;
164
+            $hash = md5($tmpMountPointName);
165
+            $data = [
166
+                'remote'		=> $remote,
167
+                'share_token'	=> $token,
168
+                'password'		=> $password,
169
+                'name'			=> $name,
170
+                'owner'			=> $owner,
171
+                'user'			=> $user,
172
+                'mountpoint'	=> $mountPoint,
173
+                'mountpoint_hash'	=> $hash,
174
+                'accepted'		=> $accepted,
175
+                'remote_id'		=> $remoteId,
176
+                'share_type'    => $shareType,
177
+            ];
178
+
179
+            $i = 1;
180
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
181
+                // The external share already exists for the user
182
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
183
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
184
+                $i++;
185
+            }
186
+            return null;
187
+        }
188
+
189
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
190
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
191
+        $hash = md5($mountPoint);
192
+
193
+        $this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
194
+
195
+        $options = array(
196
+            'remote'	=> $remote,
197
+            'token'		=> $token,
198
+            'password'	=> $password,
199
+            'mountpoint'	=> $mountPoint,
200
+            'owner'		=> $owner
201
+        );
202
+        return $this->mountShare($options);
203
+    }
204
+
205
+    /**
206
+     * write remote share to the database
207
+     *
208
+     * @param $remote
209
+     * @param $token
210
+     * @param $password
211
+     * @param $name
212
+     * @param $owner
213
+     * @param $user
214
+     * @param $mountPoint
215
+     * @param $hash
216
+     * @param $accepted
217
+     * @param $remoteId
218
+     * @param $parent
219
+     * @param $shareType
220
+     */
221
+    private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType) {
222
+        $query = $this->connection->prepare('
223 223
 				INSERT INTO `*PREFIX*share_external`
224 224
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
225 225
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
226 226
 			');
227
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
228
-	}
229
-
230
-	/**
231
-	 * get share
232
-	 *
233
-	 * @param int $id share id
234
-	 * @return mixed share of false
235
-	 */
236
-	public function getShare($id) {
237
-		$getShare = $this->connection->prepare('
227
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
228
+    }
229
+
230
+    /**
231
+     * get share
232
+     *
233
+     * @param int $id share id
234
+     * @return mixed share of false
235
+     */
236
+    public function getShare($id) {
237
+        $getShare = $this->connection->prepare('
238 238
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
239 239
 			FROM  `*PREFIX*share_external`
240 240
 			WHERE `id` = ?');
241
-		$result = $getShare->execute(array($id));
242
-
243
-		$share = $result ? $getShare->fetch() : [];
244
-
245
-		$validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
246
-
247
-		// check if the user is allowed to access it
248
-		if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_USER && $share['user'] === $this->uid) {
249
-			return $share;
250
-		} else if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
251
-			$user = $this->userManager->get($this->uid);
252
-			if ($this->groupManager->get($share['user'])->inGroup($user)) {
253
-				return $share;
254
-			}
255
-		}
256
-
257
-		return false;
258
-
259
-	}
260
-
261
-	/**
262
-	 * accept server-to-server share
263
-	 *
264
-	 * @param int $id
265
-	 * @return bool True if the share could be accepted, false otherwise
266
-	 */
267
-	public function acceptShare($id) {
268
-
269
-		$share = $this->getShare($id);
270
-		$result = false;
271
-
272
-		if ($share) {
273
-			\OC_Util::setupFS($this->uid);
274
-			$shareFolder = Helper::getShareFolder();
275
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
276
-			$mountPoint = Filesystem::normalizePath($mountPoint);
277
-			$hash = md5($mountPoint);
278
-
279
-			if($share['share_type'] === Share::SHARE_TYPE_USER) {
280
-				$acceptShare = $this->connection->prepare('
241
+        $result = $getShare->execute(array($id));
242
+
243
+        $share = $result ? $getShare->fetch() : [];
244
+
245
+        $validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
246
+
247
+        // check if the user is allowed to access it
248
+        if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_USER && $share['user'] === $this->uid) {
249
+            return $share;
250
+        } else if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
251
+            $user = $this->userManager->get($this->uid);
252
+            if ($this->groupManager->get($share['user'])->inGroup($user)) {
253
+                return $share;
254
+            }
255
+        }
256
+
257
+        return false;
258
+
259
+    }
260
+
261
+    /**
262
+     * accept server-to-server share
263
+     *
264
+     * @param int $id
265
+     * @return bool True if the share could be accepted, false otherwise
266
+     */
267
+    public function acceptShare($id) {
268
+
269
+        $share = $this->getShare($id);
270
+        $result = false;
271
+
272
+        if ($share) {
273
+            \OC_Util::setupFS($this->uid);
274
+            $shareFolder = Helper::getShareFolder();
275
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
276
+            $mountPoint = Filesystem::normalizePath($mountPoint);
277
+            $hash = md5($mountPoint);
278
+
279
+            if($share['share_type'] === Share::SHARE_TYPE_USER) {
280
+                $acceptShare = $this->connection->prepare('
281 281
 				UPDATE `*PREFIX*share_external`
282 282
 				SET `accepted` = ?,
283 283
 					`mountpoint` = ?,
284 284
 					`mountpoint_hash` = ?
285 285
 				WHERE `id` = ? AND `user` = ?');
286
-				$updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
287
-			} else {
288
-				$this->writeShareToDb(
289
-					$share['remote'],
290
-					$share['share_token'],
291
-					$share['password'],
292
-					$share['name'],
293
-					$share['owner'],
294
-					$this->uid,
295
-					$mountPoint, $hash, 1,
296
-					$share['remote_id'],
297
-					$id,
298
-					$share['share_type']);
299
-				// TODO group share, add additional row for the user who accepted it
300
-			}
301
-			if ($updated === true) {
302
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
303
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
304
-				$result = true;
305
-			}
306
-		}
307
-
308
-		// Make sure the user has no notification for something that does not exist anymore.
309
-		$this->processNotification($id);
310
-
311
-		return $result;
312
-	}
313
-
314
-	/**
315
-	 * decline server-to-server share
316
-	 *
317
-	 * @param int $id
318
-	 * @return bool True if the share could be declined, false otherwise
319
-	 */
320
-	public function declineShare($id) {
321
-
322
-		$share = $this->getShare($id);
323
-
324
-		if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
325
-			$removeShare = $this->connection->prepare('
286
+                $updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
287
+            } else {
288
+                $this->writeShareToDb(
289
+                    $share['remote'],
290
+                    $share['share_token'],
291
+                    $share['password'],
292
+                    $share['name'],
293
+                    $share['owner'],
294
+                    $this->uid,
295
+                    $mountPoint, $hash, 1,
296
+                    $share['remote_id'],
297
+                    $id,
298
+                    $share['share_type']);
299
+                // TODO group share, add additional row for the user who accepted it
300
+            }
301
+            if ($updated === true) {
302
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
303
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
304
+                $result = true;
305
+            }
306
+        }
307
+
308
+        // Make sure the user has no notification for something that does not exist anymore.
309
+        $this->processNotification($id);
310
+
311
+        return $result;
312
+    }
313
+
314
+    /**
315
+     * decline server-to-server share
316
+     *
317
+     * @param int $id
318
+     * @return bool True if the share could be declined, false otherwise
319
+     */
320
+    public function declineShare($id) {
321
+
322
+        $share = $this->getShare($id);
323
+
324
+        if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
325
+            $removeShare = $this->connection->prepare('
326 326
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
327
-			$removeShare->execute(array($id, $this->uid));
328
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
329
-
330
-			$this->processNotification($id);
331
-			return true;
332
-		} else if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
333
-			$this->writeShareToDb(
334
-				$share['remote'],
335
-				$share['share_token'],
336
-				$share['password'],
337
-				$share['name'],
338
-				$share['owner'],
339
-				$this->uid,
340
-				$share['mountpoint'],
341
-				$share['mountpoint_hash'],
342
-				0,
343
-				$share['remote_id'],
344
-				$id,
345
-				$share['share_type']);
346
-			$this->processNotification($id);
347
-			return true;
348
-		}
349
-
350
-		return false;
351
-	}
352
-
353
-	/**
354
-	 * @param int $remoteShare
355
-	 */
356
-	public function processNotification($remoteShare) {
357
-		$filter = $this->notificationManager->createNotification();
358
-		$filter->setApp('files_sharing')
359
-			->setUser($this->uid)
360
-			->setObject('remote_share', (int) $remoteShare);
361
-		$this->notificationManager->markProcessed($filter);
362
-	}
363
-
364
-	/**
365
-	 * inform remote server whether server-to-server share was accepted/declined
366
-	 *
367
-	 * @param string $remote
368
-	 * @param string $token
369
-	 * @param int $remoteId Share id on the remote host
370
-	 * @param string $feedback
371
-	 * @return boolean
372
-	 */
373
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
374
-
375
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
376
-
377
-		if($result === true) {
378
-			return true;
379
-		}
380
-
381
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
382
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
383
-
384
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
385
-		$fields = array('token' => $token);
386
-
387
-		$client = $this->clientService->newClient();
388
-
389
-		try {
390
-			$response = $client->post(
391
-				$url,
392
-				[
393
-					'body' => $fields,
394
-					'connect_timeout' => 10,
395
-				]
396
-			);
397
-		} catch (\Exception $e) {
398
-			return false;
399
-		}
400
-
401
-		$status = json_decode($response->getBody(), true);
402
-
403
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
404
-	}
405
-
406
-	/**
407
-	 * try send accept message to ocm end-point
408
-	 *
409
-	 * @param string $remoteDomain
410
-	 * @param string $token
411
-	 * @param $remoteId id of the share
412
-	 * @param string $feedback
413
-	 * @return bool
414
-	 */
415
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
416
-		switch ($feedback) {
417
-			case 'accept':
418
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
419
-				$notification->setMessage(
420
-					'SHARE_ACCEPTED',
421
-					'file',
422
-					$remoteId,
423
-					[
424
-						'sharedSecret' => $token,
425
-						'message' => 'Recipient accept the share'
426
-					]
427
-
428
-				);
429
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
430
-			case 'decline':
431
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
432
-				$notification->setMessage(
433
-					'SHARE_DECLINED',
434
-					'file',
435
-					$remoteId,
436
-					[
437
-						'sharedSecret' => $token,
438
-						'message' => 'Recipient declined the share'
439
-					]
440
-
441
-				);
442
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
443
-		}
444
-
445
-		return false;
446
-
447
-	}
448
-
449
-
450
-	/**
451
-	 * remove '/user/files' from the path and trailing slashes
452
-	 *
453
-	 * @param string $path
454
-	 * @return string
455
-	 */
456
-	protected function stripPath($path) {
457
-		$prefix = '/' . $this->uid . '/files';
458
-		return rtrim(substr($path, strlen($prefix)), '/');
459
-	}
460
-
461
-	public function getMount($data) {
462
-		$data['manager'] = $this;
463
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
464
-		$data['mountpoint'] = $mountPoint;
465
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
466
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
467
-	}
468
-
469
-	/**
470
-	 * @param array $data
471
-	 * @return Mount
472
-	 */
473
-	protected function mountShare($data) {
474
-		$mount = $this->getMount($data);
475
-		$this->mountManager->addMount($mount);
476
-		return $mount;
477
-	}
478
-
479
-	/**
480
-	 * @return \OC\Files\Mount\Manager
481
-	 */
482
-	public function getMountManager() {
483
-		return $this->mountManager;
484
-	}
485
-
486
-	/**
487
-	 * @param string $source
488
-	 * @param string $target
489
-	 * @return bool
490
-	 */
491
-	public function setMountPoint($source, $target) {
492
-		$source = $this->stripPath($source);
493
-		$target = $this->stripPath($target);
494
-		$sourceHash = md5($source);
495
-		$targetHash = md5($target);
496
-
497
-		$query = $this->connection->prepare('
327
+            $removeShare->execute(array($id, $this->uid));
328
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
329
+
330
+            $this->processNotification($id);
331
+            return true;
332
+        } else if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
333
+            $this->writeShareToDb(
334
+                $share['remote'],
335
+                $share['share_token'],
336
+                $share['password'],
337
+                $share['name'],
338
+                $share['owner'],
339
+                $this->uid,
340
+                $share['mountpoint'],
341
+                $share['mountpoint_hash'],
342
+                0,
343
+                $share['remote_id'],
344
+                $id,
345
+                $share['share_type']);
346
+            $this->processNotification($id);
347
+            return true;
348
+        }
349
+
350
+        return false;
351
+    }
352
+
353
+    /**
354
+     * @param int $remoteShare
355
+     */
356
+    public function processNotification($remoteShare) {
357
+        $filter = $this->notificationManager->createNotification();
358
+        $filter->setApp('files_sharing')
359
+            ->setUser($this->uid)
360
+            ->setObject('remote_share', (int) $remoteShare);
361
+        $this->notificationManager->markProcessed($filter);
362
+    }
363
+
364
+    /**
365
+     * inform remote server whether server-to-server share was accepted/declined
366
+     *
367
+     * @param string $remote
368
+     * @param string $token
369
+     * @param int $remoteId Share id on the remote host
370
+     * @param string $feedback
371
+     * @return boolean
372
+     */
373
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
374
+
375
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
376
+
377
+        if($result === true) {
378
+            return true;
379
+        }
380
+
381
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
382
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
383
+
384
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
385
+        $fields = array('token' => $token);
386
+
387
+        $client = $this->clientService->newClient();
388
+
389
+        try {
390
+            $response = $client->post(
391
+                $url,
392
+                [
393
+                    'body' => $fields,
394
+                    'connect_timeout' => 10,
395
+                ]
396
+            );
397
+        } catch (\Exception $e) {
398
+            return false;
399
+        }
400
+
401
+        $status = json_decode($response->getBody(), true);
402
+
403
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
404
+    }
405
+
406
+    /**
407
+     * try send accept message to ocm end-point
408
+     *
409
+     * @param string $remoteDomain
410
+     * @param string $token
411
+     * @param $remoteId id of the share
412
+     * @param string $feedback
413
+     * @return bool
414
+     */
415
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
416
+        switch ($feedback) {
417
+            case 'accept':
418
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
419
+                $notification->setMessage(
420
+                    'SHARE_ACCEPTED',
421
+                    'file',
422
+                    $remoteId,
423
+                    [
424
+                        'sharedSecret' => $token,
425
+                        'message' => 'Recipient accept the share'
426
+                    ]
427
+
428
+                );
429
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
430
+            case 'decline':
431
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
432
+                $notification->setMessage(
433
+                    'SHARE_DECLINED',
434
+                    'file',
435
+                    $remoteId,
436
+                    [
437
+                        'sharedSecret' => $token,
438
+                        'message' => 'Recipient declined the share'
439
+                    ]
440
+
441
+                );
442
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
443
+        }
444
+
445
+        return false;
446
+
447
+    }
448
+
449
+
450
+    /**
451
+     * remove '/user/files' from the path and trailing slashes
452
+     *
453
+     * @param string $path
454
+     * @return string
455
+     */
456
+    protected function stripPath($path) {
457
+        $prefix = '/' . $this->uid . '/files';
458
+        return rtrim(substr($path, strlen($prefix)), '/');
459
+    }
460
+
461
+    public function getMount($data) {
462
+        $data['manager'] = $this;
463
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
464
+        $data['mountpoint'] = $mountPoint;
465
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
466
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
467
+    }
468
+
469
+    /**
470
+     * @param array $data
471
+     * @return Mount
472
+     */
473
+    protected function mountShare($data) {
474
+        $mount = $this->getMount($data);
475
+        $this->mountManager->addMount($mount);
476
+        return $mount;
477
+    }
478
+
479
+    /**
480
+     * @return \OC\Files\Mount\Manager
481
+     */
482
+    public function getMountManager() {
483
+        return $this->mountManager;
484
+    }
485
+
486
+    /**
487
+     * @param string $source
488
+     * @param string $target
489
+     * @return bool
490
+     */
491
+    public function setMountPoint($source, $target) {
492
+        $source = $this->stripPath($source);
493
+        $target = $this->stripPath($target);
494
+        $sourceHash = md5($source);
495
+        $targetHash = md5($target);
496
+
497
+        $query = $this->connection->prepare('
498 498
 			UPDATE `*PREFIX*share_external`
499 499
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
500 500
 			WHERE `mountpoint_hash` = ?
501 501
 			AND `user` = ?
502 502
 		');
503
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
503
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
504 504
 
505
-		return $result;
506
-	}
505
+        return $result;
506
+    }
507 507
 
508
-	public function removeShare($mountPoint) {
508
+    public function removeShare($mountPoint) {
509 509
 
510
-		$mountPointObj = $this->mountManager->find($mountPoint);
511
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
510
+        $mountPointObj = $this->mountManager->find($mountPoint);
511
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
512 512
 
513
-		$mountPoint = $this->stripPath($mountPoint);
514
-		$hash = md5($mountPoint);
513
+        $mountPoint = $this->stripPath($mountPoint);
514
+        $hash = md5($mountPoint);
515 515
 
516
-		$getShare = $this->connection->prepare('
516
+        $getShare = $this->connection->prepare('
517 517
 			SELECT `remote`, `share_token`, `remote_id`
518 518
 			FROM  `*PREFIX*share_external`
519 519
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
520
-		$result = $getShare->execute(array($hash, $this->uid));
521
-
522
-		if ($result) {
523
-			try {
524
-				$share = $getShare->fetch();
525
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
526
-			} catch (\Exception $e) {
527
-				// if we fail to notify the remote (probably cause the remote is down)
528
-				// we still want the share to be gone to prevent undeletable remotes
529
-			}
530
-		}
531
-		$getShare->closeCursor();
532
-
533
-		$query = $this->connection->prepare('
520
+        $result = $getShare->execute(array($hash, $this->uid));
521
+
522
+        if ($result) {
523
+            try {
524
+                $share = $getShare->fetch();
525
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
526
+            } catch (\Exception $e) {
527
+                // if we fail to notify the remote (probably cause the remote is down)
528
+                // we still want the share to be gone to prevent undeletable remotes
529
+            }
530
+        }
531
+        $getShare->closeCursor();
532
+
533
+        $query = $this->connection->prepare('
534 534
 			DELETE FROM `*PREFIX*share_external`
535 535
 			WHERE `mountpoint_hash` = ?
536 536
 			AND `user` = ?
537 537
 		');
538
-		$result = (bool)$query->execute(array($hash, $this->uid));
539
-
540
-		if($result) {
541
-			$this->removeReShares($id);
542
-		}
543
-
544
-		return $result;
545
-	}
546
-
547
-	/**
548
-	 * remove re-shares from share table and mapping in the federated_reshares table
549
-	 *
550
-	 * @param $mountPointId
551
-	 */
552
-	protected function removeReShares($mountPointId) {
553
-		$selectQuery = $this->connection->getQueryBuilder();
554
-		$query = $this->connection->getQueryBuilder();
555
-		$selectQuery->select('id')->from('share')
556
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
557
-		$select = $selectQuery->getSQL();
558
-
559
-
560
-		$query->delete('federated_reshares')
561
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
562
-		$query->execute();
563
-
564
-		$deleteReShares = $this->connection->getQueryBuilder();
565
-		$deleteReShares->delete('share')
566
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
567
-		$deleteReShares->execute();
568
-	}
569
-
570
-	/**
571
-	 * remove all shares for user $uid if the user was deleted
572
-	 *
573
-	 * @param string $uid
574
-	 * @return bool
575
-	 */
576
-	public function removeUserShares($uid) {
577
-		$getShare = $this->connection->prepare('
538
+        $result = (bool)$query->execute(array($hash, $this->uid));
539
+
540
+        if($result) {
541
+            $this->removeReShares($id);
542
+        }
543
+
544
+        return $result;
545
+    }
546
+
547
+    /**
548
+     * remove re-shares from share table and mapping in the federated_reshares table
549
+     *
550
+     * @param $mountPointId
551
+     */
552
+    protected function removeReShares($mountPointId) {
553
+        $selectQuery = $this->connection->getQueryBuilder();
554
+        $query = $this->connection->getQueryBuilder();
555
+        $selectQuery->select('id')->from('share')
556
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
557
+        $select = $selectQuery->getSQL();
558
+
559
+
560
+        $query->delete('federated_reshares')
561
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
562
+        $query->execute();
563
+
564
+        $deleteReShares = $this->connection->getQueryBuilder();
565
+        $deleteReShares->delete('share')
566
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
567
+        $deleteReShares->execute();
568
+    }
569
+
570
+    /**
571
+     * remove all shares for user $uid if the user was deleted
572
+     *
573
+     * @param string $uid
574
+     * @return bool
575
+     */
576
+    public function removeUserShares($uid) {
577
+        $getShare = $this->connection->prepare('
578 578
 			SELECT `remote`, `share_token`, `remote_id`
579 579
 			FROM  `*PREFIX*share_external`
580 580
 			WHERE `user` = ?');
581
-		$result = $getShare->execute(array($uid));
581
+        $result = $getShare->execute(array($uid));
582 582
 
583
-		if ($result) {
584
-			$shares = $getShare->fetchAll();
585
-			foreach($shares as $share) {
586
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
587
-			}
588
-		}
583
+        if ($result) {
584
+            $shares = $getShare->fetchAll();
585
+            foreach($shares as $share) {
586
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
587
+            }
588
+        }
589 589
 
590
-		$query = $this->connection->prepare('
590
+        $query = $this->connection->prepare('
591 591
 			DELETE FROM `*PREFIX*share_external`
592 592
 			WHERE `user` = ?
593 593
 		');
594
-		return (bool)$query->execute(array($uid));
595
-	}
596
-
597
-	/**
598
-	 * return a list of shares which are not yet accepted by the user
599
-	 *
600
-	 * @return array list of open server-to-server shares
601
-	 */
602
-	public function getOpenShares() {
603
-		return $this->getShares(false);
604
-	}
605
-
606
-	/**
607
-	 * return a list of shares which are accepted by the user
608
-	 *
609
-	 * @return array list of accepted server-to-server shares
610
-	 */
611
-	public function getAcceptedShares() {
612
-		return $this->getShares(true);
613
-	}
614
-
615
-	/**
616
-	 * return a list of shares for the user
617
-	 *
618
-	 * @param bool|null $accepted True for accepted only,
619
-	 *                            false for not accepted,
620
-	 *                            null for all shares of the user
621
-	 * @return array list of open server-to-server shares
622
-	 */
623
-	private function getShares($accepted) {
624
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
594
+        return (bool)$query->execute(array($uid));
595
+    }
596
+
597
+    /**
598
+     * return a list of shares which are not yet accepted by the user
599
+     *
600
+     * @return array list of open server-to-server shares
601
+     */
602
+    public function getOpenShares() {
603
+        return $this->getShares(false);
604
+    }
605
+
606
+    /**
607
+     * return a list of shares which are accepted by the user
608
+     *
609
+     * @return array list of accepted server-to-server shares
610
+     */
611
+    public function getAcceptedShares() {
612
+        return $this->getShares(true);
613
+    }
614
+
615
+    /**
616
+     * return a list of shares for the user
617
+     *
618
+     * @param bool|null $accepted True for accepted only,
619
+     *                            false for not accepted,
620
+     *                            null for all shares of the user
621
+     * @return array list of open server-to-server shares
622
+     */
623
+    private function getShares($accepted) {
624
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
625 625
 		          FROM `*PREFIX*share_external` 
626 626
 				  WHERE `user` = ?';
627
-		$parameters = [$this->uid];
628
-		if (!is_null($accepted)) {
629
-			$query .= ' AND `accepted` = ?';
630
-			$parameters[] = (int) $accepted;
631
-		}
632
-		$query .= ' ORDER BY `id` ASC';
633
-
634
-		$shares = $this->connection->prepare($query);
635
-		$result = $shares->execute($parameters);
636
-
637
-		return $result ? $shares->fetchAll() : [];
638
-	}
627
+        $parameters = [$this->uid];
628
+        if (!is_null($accepted)) {
629
+            $query .= ' AND `accepted` = ?';
630
+            $parameters[] = (int) $accepted;
631
+        }
632
+        $query .= ' ORDER BY `id` ASC';
633
+
634
+        $shares = $this->connection->prepare($query);
635
+        $result = $shares->execute($parameters);
636
+
637
+        return $result ? $shares->fetchAll() : [];
638
+    }
639 639
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Hooks.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -32,35 +32,35 @@
 block discarded – undo
32 32
 
33 33
 class Hooks {
34 34
 
35
-	public static function deleteUser($params) {
36
-		$manager = new External\Manager(
37
-			\OC::$server->getDatabaseConnection(),
38
-			\OC\Files\Filesystem::getMountManager(),
39
-			\OC\Files\Filesystem::getLoader(),
40
-			\OC::$server->getHTTPClientService(),
41
-			\OC::$server->getNotificationManager(),
42
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
43
-			\OC::$server->getCloudFederationProviderManager(),
44
-			\OC::$server->getCloudFederationFactory(),
45
-			\OC::$server->getGroupManager(),
46
-			\OC::$server->getUserManager(),
47
-			$params['uid']);
35
+    public static function deleteUser($params) {
36
+        $manager = new External\Manager(
37
+            \OC::$server->getDatabaseConnection(),
38
+            \OC\Files\Filesystem::getMountManager(),
39
+            \OC\Files\Filesystem::getLoader(),
40
+            \OC::$server->getHTTPClientService(),
41
+            \OC::$server->getNotificationManager(),
42
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
43
+            \OC::$server->getCloudFederationProviderManager(),
44
+            \OC::$server->getCloudFederationFactory(),
45
+            \OC::$server->getGroupManager(),
46
+            \OC::$server->getUserManager(),
47
+            $params['uid']);
48 48
 
49
-		$manager->removeUserShares($params['uid']);
50
-	}
49
+        $manager->removeUserShares($params['uid']);
50
+    }
51 51
 
52
-	public static function unshareChildren($params) {
53
-		$path = Filesystem::getView()->getAbsolutePath($params['path']);
54
-		$view = new \OC\Files\View('/');
52
+    public static function unshareChildren($params) {
53
+        $path = Filesystem::getView()->getAbsolutePath($params['path']);
54
+        $view = new \OC\Files\View('/');
55 55
 
56
-		// find share mount points within $path and unmount them
57
-		$mountManager = \OC\Files\Filesystem::getMountManager();
58
-		$mountedShares = $mountManager->findIn($path);
59
-		foreach ($mountedShares as $mount) {
60
-			if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
61
-				$mountPoint = $mount->getMountPoint();
62
-				$view->unlink($mountPoint);
63
-			}
64
-		}
65
-	}
56
+        // find share mount points within $path and unmount them
57
+        $mountManager = \OC\Files\Filesystem::getMountManager();
58
+        $mountedShares = $mountManager->findIn($path);
59
+        foreach ($mountedShares as $mount) {
60
+            if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
61
+                $mountPoint = $mount->getMountPoint();
62
+                $view->unlink($mountPoint);
63
+            }
64
+        }
65
+    }
66 66
 }
Please login to merge, or discard this patch.