Completed
Push — master ( c70de1...74fccf )
by Björn
18:31
created
lib/private/GlobalScale/Config.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -27,45 +27,45 @@
 block discarded – undo
27 27
 
28 28
 class Config implements \OCP\GlobalScale\IConfig {
29 29
 
30
-	/** @var IConfig */
31
-	private $config;
30
+    /** @var IConfig */
31
+    private $config;
32 32
 
33
-	/**
34
-	 * Config constructor.
35
-	 *
36
-	 * @param IConfig $config
37
-	 */
38
-	public function __construct(IConfig $config) {
39
-		$this->config = $config;
40
-	}
33
+    /**
34
+     * Config constructor.
35
+     *
36
+     * @param IConfig $config
37
+     */
38
+    public function __construct(IConfig $config) {
39
+        $this->config = $config;
40
+    }
41 41
 
42
-	/**
43
-	 * check if global scale is enabled
44
-	 *
45
-	 * @since 12.0.1
46
-	 * @return bool
47
-	 */
48
-	public function isGlobalScaleEnabled() {
49
-		$enabled = $this->config->getSystemValue('gs.enabled', false);
50
-		return $enabled !== false;
51
-	}
42
+    /**
43
+     * check if global scale is enabled
44
+     *
45
+     * @since 12.0.1
46
+     * @return bool
47
+     */
48
+    public function isGlobalScaleEnabled() {
49
+        $enabled = $this->config->getSystemValue('gs.enabled', false);
50
+        return $enabled !== false;
51
+    }
52 52
 
53
-	/**
54
-	 * check if federation should only be used internally in a global scale setup
55
-	 *
56
-	 * @since 12.0.1
57
-	 * @return bool
58
-	 */
59
-	public function onlyInternalFederation() {
60
-		// if global scale is disabled federation works always globally
61
-		$gsEnabled = $this->isGlobalScaleEnabled();
62
-		if ($gsEnabled === false) {
63
-			return false;
64
-		}
53
+    /**
54
+     * check if federation should only be used internally in a global scale setup
55
+     *
56
+     * @since 12.0.1
57
+     * @return bool
58
+     */
59
+    public function onlyInternalFederation() {
60
+        // if global scale is disabled federation works always globally
61
+        $gsEnabled = $this->isGlobalScaleEnabled();
62
+        if ($gsEnabled === false) {
63
+            return false;
64
+        }
65 65
 
66
-		$enabled = $this->config->getSystemValue('gs.federation', 'internal');
66
+        $enabled = $this->config->getSystemValue('gs.federation', 'internal');
67 67
 
68
-		return $enabled === 'internal';
69
-	}
68
+        return $enabled === 'internal';
69
+    }
70 70
 
71 71
 }
Please login to merge, or discard this patch.
lib/public/GlobalScale/IConfig.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -32,20 +32,20 @@
 block discarded – undo
32 32
  */
33 33
 interface IConfig {
34 34
 
35
-	/**
36
-	 * check if global scale is enabled
37
-	 *
38
-	 * @since 12.0.1
39
-	 * @return bool
40
-	 */
41
-	public function isGlobalScaleEnabled();
35
+    /**
36
+     * check if global scale is enabled
37
+     *
38
+     * @since 12.0.1
39
+     * @return bool
40
+     */
41
+    public function isGlobalScaleEnabled();
42 42
 
43
-	/**
44
-	 * check if federation should only be used internally in a global scale setup
45
-	 *
46
-	 * @since 12.0.1
47
-	 * @return bool
48
-	 */
49
-	public function onlyInternalFederation();
43
+    /**
44
+     * check if federation should only be used internally in a global scale setup
45
+     *
46
+     * @since 12.0.1
47
+     * @return bool
48
+     */
49
+    public function onlyInternalFederation();
50 50
 
51 51
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -34,93 +34,93 @@
 block discarded – undo
34 34
 
35 35
 class Application extends App {
36 36
 
37
-	/** @var FederatedShareProvider */
38
-	protected $federatedShareProvider;
37
+    /** @var FederatedShareProvider */
38
+    protected $federatedShareProvider;
39 39
 
40
-	public function __construct() {
41
-		parent::__construct('federatedfilesharing');
40
+    public function __construct() {
41
+        parent::__construct('federatedfilesharing');
42 42
 
43
-		$container = $this->getContainer();
44
-		$server = $container->getServer();
43
+        $container = $this->getContainer();
44
+        $server = $container->getServer();
45 45
 
46
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
47
-			$addressHandler = new AddressHandler(
48
-				$server->getURLGenerator(),
49
-				$server->getL10N('federatedfilesharing'),
50
-				$server->getCloudIdManager()
51
-			);
52
-			$notification = new Notifications(
53
-				$addressHandler,
54
-				$server->getHTTPClientService(),
55
-				$server->query(\OCP\OCS\IDiscoveryService::class),
56
-				\OC::$server->getJobList()
57
-			);
58
-			return new RequestHandlerController(
59
-				$c->query('AppName'),
60
-				$server->getRequest(),
61
-				$this->getFederatedShareProvider(),
62
-				$server->getDatabaseConnection(),
63
-				$server->getShareManager(),
64
-				$notification,
65
-				$addressHandler,
66
-				$server->getUserManager(),
67
-				$server->getCloudIdManager()
68
-			);
69
-		});
70
-	}
46
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
47
+            $addressHandler = new AddressHandler(
48
+                $server->getURLGenerator(),
49
+                $server->getL10N('federatedfilesharing'),
50
+                $server->getCloudIdManager()
51
+            );
52
+            $notification = new Notifications(
53
+                $addressHandler,
54
+                $server->getHTTPClientService(),
55
+                $server->query(\OCP\OCS\IDiscoveryService::class),
56
+                \OC::$server->getJobList()
57
+            );
58
+            return new RequestHandlerController(
59
+                $c->query('AppName'),
60
+                $server->getRequest(),
61
+                $this->getFederatedShareProvider(),
62
+                $server->getDatabaseConnection(),
63
+                $server->getShareManager(),
64
+                $notification,
65
+                $addressHandler,
66
+                $server->getUserManager(),
67
+                $server->getCloudIdManager()
68
+            );
69
+        });
70
+    }
71 71
 
72
-	/**
73
-	 * register personal and admin settings page
74
-	 */
75
-	public function registerSettings() {
76
-		\OCP\App::registerPersonal('federatedfilesharing', 'settings-personal');
77
-	}
72
+    /**
73
+     * register personal and admin settings page
74
+     */
75
+    public function registerSettings() {
76
+        \OCP\App::registerPersonal('federatedfilesharing', 'settings-personal');
77
+    }
78 78
 
79
-	/**
80
-	 * get instance of federated share provider
81
-	 *
82
-	 * @return FederatedShareProvider
83
-	 */
84
-	public function getFederatedShareProvider() {
85
-		if ($this->federatedShareProvider === null) {
86
-			$this->initFederatedShareProvider();
87
-		}
88
-		return $this->federatedShareProvider;
89
-	}
79
+    /**
80
+     * get instance of federated share provider
81
+     *
82
+     * @return FederatedShareProvider
83
+     */
84
+    public function getFederatedShareProvider() {
85
+        if ($this->federatedShareProvider === null) {
86
+            $this->initFederatedShareProvider();
87
+        }
88
+        return $this->federatedShareProvider;
89
+    }
90 90
 
91
-	/**
92
-	 * initialize federated share provider
93
-	 */
94
-	protected function initFederatedShareProvider() {
95
-		$c = $this->getContainer();
96
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
97
-			\OC::$server->getURLGenerator(),
98
-			\OC::$server->getL10N('federatedfilesharing'),
99
-			\OC::$server->getCloudIdManager()
100
-		);
101
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
102
-			$addressHandler,
103
-			\OC::$server->getHTTPClientService(),
104
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
105
-			\OC::$server->getJobList()
106
-		);
107
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
108
-			\OC::$server->getSecureRandom()
109
-		);
91
+    /**
92
+     * initialize federated share provider
93
+     */
94
+    protected function initFederatedShareProvider() {
95
+        $c = $this->getContainer();
96
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
97
+            \OC::$server->getURLGenerator(),
98
+            \OC::$server->getL10N('federatedfilesharing'),
99
+            \OC::$server->getCloudIdManager()
100
+        );
101
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
102
+            $addressHandler,
103
+            \OC::$server->getHTTPClientService(),
104
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
105
+            \OC::$server->getJobList()
106
+        );
107
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
108
+            \OC::$server->getSecureRandom()
109
+        );
110 110
 
111
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
112
-			\OC::$server->getDatabaseConnection(),
113
-			$addressHandler,
114
-			$notifications,
115
-			$tokenHandler,
116
-			\OC::$server->getL10N('federatedfilesharing'),
117
-			\OC::$server->getLogger(),
118
-			\OC::$server->getLazyRootFolder(),
119
-			\OC::$server->getConfig(),
120
-			\OC::$server->getUserManager(),
121
-			\OC::$server->getCloudIdManager(),
122
-			$c->query(IConfig::class)
123
-		);
124
-	}
111
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
112
+            \OC::$server->getDatabaseConnection(),
113
+            $addressHandler,
114
+            $notifications,
115
+            $tokenHandler,
116
+            \OC::$server->getL10N('federatedfilesharing'),
117
+            \OC::$server->getLogger(),
118
+            \OC::$server->getLazyRootFolder(),
119
+            \OC::$server->getConfig(),
120
+            \OC::$server->getUserManager(),
121
+            \OC::$server->getCloudIdManager(),
122
+            $c->query(IConfig::class)
123
+        );
124
+    }
125 125
 
126 126
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 patch
Indentation   +974 added lines, -974 removed lines patch added patch discarded remove patch
@@ -50,988 +50,988 @@
 block discarded – undo
50 50
  */
51 51
 class FederatedShareProvider implements IShareProvider {
52 52
 
53
-	const SHARE_TYPE_REMOTE = 6;
54
-
55
-	/** @var IDBConnection */
56
-	private $dbConnection;
57
-
58
-	/** @var AddressHandler */
59
-	private $addressHandler;
60
-
61
-	/** @var Notifications */
62
-	private $notifications;
63
-
64
-	/** @var TokenHandler */
65
-	private $tokenHandler;
66
-
67
-	/** @var IL10N */
68
-	private $l;
69
-
70
-	/** @var ILogger */
71
-	private $logger;
72
-
73
-	/** @var IRootFolder */
74
-	private $rootFolder;
75
-
76
-	/** @var IConfig */
77
-	private $config;
78
-
79
-	/** @var string */
80
-	private $externalShareTable = 'share_external';
81
-
82
-	/** @var IUserManager */
83
-	private $userManager;
84
-
85
-	/** @var ICloudIdManager */
86
-	private $cloudIdManager;
87
-
88
-	/** @var \OCP\GlobalScale\IConfig */
89
-	private $gsConfig;
90
-
91
-	/**
92
-	 * DefaultShareProvider constructor.
93
-	 *
94
-	 * @param IDBConnection $connection
95
-	 * @param AddressHandler $addressHandler
96
-	 * @param Notifications $notifications
97
-	 * @param TokenHandler $tokenHandler
98
-	 * @param IL10N $l10n
99
-	 * @param ILogger $logger
100
-	 * @param IRootFolder $rootFolder
101
-	 * @param IConfig $config
102
-	 * @param IUserManager $userManager
103
-	 * @param ICloudIdManager $cloudIdManager
104
-	 * @param \OCP\GlobalScale\IConfig $globalScaleConfig
105
-	 */
106
-	public function __construct(
107
-			IDBConnection $connection,
108
-			AddressHandler $addressHandler,
109
-			Notifications $notifications,
110
-			TokenHandler $tokenHandler,
111
-			IL10N $l10n,
112
-			ILogger $logger,
113
-			IRootFolder $rootFolder,
114
-			IConfig $config,
115
-			IUserManager $userManager,
116
-			ICloudIdManager $cloudIdManager,
117
-			\OCP\GlobalScale\IConfig $globalScaleConfig
118
-	) {
119
-		$this->dbConnection = $connection;
120
-		$this->addressHandler = $addressHandler;
121
-		$this->notifications = $notifications;
122
-		$this->tokenHandler = $tokenHandler;
123
-		$this->l = $l10n;
124
-		$this->logger = $logger;
125
-		$this->rootFolder = $rootFolder;
126
-		$this->config = $config;
127
-		$this->userManager = $userManager;
128
-		$this->cloudIdManager = $cloudIdManager;
129
-		$this->gsConfig = $globalScaleConfig;
130
-	}
131
-
132
-	/**
133
-	 * Return the identifier of this provider.
134
-	 *
135
-	 * @return string Containing only [a-zA-Z0-9]
136
-	 */
137
-	public function identifier() {
138
-		return 'ocFederatedSharing';
139
-	}
140
-
141
-	/**
142
-	 * Share a path
143
-	 *
144
-	 * @param IShare $share
145
-	 * @return IShare The share object
146
-	 * @throws ShareNotFound
147
-	 * @throws \Exception
148
-	 */
149
-	public function create(IShare $share) {
150
-
151
-		$shareWith = $share->getSharedWith();
152
-		$itemSource = $share->getNodeId();
153
-		$itemType = $share->getNodeType();
154
-		$permissions = $share->getPermissions();
155
-		$sharedBy = $share->getSharedBy();
156
-
157
-		/*
53
+    const SHARE_TYPE_REMOTE = 6;
54
+
55
+    /** @var IDBConnection */
56
+    private $dbConnection;
57
+
58
+    /** @var AddressHandler */
59
+    private $addressHandler;
60
+
61
+    /** @var Notifications */
62
+    private $notifications;
63
+
64
+    /** @var TokenHandler */
65
+    private $tokenHandler;
66
+
67
+    /** @var IL10N */
68
+    private $l;
69
+
70
+    /** @var ILogger */
71
+    private $logger;
72
+
73
+    /** @var IRootFolder */
74
+    private $rootFolder;
75
+
76
+    /** @var IConfig */
77
+    private $config;
78
+
79
+    /** @var string */
80
+    private $externalShareTable = 'share_external';
81
+
82
+    /** @var IUserManager */
83
+    private $userManager;
84
+
85
+    /** @var ICloudIdManager */
86
+    private $cloudIdManager;
87
+
88
+    /** @var \OCP\GlobalScale\IConfig */
89
+    private $gsConfig;
90
+
91
+    /**
92
+     * DefaultShareProvider constructor.
93
+     *
94
+     * @param IDBConnection $connection
95
+     * @param AddressHandler $addressHandler
96
+     * @param Notifications $notifications
97
+     * @param TokenHandler $tokenHandler
98
+     * @param IL10N $l10n
99
+     * @param ILogger $logger
100
+     * @param IRootFolder $rootFolder
101
+     * @param IConfig $config
102
+     * @param IUserManager $userManager
103
+     * @param ICloudIdManager $cloudIdManager
104
+     * @param \OCP\GlobalScale\IConfig $globalScaleConfig
105
+     */
106
+    public function __construct(
107
+            IDBConnection $connection,
108
+            AddressHandler $addressHandler,
109
+            Notifications $notifications,
110
+            TokenHandler $tokenHandler,
111
+            IL10N $l10n,
112
+            ILogger $logger,
113
+            IRootFolder $rootFolder,
114
+            IConfig $config,
115
+            IUserManager $userManager,
116
+            ICloudIdManager $cloudIdManager,
117
+            \OCP\GlobalScale\IConfig $globalScaleConfig
118
+    ) {
119
+        $this->dbConnection = $connection;
120
+        $this->addressHandler = $addressHandler;
121
+        $this->notifications = $notifications;
122
+        $this->tokenHandler = $tokenHandler;
123
+        $this->l = $l10n;
124
+        $this->logger = $logger;
125
+        $this->rootFolder = $rootFolder;
126
+        $this->config = $config;
127
+        $this->userManager = $userManager;
128
+        $this->cloudIdManager = $cloudIdManager;
129
+        $this->gsConfig = $globalScaleConfig;
130
+    }
131
+
132
+    /**
133
+     * Return the identifier of this provider.
134
+     *
135
+     * @return string Containing only [a-zA-Z0-9]
136
+     */
137
+    public function identifier() {
138
+        return 'ocFederatedSharing';
139
+    }
140
+
141
+    /**
142
+     * Share a path
143
+     *
144
+     * @param IShare $share
145
+     * @return IShare The share object
146
+     * @throws ShareNotFound
147
+     * @throws \Exception
148
+     */
149
+    public function create(IShare $share) {
150
+
151
+        $shareWith = $share->getSharedWith();
152
+        $itemSource = $share->getNodeId();
153
+        $itemType = $share->getNodeType();
154
+        $permissions = $share->getPermissions();
155
+        $sharedBy = $share->getSharedBy();
156
+
157
+        /*
158 158
 		 * Check if file is not already shared with the remote user
159 159
 		 */
160
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
161
-		if (!empty($alreadyShared)) {
162
-			$message = 'Sharing %s failed, because this item is already shared with %s';
163
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
164
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
165
-			throw new \Exception($message_t);
166
-		}
167
-
168
-
169
-		// don't allow federated shares if source and target server are the same
170
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
171
-		$currentServer = $this->addressHandler->generateRemoteURL();
172
-		$currentUser = $sharedBy;
173
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
174
-			$message = 'Not allowed to create a federated share with the same user.';
175
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
176
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
177
-			throw new \Exception($message_t);
178
-		}
179
-
180
-
181
-		$share->setSharedWith($cloudId->getId());
182
-
183
-		try {
184
-			$remoteShare = $this->getShareFromExternalShareTable($share);
185
-		} catch (ShareNotFound $e) {
186
-			$remoteShare = null;
187
-		}
188
-
189
-		if ($remoteShare) {
190
-			try {
191
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
192
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
193
-				$share->setId($shareId);
194
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
195
-				// remote share was create successfully if we get a valid token as return
196
-				$send = is_string($token) && $token !== '';
197
-			} catch (\Exception $e) {
198
-				// fall back to old re-share behavior if the remote server
199
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
200
-				$this->removeShareFromTable($share);
201
-				$shareId = $this->createFederatedShare($share);
202
-			}
203
-			if ($send) {
204
-				$this->updateSuccessfulReshare($shareId, $token);
205
-				$this->storeRemoteId($shareId, $remoteId);
206
-			} else {
207
-				$this->removeShareFromTable($share);
208
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
209
-				throw new \Exception($message_t);
210
-			}
211
-
212
-		} else {
213
-			$shareId = $this->createFederatedShare($share);
214
-		}
215
-
216
-		$data = $this->getRawShare($shareId);
217
-		return $this->createShareObject($data);
218
-	}
219
-
220
-	/**
221
-	 * create federated share and inform the recipient
222
-	 *
223
-	 * @param IShare $share
224
-	 * @return int
225
-	 * @throws ShareNotFound
226
-	 * @throws \Exception
227
-	 */
228
-	protected function createFederatedShare(IShare $share) {
229
-		$token = $this->tokenHandler->generateToken();
230
-		$shareId = $this->addShareToDB(
231
-			$share->getNodeId(),
232
-			$share->getNodeType(),
233
-			$share->getSharedWith(),
234
-			$share->getSharedBy(),
235
-			$share->getShareOwner(),
236
-			$share->getPermissions(),
237
-			$token
238
-		);
239
-
240
-		$failure = false;
241
-
242
-		try {
243
-			$sharedByFederatedId = $share->getSharedBy();
244
-			if ($this->userManager->userExists($sharedByFederatedId)) {
245
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
246
-				$sharedByFederatedId = $cloudId->getId();
247
-			}
248
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
249
-			$send = $this->notifications->sendRemoteShare(
250
-				$token,
251
-				$share->getSharedWith(),
252
-				$share->getNode()->getName(),
253
-				$shareId,
254
-				$share->getShareOwner(),
255
-				$ownerCloudId->getId(),
256
-				$share->getSharedBy(),
257
-				$sharedByFederatedId
258
-			);
259
-
260
-			if ($send === false) {
261
-				$failure = true;
262
-			}
263
-		} catch (\Exception $e) {
264
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
265
-			$failure = true;
266
-		}
267
-
268
-		if($failure) {
269
-			$this->removeShareFromTableById($shareId);
270
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
271
-				[$share->getNode()->getName(), $share->getSharedWith()]);
272
-			throw new \Exception($message_t);
273
-		}
274
-
275
-		return $shareId;
276
-
277
-	}
278
-
279
-	/**
280
-	 * @param string $shareWith
281
-	 * @param IShare $share
282
-	 * @param string $shareId internal share Id
283
-	 * @return array
284
-	 * @throws \Exception
285
-	 */
286
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
287
-
288
-		$remoteShare = $this->getShareFromExternalShareTable($share);
289
-		$token = $remoteShare['share_token'];
290
-		$remoteId = $remoteShare['remote_id'];
291
-		$remote = $remoteShare['remote'];
292
-
293
-		list($token, $remoteId) = $this->notifications->requestReShare(
294
-			$token,
295
-			$remoteId,
296
-			$shareId,
297
-			$remote,
298
-			$shareWith,
299
-			$share->getPermissions()
300
-		);
301
-
302
-		return [$token, $remoteId];
303
-	}
304
-
305
-	/**
306
-	 * get federated share from the share_external table but exclude mounted link shares
307
-	 *
308
-	 * @param IShare $share
309
-	 * @return array
310
-	 * @throws ShareNotFound
311
-	 */
312
-	protected function getShareFromExternalShareTable(IShare $share) {
313
-		$query = $this->dbConnection->getQueryBuilder();
314
-		$query->select('*')->from($this->externalShareTable)
315
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
316
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
317
-		$result = $query->execute()->fetchAll();
318
-
319
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
320
-			return $result[0];
321
-		}
322
-
323
-		throw new ShareNotFound('share not found in share_external table');
324
-	}
325
-
326
-	/**
327
-	 * add share to the database and return the ID
328
-	 *
329
-	 * @param int $itemSource
330
-	 * @param string $itemType
331
-	 * @param string $shareWith
332
-	 * @param string $sharedBy
333
-	 * @param string $uidOwner
334
-	 * @param int $permissions
335
-	 * @param string $token
336
-	 * @return int
337
-	 */
338
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
339
-		$qb = $this->dbConnection->getQueryBuilder();
340
-		$qb->insert('share')
341
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
342
-			->setValue('item_type', $qb->createNamedParameter($itemType))
343
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
344
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
345
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
346
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
347
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
348
-			->setValue('permissions', $qb->createNamedParameter($permissions))
349
-			->setValue('token', $qb->createNamedParameter($token))
350
-			->setValue('stime', $qb->createNamedParameter(time()));
351
-
352
-		/*
160
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
161
+        if (!empty($alreadyShared)) {
162
+            $message = 'Sharing %s failed, because this item is already shared with %s';
163
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
164
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
165
+            throw new \Exception($message_t);
166
+        }
167
+
168
+
169
+        // don't allow federated shares if source and target server are the same
170
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
171
+        $currentServer = $this->addressHandler->generateRemoteURL();
172
+        $currentUser = $sharedBy;
173
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
174
+            $message = 'Not allowed to create a federated share with the same user.';
175
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
176
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
177
+            throw new \Exception($message_t);
178
+        }
179
+
180
+
181
+        $share->setSharedWith($cloudId->getId());
182
+
183
+        try {
184
+            $remoteShare = $this->getShareFromExternalShareTable($share);
185
+        } catch (ShareNotFound $e) {
186
+            $remoteShare = null;
187
+        }
188
+
189
+        if ($remoteShare) {
190
+            try {
191
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
192
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
193
+                $share->setId($shareId);
194
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
195
+                // remote share was create successfully if we get a valid token as return
196
+                $send = is_string($token) && $token !== '';
197
+            } catch (\Exception $e) {
198
+                // fall back to old re-share behavior if the remote server
199
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
200
+                $this->removeShareFromTable($share);
201
+                $shareId = $this->createFederatedShare($share);
202
+            }
203
+            if ($send) {
204
+                $this->updateSuccessfulReshare($shareId, $token);
205
+                $this->storeRemoteId($shareId, $remoteId);
206
+            } else {
207
+                $this->removeShareFromTable($share);
208
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
209
+                throw new \Exception($message_t);
210
+            }
211
+
212
+        } else {
213
+            $shareId = $this->createFederatedShare($share);
214
+        }
215
+
216
+        $data = $this->getRawShare($shareId);
217
+        return $this->createShareObject($data);
218
+    }
219
+
220
+    /**
221
+     * create federated share and inform the recipient
222
+     *
223
+     * @param IShare $share
224
+     * @return int
225
+     * @throws ShareNotFound
226
+     * @throws \Exception
227
+     */
228
+    protected function createFederatedShare(IShare $share) {
229
+        $token = $this->tokenHandler->generateToken();
230
+        $shareId = $this->addShareToDB(
231
+            $share->getNodeId(),
232
+            $share->getNodeType(),
233
+            $share->getSharedWith(),
234
+            $share->getSharedBy(),
235
+            $share->getShareOwner(),
236
+            $share->getPermissions(),
237
+            $token
238
+        );
239
+
240
+        $failure = false;
241
+
242
+        try {
243
+            $sharedByFederatedId = $share->getSharedBy();
244
+            if ($this->userManager->userExists($sharedByFederatedId)) {
245
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
246
+                $sharedByFederatedId = $cloudId->getId();
247
+            }
248
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
249
+            $send = $this->notifications->sendRemoteShare(
250
+                $token,
251
+                $share->getSharedWith(),
252
+                $share->getNode()->getName(),
253
+                $shareId,
254
+                $share->getShareOwner(),
255
+                $ownerCloudId->getId(),
256
+                $share->getSharedBy(),
257
+                $sharedByFederatedId
258
+            );
259
+
260
+            if ($send === false) {
261
+                $failure = true;
262
+            }
263
+        } catch (\Exception $e) {
264
+            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
265
+            $failure = true;
266
+        }
267
+
268
+        if($failure) {
269
+            $this->removeShareFromTableById($shareId);
270
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
271
+                [$share->getNode()->getName(), $share->getSharedWith()]);
272
+            throw new \Exception($message_t);
273
+        }
274
+
275
+        return $shareId;
276
+
277
+    }
278
+
279
+    /**
280
+     * @param string $shareWith
281
+     * @param IShare $share
282
+     * @param string $shareId internal share Id
283
+     * @return array
284
+     * @throws \Exception
285
+     */
286
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
287
+
288
+        $remoteShare = $this->getShareFromExternalShareTable($share);
289
+        $token = $remoteShare['share_token'];
290
+        $remoteId = $remoteShare['remote_id'];
291
+        $remote = $remoteShare['remote'];
292
+
293
+        list($token, $remoteId) = $this->notifications->requestReShare(
294
+            $token,
295
+            $remoteId,
296
+            $shareId,
297
+            $remote,
298
+            $shareWith,
299
+            $share->getPermissions()
300
+        );
301
+
302
+        return [$token, $remoteId];
303
+    }
304
+
305
+    /**
306
+     * get federated share from the share_external table but exclude mounted link shares
307
+     *
308
+     * @param IShare $share
309
+     * @return array
310
+     * @throws ShareNotFound
311
+     */
312
+    protected function getShareFromExternalShareTable(IShare $share) {
313
+        $query = $this->dbConnection->getQueryBuilder();
314
+        $query->select('*')->from($this->externalShareTable)
315
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
316
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
317
+        $result = $query->execute()->fetchAll();
318
+
319
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
320
+            return $result[0];
321
+        }
322
+
323
+        throw new ShareNotFound('share not found in share_external table');
324
+    }
325
+
326
+    /**
327
+     * add share to the database and return the ID
328
+     *
329
+     * @param int $itemSource
330
+     * @param string $itemType
331
+     * @param string $shareWith
332
+     * @param string $sharedBy
333
+     * @param string $uidOwner
334
+     * @param int $permissions
335
+     * @param string $token
336
+     * @return int
337
+     */
338
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
339
+        $qb = $this->dbConnection->getQueryBuilder();
340
+        $qb->insert('share')
341
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
342
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
343
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
344
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
345
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
346
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
347
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
348
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
349
+            ->setValue('token', $qb->createNamedParameter($token))
350
+            ->setValue('stime', $qb->createNamedParameter(time()));
351
+
352
+        /*
353 353
 		 * Added to fix https://github.com/owncloud/core/issues/22215
354 354
 		 * Can be removed once we get rid of ajax/share.php
355 355
 		 */
356
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
357
-
358
-		$qb->execute();
359
-		$id = $qb->getLastInsertId();
360
-
361
-		return (int)$id;
362
-	}
363
-
364
-	/**
365
-	 * Update a share
366
-	 *
367
-	 * @param IShare $share
368
-	 * @return IShare The share object
369
-	 */
370
-	public function update(IShare $share) {
371
-		/*
356
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
357
+
358
+        $qb->execute();
359
+        $id = $qb->getLastInsertId();
360
+
361
+        return (int)$id;
362
+    }
363
+
364
+    /**
365
+     * Update a share
366
+     *
367
+     * @param IShare $share
368
+     * @return IShare The share object
369
+     */
370
+    public function update(IShare $share) {
371
+        /*
372 372
 		 * We allow updating the permissions of federated shares
373 373
 		 */
374
-		$qb = $this->dbConnection->getQueryBuilder();
375
-			$qb->update('share')
376
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
377
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
378
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
379
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
380
-				->execute();
381
-
382
-		// send the updated permission to the owner/initiator, if they are not the same
383
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
384
-			$this->sendPermissionUpdate($share);
385
-		}
386
-
387
-		return $share;
388
-	}
389
-
390
-	/**
391
-	 * send the updated permission to the owner/initiator, if they are not the same
392
-	 *
393
-	 * @param IShare $share
394
-	 * @throws ShareNotFound
395
-	 * @throws \OC\HintException
396
-	 */
397
-	protected function sendPermissionUpdate(IShare $share) {
398
-		$remoteId = $this->getRemoteId($share);
399
-		// if the local user is the owner we send the permission change to the initiator
400
-		if ($this->userManager->userExists($share->getShareOwner())) {
401
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
402
-		} else { // ... if not we send the permission change to the owner
403
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
404
-		}
405
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
406
-	}
407
-
408
-
409
-	/**
410
-	 * update successful reShare with the correct token
411
-	 *
412
-	 * @param int $shareId
413
-	 * @param string $token
414
-	 */
415
-	protected function updateSuccessfulReShare($shareId, $token) {
416
-		$query = $this->dbConnection->getQueryBuilder();
417
-		$query->update('share')
418
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
419
-			->set('token', $query->createNamedParameter($token))
420
-			->execute();
421
-	}
422
-
423
-	/**
424
-	 * store remote ID in federated reShare table
425
-	 *
426
-	 * @param $shareId
427
-	 * @param $remoteId
428
-	 */
429
-	public function storeRemoteId($shareId, $remoteId) {
430
-		$query = $this->dbConnection->getQueryBuilder();
431
-		$query->insert('federated_reshares')
432
-			->values(
433
-				[
434
-					'share_id' =>  $query->createNamedParameter($shareId),
435
-					'remote_id' => $query->createNamedParameter($remoteId),
436
-				]
437
-			);
438
-		$query->execute();
439
-	}
440
-
441
-	/**
442
-	 * get share ID on remote server for federated re-shares
443
-	 *
444
-	 * @param IShare $share
445
-	 * @return int
446
-	 * @throws ShareNotFound
447
-	 */
448
-	public function getRemoteId(IShare $share) {
449
-		$query = $this->dbConnection->getQueryBuilder();
450
-		$query->select('remote_id')->from('federated_reshares')
451
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
452
-		$data = $query->execute()->fetch();
453
-
454
-		if (!is_array($data) || !isset($data['remote_id'])) {
455
-			throw new ShareNotFound();
456
-		}
457
-
458
-		return (int)$data['remote_id'];
459
-	}
460
-
461
-	/**
462
-	 * @inheritdoc
463
-	 */
464
-	public function move(IShare $share, $recipient) {
465
-		/*
374
+        $qb = $this->dbConnection->getQueryBuilder();
375
+            $qb->update('share')
376
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
377
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
378
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
379
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
380
+                ->execute();
381
+
382
+        // send the updated permission to the owner/initiator, if they are not the same
383
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
384
+            $this->sendPermissionUpdate($share);
385
+        }
386
+
387
+        return $share;
388
+    }
389
+
390
+    /**
391
+     * send the updated permission to the owner/initiator, if they are not the same
392
+     *
393
+     * @param IShare $share
394
+     * @throws ShareNotFound
395
+     * @throws \OC\HintException
396
+     */
397
+    protected function sendPermissionUpdate(IShare $share) {
398
+        $remoteId = $this->getRemoteId($share);
399
+        // if the local user is the owner we send the permission change to the initiator
400
+        if ($this->userManager->userExists($share->getShareOwner())) {
401
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
402
+        } else { // ... if not we send the permission change to the owner
403
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
404
+        }
405
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
406
+    }
407
+
408
+
409
+    /**
410
+     * update successful reShare with the correct token
411
+     *
412
+     * @param int $shareId
413
+     * @param string $token
414
+     */
415
+    protected function updateSuccessfulReShare($shareId, $token) {
416
+        $query = $this->dbConnection->getQueryBuilder();
417
+        $query->update('share')
418
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
419
+            ->set('token', $query->createNamedParameter($token))
420
+            ->execute();
421
+    }
422
+
423
+    /**
424
+     * store remote ID in federated reShare table
425
+     *
426
+     * @param $shareId
427
+     * @param $remoteId
428
+     */
429
+    public function storeRemoteId($shareId, $remoteId) {
430
+        $query = $this->dbConnection->getQueryBuilder();
431
+        $query->insert('federated_reshares')
432
+            ->values(
433
+                [
434
+                    'share_id' =>  $query->createNamedParameter($shareId),
435
+                    'remote_id' => $query->createNamedParameter($remoteId),
436
+                ]
437
+            );
438
+        $query->execute();
439
+    }
440
+
441
+    /**
442
+     * get share ID on remote server for federated re-shares
443
+     *
444
+     * @param IShare $share
445
+     * @return int
446
+     * @throws ShareNotFound
447
+     */
448
+    public function getRemoteId(IShare $share) {
449
+        $query = $this->dbConnection->getQueryBuilder();
450
+        $query->select('remote_id')->from('federated_reshares')
451
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
452
+        $data = $query->execute()->fetch();
453
+
454
+        if (!is_array($data) || !isset($data['remote_id'])) {
455
+            throw new ShareNotFound();
456
+        }
457
+
458
+        return (int)$data['remote_id'];
459
+    }
460
+
461
+    /**
462
+     * @inheritdoc
463
+     */
464
+    public function move(IShare $share, $recipient) {
465
+        /*
466 466
 		 * This function does nothing yet as it is just for outgoing
467 467
 		 * federated shares.
468 468
 		 */
469
-		return $share;
470
-	}
471
-
472
-	/**
473
-	 * Get all children of this share
474
-	 *
475
-	 * @param IShare $parent
476
-	 * @return IShare[]
477
-	 */
478
-	public function getChildren(IShare $parent) {
479
-		$children = [];
480
-
481
-		$qb = $this->dbConnection->getQueryBuilder();
482
-		$qb->select('*')
483
-			->from('share')
484
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
485
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
486
-			->orderBy('id');
487
-
488
-		$cursor = $qb->execute();
489
-		while($data = $cursor->fetch()) {
490
-			$children[] = $this->createShareObject($data);
491
-		}
492
-		$cursor->closeCursor();
493
-
494
-		return $children;
495
-	}
496
-
497
-	/**
498
-	 * Delete a share (owner unShares the file)
499
-	 *
500
-	 * @param IShare $share
501
-	 */
502
-	public function delete(IShare $share) {
503
-
504
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
505
-
506
-		$isOwner = false;
507
-
508
-		$this->removeShareFromTable($share);
509
-
510
-		// if the local user is the owner we can send the unShare request directly...
511
-		if ($this->userManager->userExists($share->getShareOwner())) {
512
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
513
-			$this->revokeShare($share, true);
514
-			$isOwner = true;
515
-		} else { // ... if not we need to correct ID for the unShare request
516
-			$remoteId = $this->getRemoteId($share);
517
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
518
-			$this->revokeShare($share, false);
519
-		}
520
-
521
-		// send revoke notification to the other user, if initiator and owner are not the same user
522
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
523
-			$remoteId = $this->getRemoteId($share);
524
-			if ($isOwner) {
525
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
526
-			} else {
527
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
528
-			}
529
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
530
-		}
531
-	}
532
-
533
-	/**
534
-	 * in case of a re-share we need to send the other use (initiator or owner)
535
-	 * a message that the file was unshared
536
-	 *
537
-	 * @param IShare $share
538
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
539
-	 * @throws ShareNotFound
540
-	 * @throws \OC\HintException
541
-	 */
542
-	protected function revokeShare($share, $isOwner) {
543
-		// also send a unShare request to the initiator, if this is a different user than the owner
544
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
545
-			if ($isOwner) {
546
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
547
-			} else {
548
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
549
-			}
550
-			$remoteId = $this->getRemoteId($share);
551
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
552
-		}
553
-	}
554
-
555
-	/**
556
-	 * remove share from table
557
-	 *
558
-	 * @param IShare $share
559
-	 */
560
-	public function removeShareFromTable(IShare $share) {
561
-		$this->removeShareFromTableById($share->getId());
562
-	}
563
-
564
-	/**
565
-	 * remove share from table
566
-	 *
567
-	 * @param string $shareId
568
-	 */
569
-	private function removeShareFromTableById($shareId) {
570
-		$qb = $this->dbConnection->getQueryBuilder();
571
-		$qb->delete('share')
572
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
573
-		$qb->execute();
574
-
575
-		$qb->delete('federated_reshares')
576
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
577
-		$qb->execute();
578
-	}
579
-
580
-	/**
581
-	 * @inheritdoc
582
-	 */
583
-	public function deleteFromSelf(IShare $share, $recipient) {
584
-		// nothing to do here. Technically deleteFromSelf in the context of federated
585
-		// shares is a umount of a external storage. This is handled here
586
-		// apps/files_sharing/lib/external/manager.php
587
-		// TODO move this code over to this app
588
-		return;
589
-	}
590
-
591
-
592
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
593
-		$qb = $this->dbConnection->getQueryBuilder();
594
-		$qb->select('*')
595
-			->from('share', 's')
596
-			->andWhere($qb->expr()->orX(
597
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
598
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
599
-			))
600
-			->andWhere(
601
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
602
-			);
603
-
604
-		/**
605
-		 * Reshares for this user are shares where they are the owner.
606
-		 */
607
-		if ($reshares === false) {
608
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
609
-		} else {
610
-			$qb->andWhere(
611
-				$qb->expr()->orX(
612
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
613
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
614
-				)
615
-			);
616
-		}
617
-
618
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
619
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
620
-
621
-		$qb->orderBy('id');
622
-
623
-		$cursor = $qb->execute();
624
-		$shares = [];
625
-		while ($data = $cursor->fetch()) {
626
-			$shares[$data['fileid']][] = $this->createShareObject($data);
627
-		}
628
-		$cursor->closeCursor();
629
-
630
-		return $shares;
631
-	}
632
-
633
-	/**
634
-	 * @inheritdoc
635
-	 */
636
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
637
-		$qb = $this->dbConnection->getQueryBuilder();
638
-		$qb->select('*')
639
-			->from('share');
640
-
641
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
642
-
643
-		/**
644
-		 * Reshares for this user are shares where they are the owner.
645
-		 */
646
-		if ($reshares === false) {
647
-			//Special case for old shares created via the web UI
648
-			$or1 = $qb->expr()->andX(
649
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
650
-				$qb->expr()->isNull('uid_initiator')
651
-			);
652
-
653
-			$qb->andWhere(
654
-				$qb->expr()->orX(
655
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
656
-					$or1
657
-				)
658
-			);
659
-		} else {
660
-			$qb->andWhere(
661
-				$qb->expr()->orX(
662
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
663
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
664
-				)
665
-			);
666
-		}
667
-
668
-		if ($node !== null) {
669
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
670
-		}
671
-
672
-		if ($limit !== -1) {
673
-			$qb->setMaxResults($limit);
674
-		}
675
-
676
-		$qb->setFirstResult($offset);
677
-		$qb->orderBy('id');
678
-
679
-		$cursor = $qb->execute();
680
-		$shares = [];
681
-		while($data = $cursor->fetch()) {
682
-			$shares[] = $this->createShareObject($data);
683
-		}
684
-		$cursor->closeCursor();
685
-
686
-		return $shares;
687
-	}
688
-
689
-	/**
690
-	 * @inheritdoc
691
-	 */
692
-	public function getShareById($id, $recipientId = null) {
693
-		$qb = $this->dbConnection->getQueryBuilder();
694
-
695
-		$qb->select('*')
696
-			->from('share')
697
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
698
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
699
-
700
-		$cursor = $qb->execute();
701
-		$data = $cursor->fetch();
702
-		$cursor->closeCursor();
703
-
704
-		if ($data === false) {
705
-			throw new ShareNotFound();
706
-		}
707
-
708
-		try {
709
-			$share = $this->createShareObject($data);
710
-		} catch (InvalidShare $e) {
711
-			throw new ShareNotFound();
712
-		}
713
-
714
-		return $share;
715
-	}
716
-
717
-	/**
718
-	 * Get shares for a given path
719
-	 *
720
-	 * @param \OCP\Files\Node $path
721
-	 * @return IShare[]
722
-	 */
723
-	public function getSharesByPath(Node $path) {
724
-		$qb = $this->dbConnection->getQueryBuilder();
725
-
726
-		$cursor = $qb->select('*')
727
-			->from('share')
728
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
729
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
730
-			->execute();
731
-
732
-		$shares = [];
733
-		while($data = $cursor->fetch()) {
734
-			$shares[] = $this->createShareObject($data);
735
-		}
736
-		$cursor->closeCursor();
737
-
738
-		return $shares;
739
-	}
740
-
741
-	/**
742
-	 * @inheritdoc
743
-	 */
744
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
745
-		/** @var IShare[] $shares */
746
-		$shares = [];
747
-
748
-		//Get shares directly with this user
749
-		$qb = $this->dbConnection->getQueryBuilder();
750
-		$qb->select('*')
751
-			->from('share');
752
-
753
-		// Order by id
754
-		$qb->orderBy('id');
755
-
756
-		// Set limit and offset
757
-		if ($limit !== -1) {
758
-			$qb->setMaxResults($limit);
759
-		}
760
-		$qb->setFirstResult($offset);
761
-
762
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
763
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
764
-
765
-		// Filter by node if provided
766
-		if ($node !== null) {
767
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
768
-		}
769
-
770
-		$cursor = $qb->execute();
771
-
772
-		while($data = $cursor->fetch()) {
773
-			$shares[] = $this->createShareObject($data);
774
-		}
775
-		$cursor->closeCursor();
776
-
777
-
778
-		return $shares;
779
-	}
780
-
781
-	/**
782
-	 * Get a share by token
783
-	 *
784
-	 * @param string $token
785
-	 * @return IShare
786
-	 * @throws ShareNotFound
787
-	 */
788
-	public function getShareByToken($token) {
789
-		$qb = $this->dbConnection->getQueryBuilder();
790
-
791
-		$cursor = $qb->select('*')
792
-			->from('share')
793
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
794
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
795
-			->execute();
796
-
797
-		$data = $cursor->fetch();
798
-
799
-		if ($data === false) {
800
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
801
-		}
802
-
803
-		try {
804
-			$share = $this->createShareObject($data);
805
-		} catch (InvalidShare $e) {
806
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
807
-		}
808
-
809
-		return $share;
810
-	}
811
-
812
-	/**
813
-	 * get database row of a give share
814
-	 *
815
-	 * @param $id
816
-	 * @return array
817
-	 * @throws ShareNotFound
818
-	 */
819
-	private function getRawShare($id) {
820
-
821
-		// Now fetch the inserted share and create a complete share object
822
-		$qb = $this->dbConnection->getQueryBuilder();
823
-		$qb->select('*')
824
-			->from('share')
825
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
826
-
827
-		$cursor = $qb->execute();
828
-		$data = $cursor->fetch();
829
-		$cursor->closeCursor();
830
-
831
-		if ($data === false) {
832
-			throw new ShareNotFound;
833
-		}
834
-
835
-		return $data;
836
-	}
837
-
838
-	/**
839
-	 * Create a share object from an database row
840
-	 *
841
-	 * @param array $data
842
-	 * @return IShare
843
-	 * @throws InvalidShare
844
-	 * @throws ShareNotFound
845
-	 */
846
-	private function createShareObject($data) {
847
-
848
-		$share = new Share($this->rootFolder, $this->userManager);
849
-		$share->setId((int)$data['id'])
850
-			->setShareType((int)$data['share_type'])
851
-			->setPermissions((int)$data['permissions'])
852
-			->setTarget($data['file_target'])
853
-			->setMailSend((bool)$data['mail_send'])
854
-			->setToken($data['token']);
855
-
856
-		$shareTime = new \DateTime();
857
-		$shareTime->setTimestamp((int)$data['stime']);
858
-		$share->setShareTime($shareTime);
859
-		$share->setSharedWith($data['share_with']);
860
-
861
-		if ($data['uid_initiator'] !== null) {
862
-			$share->setShareOwner($data['uid_owner']);
863
-			$share->setSharedBy($data['uid_initiator']);
864
-		} else {
865
-			//OLD SHARE
866
-			$share->setSharedBy($data['uid_owner']);
867
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
868
-
869
-			$owner = $path->getOwner();
870
-			$share->setShareOwner($owner->getUID());
871
-		}
872
-
873
-		$share->setNodeId((int)$data['file_source']);
874
-		$share->setNodeType($data['item_type']);
875
-
876
-		$share->setProviderId($this->identifier());
877
-
878
-		return $share;
879
-	}
880
-
881
-	/**
882
-	 * Get the node with file $id for $user
883
-	 *
884
-	 * @param string $userId
885
-	 * @param int $id
886
-	 * @return \OCP\Files\File|\OCP\Files\Folder
887
-	 * @throws InvalidShare
888
-	 */
889
-	private function getNode($userId, $id) {
890
-		try {
891
-			$userFolder = $this->rootFolder->getUserFolder($userId);
892
-		} catch (NotFoundException $e) {
893
-			throw new InvalidShare();
894
-		}
895
-
896
-		$nodes = $userFolder->getById($id);
897
-
898
-		if (empty($nodes)) {
899
-			throw new InvalidShare();
900
-		}
901
-
902
-		return $nodes[0];
903
-	}
904
-
905
-	/**
906
-	 * A user is deleted from the system
907
-	 * So clean up the relevant shares.
908
-	 *
909
-	 * @param string $uid
910
-	 * @param int $shareType
911
-	 */
912
-	public function userDeleted($uid, $shareType) {
913
-		//TODO: probabaly a good idea to send unshare info to remote servers
914
-
915
-		$qb = $this->dbConnection->getQueryBuilder();
916
-
917
-		$qb->delete('share')
918
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
919
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
920
-			->execute();
921
-	}
922
-
923
-	/**
924
-	 * This provider does not handle groups
925
-	 *
926
-	 * @param string $gid
927
-	 */
928
-	public function groupDeleted($gid) {
929
-		// We don't handle groups here
930
-		return;
931
-	}
932
-
933
-	/**
934
-	 * This provider does not handle groups
935
-	 *
936
-	 * @param string $uid
937
-	 * @param string $gid
938
-	 */
939
-	public function userDeletedFromGroup($uid, $gid) {
940
-		// We don't handle groups here
941
-		return;
942
-	}
943
-
944
-	/**
945
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
946
-	 *
947
-	 * @return bool
948
-	 */
949
-	public function isOutgoingServer2serverShareEnabled() {
950
-		if ($this->gsConfig->onlyInternalFederation()) {
951
-			return false;
952
-		}
953
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
954
-		return ($result === 'yes');
955
-	}
956
-
957
-	/**
958
-	 * check if users are allowed to mount public links from other Nextclouds
959
-	 *
960
-	 * @return bool
961
-	 */
962
-	public function isIncomingServer2serverShareEnabled() {
963
-		if ($this->gsConfig->onlyInternalFederation()) {
964
-			return false;
965
-		}
966
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
967
-		return ($result === 'yes');
968
-	}
969
-
970
-	/**
971
-	 * Check if querying sharees on the lookup server is enabled
972
-	 *
973
-	 * @return bool
974
-	 */
975
-	public function isLookupServerQueriesEnabled() {
976
-		// in a global scale setup we should always query the lookup server
977
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
978
-			return true;
979
-		}
980
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
981
-		return ($result === 'yes');
982
-	}
983
-
984
-
985
-	/**
986
-	 * Check if it is allowed to publish user specific data to the lookup server
987
-	 *
988
-	 * @return bool
989
-	 */
990
-	public function isLookupServerUploadEnabled() {
991
-		// in a global scale setup the admin is responsible to keep the lookup server up-to-date
992
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
993
-			return false;
994
-		}
995
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
996
-		return ($result === 'yes');
997
-	}
998
-
999
-	/**
1000
-	 * @inheritdoc
1001
-	 */
1002
-	public function getAccessList($nodes, $currentAccess) {
1003
-		$ids = [];
1004
-		foreach ($nodes as $node) {
1005
-			$ids[] = $node->getId();
1006
-		}
1007
-
1008
-		$qb = $this->dbConnection->getQueryBuilder();
1009
-		$qb->select('share_with', 'token', 'file_source')
1010
-			->from('share')
1011
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1012
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1013
-			->andWhere($qb->expr()->orX(
1014
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1015
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1016
-			));
1017
-		$cursor = $qb->execute();
1018
-
1019
-		if ($currentAccess === false) {
1020
-			$remote = $cursor->fetch() !== false;
1021
-			$cursor->closeCursor();
1022
-
1023
-			return ['remote' => $remote];
1024
-		}
1025
-
1026
-		$remote = [];
1027
-		while ($row = $cursor->fetch()) {
1028
-			$remote[$row['share_with']] = [
1029
-				'node_id' => $row['file_source'],
1030
-				'token' => $row['token'],
1031
-			];
1032
-		}
1033
-		$cursor->closeCursor();
1034
-
1035
-		return ['remote' => $remote];
1036
-	}
469
+        return $share;
470
+    }
471
+
472
+    /**
473
+     * Get all children of this share
474
+     *
475
+     * @param IShare $parent
476
+     * @return IShare[]
477
+     */
478
+    public function getChildren(IShare $parent) {
479
+        $children = [];
480
+
481
+        $qb = $this->dbConnection->getQueryBuilder();
482
+        $qb->select('*')
483
+            ->from('share')
484
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
485
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
486
+            ->orderBy('id');
487
+
488
+        $cursor = $qb->execute();
489
+        while($data = $cursor->fetch()) {
490
+            $children[] = $this->createShareObject($data);
491
+        }
492
+        $cursor->closeCursor();
493
+
494
+        return $children;
495
+    }
496
+
497
+    /**
498
+     * Delete a share (owner unShares the file)
499
+     *
500
+     * @param IShare $share
501
+     */
502
+    public function delete(IShare $share) {
503
+
504
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
505
+
506
+        $isOwner = false;
507
+
508
+        $this->removeShareFromTable($share);
509
+
510
+        // if the local user is the owner we can send the unShare request directly...
511
+        if ($this->userManager->userExists($share->getShareOwner())) {
512
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
513
+            $this->revokeShare($share, true);
514
+            $isOwner = true;
515
+        } else { // ... if not we need to correct ID for the unShare request
516
+            $remoteId = $this->getRemoteId($share);
517
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
518
+            $this->revokeShare($share, false);
519
+        }
520
+
521
+        // send revoke notification to the other user, if initiator and owner are not the same user
522
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
523
+            $remoteId = $this->getRemoteId($share);
524
+            if ($isOwner) {
525
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
526
+            } else {
527
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
528
+            }
529
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
530
+        }
531
+    }
532
+
533
+    /**
534
+     * in case of a re-share we need to send the other use (initiator or owner)
535
+     * a message that the file was unshared
536
+     *
537
+     * @param IShare $share
538
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
539
+     * @throws ShareNotFound
540
+     * @throws \OC\HintException
541
+     */
542
+    protected function revokeShare($share, $isOwner) {
543
+        // also send a unShare request to the initiator, if this is a different user than the owner
544
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
545
+            if ($isOwner) {
546
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
547
+            } else {
548
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
549
+            }
550
+            $remoteId = $this->getRemoteId($share);
551
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
552
+        }
553
+    }
554
+
555
+    /**
556
+     * remove share from table
557
+     *
558
+     * @param IShare $share
559
+     */
560
+    public function removeShareFromTable(IShare $share) {
561
+        $this->removeShareFromTableById($share->getId());
562
+    }
563
+
564
+    /**
565
+     * remove share from table
566
+     *
567
+     * @param string $shareId
568
+     */
569
+    private function removeShareFromTableById($shareId) {
570
+        $qb = $this->dbConnection->getQueryBuilder();
571
+        $qb->delete('share')
572
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
573
+        $qb->execute();
574
+
575
+        $qb->delete('federated_reshares')
576
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
577
+        $qb->execute();
578
+    }
579
+
580
+    /**
581
+     * @inheritdoc
582
+     */
583
+    public function deleteFromSelf(IShare $share, $recipient) {
584
+        // nothing to do here. Technically deleteFromSelf in the context of federated
585
+        // shares is a umount of a external storage. This is handled here
586
+        // apps/files_sharing/lib/external/manager.php
587
+        // TODO move this code over to this app
588
+        return;
589
+    }
590
+
591
+
592
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
593
+        $qb = $this->dbConnection->getQueryBuilder();
594
+        $qb->select('*')
595
+            ->from('share', 's')
596
+            ->andWhere($qb->expr()->orX(
597
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
598
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
599
+            ))
600
+            ->andWhere(
601
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
602
+            );
603
+
604
+        /**
605
+         * Reshares for this user are shares where they are the owner.
606
+         */
607
+        if ($reshares === false) {
608
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
609
+        } else {
610
+            $qb->andWhere(
611
+                $qb->expr()->orX(
612
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
613
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
614
+                )
615
+            );
616
+        }
617
+
618
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
619
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
620
+
621
+        $qb->orderBy('id');
622
+
623
+        $cursor = $qb->execute();
624
+        $shares = [];
625
+        while ($data = $cursor->fetch()) {
626
+            $shares[$data['fileid']][] = $this->createShareObject($data);
627
+        }
628
+        $cursor->closeCursor();
629
+
630
+        return $shares;
631
+    }
632
+
633
+    /**
634
+     * @inheritdoc
635
+     */
636
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
637
+        $qb = $this->dbConnection->getQueryBuilder();
638
+        $qb->select('*')
639
+            ->from('share');
640
+
641
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
642
+
643
+        /**
644
+         * Reshares for this user are shares where they are the owner.
645
+         */
646
+        if ($reshares === false) {
647
+            //Special case for old shares created via the web UI
648
+            $or1 = $qb->expr()->andX(
649
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
650
+                $qb->expr()->isNull('uid_initiator')
651
+            );
652
+
653
+            $qb->andWhere(
654
+                $qb->expr()->orX(
655
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
656
+                    $or1
657
+                )
658
+            );
659
+        } else {
660
+            $qb->andWhere(
661
+                $qb->expr()->orX(
662
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
663
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
664
+                )
665
+            );
666
+        }
667
+
668
+        if ($node !== null) {
669
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
670
+        }
671
+
672
+        if ($limit !== -1) {
673
+            $qb->setMaxResults($limit);
674
+        }
675
+
676
+        $qb->setFirstResult($offset);
677
+        $qb->orderBy('id');
678
+
679
+        $cursor = $qb->execute();
680
+        $shares = [];
681
+        while($data = $cursor->fetch()) {
682
+            $shares[] = $this->createShareObject($data);
683
+        }
684
+        $cursor->closeCursor();
685
+
686
+        return $shares;
687
+    }
688
+
689
+    /**
690
+     * @inheritdoc
691
+     */
692
+    public function getShareById($id, $recipientId = null) {
693
+        $qb = $this->dbConnection->getQueryBuilder();
694
+
695
+        $qb->select('*')
696
+            ->from('share')
697
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
698
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
699
+
700
+        $cursor = $qb->execute();
701
+        $data = $cursor->fetch();
702
+        $cursor->closeCursor();
703
+
704
+        if ($data === false) {
705
+            throw new ShareNotFound();
706
+        }
707
+
708
+        try {
709
+            $share = $this->createShareObject($data);
710
+        } catch (InvalidShare $e) {
711
+            throw new ShareNotFound();
712
+        }
713
+
714
+        return $share;
715
+    }
716
+
717
+    /**
718
+     * Get shares for a given path
719
+     *
720
+     * @param \OCP\Files\Node $path
721
+     * @return IShare[]
722
+     */
723
+    public function getSharesByPath(Node $path) {
724
+        $qb = $this->dbConnection->getQueryBuilder();
725
+
726
+        $cursor = $qb->select('*')
727
+            ->from('share')
728
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
729
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
730
+            ->execute();
731
+
732
+        $shares = [];
733
+        while($data = $cursor->fetch()) {
734
+            $shares[] = $this->createShareObject($data);
735
+        }
736
+        $cursor->closeCursor();
737
+
738
+        return $shares;
739
+    }
740
+
741
+    /**
742
+     * @inheritdoc
743
+     */
744
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
745
+        /** @var IShare[] $shares */
746
+        $shares = [];
747
+
748
+        //Get shares directly with this user
749
+        $qb = $this->dbConnection->getQueryBuilder();
750
+        $qb->select('*')
751
+            ->from('share');
752
+
753
+        // Order by id
754
+        $qb->orderBy('id');
755
+
756
+        // Set limit and offset
757
+        if ($limit !== -1) {
758
+            $qb->setMaxResults($limit);
759
+        }
760
+        $qb->setFirstResult($offset);
761
+
762
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
763
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
764
+
765
+        // Filter by node if provided
766
+        if ($node !== null) {
767
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
768
+        }
769
+
770
+        $cursor = $qb->execute();
771
+
772
+        while($data = $cursor->fetch()) {
773
+            $shares[] = $this->createShareObject($data);
774
+        }
775
+        $cursor->closeCursor();
776
+
777
+
778
+        return $shares;
779
+    }
780
+
781
+    /**
782
+     * Get a share by token
783
+     *
784
+     * @param string $token
785
+     * @return IShare
786
+     * @throws ShareNotFound
787
+     */
788
+    public function getShareByToken($token) {
789
+        $qb = $this->dbConnection->getQueryBuilder();
790
+
791
+        $cursor = $qb->select('*')
792
+            ->from('share')
793
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
794
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
795
+            ->execute();
796
+
797
+        $data = $cursor->fetch();
798
+
799
+        if ($data === false) {
800
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
801
+        }
802
+
803
+        try {
804
+            $share = $this->createShareObject($data);
805
+        } catch (InvalidShare $e) {
806
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
807
+        }
808
+
809
+        return $share;
810
+    }
811
+
812
+    /**
813
+     * get database row of a give share
814
+     *
815
+     * @param $id
816
+     * @return array
817
+     * @throws ShareNotFound
818
+     */
819
+    private function getRawShare($id) {
820
+
821
+        // Now fetch the inserted share and create a complete share object
822
+        $qb = $this->dbConnection->getQueryBuilder();
823
+        $qb->select('*')
824
+            ->from('share')
825
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
826
+
827
+        $cursor = $qb->execute();
828
+        $data = $cursor->fetch();
829
+        $cursor->closeCursor();
830
+
831
+        if ($data === false) {
832
+            throw new ShareNotFound;
833
+        }
834
+
835
+        return $data;
836
+    }
837
+
838
+    /**
839
+     * Create a share object from an database row
840
+     *
841
+     * @param array $data
842
+     * @return IShare
843
+     * @throws InvalidShare
844
+     * @throws ShareNotFound
845
+     */
846
+    private function createShareObject($data) {
847
+
848
+        $share = new Share($this->rootFolder, $this->userManager);
849
+        $share->setId((int)$data['id'])
850
+            ->setShareType((int)$data['share_type'])
851
+            ->setPermissions((int)$data['permissions'])
852
+            ->setTarget($data['file_target'])
853
+            ->setMailSend((bool)$data['mail_send'])
854
+            ->setToken($data['token']);
855
+
856
+        $shareTime = new \DateTime();
857
+        $shareTime->setTimestamp((int)$data['stime']);
858
+        $share->setShareTime($shareTime);
859
+        $share->setSharedWith($data['share_with']);
860
+
861
+        if ($data['uid_initiator'] !== null) {
862
+            $share->setShareOwner($data['uid_owner']);
863
+            $share->setSharedBy($data['uid_initiator']);
864
+        } else {
865
+            //OLD SHARE
866
+            $share->setSharedBy($data['uid_owner']);
867
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
868
+
869
+            $owner = $path->getOwner();
870
+            $share->setShareOwner($owner->getUID());
871
+        }
872
+
873
+        $share->setNodeId((int)$data['file_source']);
874
+        $share->setNodeType($data['item_type']);
875
+
876
+        $share->setProviderId($this->identifier());
877
+
878
+        return $share;
879
+    }
880
+
881
+    /**
882
+     * Get the node with file $id for $user
883
+     *
884
+     * @param string $userId
885
+     * @param int $id
886
+     * @return \OCP\Files\File|\OCP\Files\Folder
887
+     * @throws InvalidShare
888
+     */
889
+    private function getNode($userId, $id) {
890
+        try {
891
+            $userFolder = $this->rootFolder->getUserFolder($userId);
892
+        } catch (NotFoundException $e) {
893
+            throw new InvalidShare();
894
+        }
895
+
896
+        $nodes = $userFolder->getById($id);
897
+
898
+        if (empty($nodes)) {
899
+            throw new InvalidShare();
900
+        }
901
+
902
+        return $nodes[0];
903
+    }
904
+
905
+    /**
906
+     * A user is deleted from the system
907
+     * So clean up the relevant shares.
908
+     *
909
+     * @param string $uid
910
+     * @param int $shareType
911
+     */
912
+    public function userDeleted($uid, $shareType) {
913
+        //TODO: probabaly a good idea to send unshare info to remote servers
914
+
915
+        $qb = $this->dbConnection->getQueryBuilder();
916
+
917
+        $qb->delete('share')
918
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
919
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
920
+            ->execute();
921
+    }
922
+
923
+    /**
924
+     * This provider does not handle groups
925
+     *
926
+     * @param string $gid
927
+     */
928
+    public function groupDeleted($gid) {
929
+        // We don't handle groups here
930
+        return;
931
+    }
932
+
933
+    /**
934
+     * This provider does not handle groups
935
+     *
936
+     * @param string $uid
937
+     * @param string $gid
938
+     */
939
+    public function userDeletedFromGroup($uid, $gid) {
940
+        // We don't handle groups here
941
+        return;
942
+    }
943
+
944
+    /**
945
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
946
+     *
947
+     * @return bool
948
+     */
949
+    public function isOutgoingServer2serverShareEnabled() {
950
+        if ($this->gsConfig->onlyInternalFederation()) {
951
+            return false;
952
+        }
953
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
954
+        return ($result === 'yes');
955
+    }
956
+
957
+    /**
958
+     * check if users are allowed to mount public links from other Nextclouds
959
+     *
960
+     * @return bool
961
+     */
962
+    public function isIncomingServer2serverShareEnabled() {
963
+        if ($this->gsConfig->onlyInternalFederation()) {
964
+            return false;
965
+        }
966
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
967
+        return ($result === 'yes');
968
+    }
969
+
970
+    /**
971
+     * Check if querying sharees on the lookup server is enabled
972
+     *
973
+     * @return bool
974
+     */
975
+    public function isLookupServerQueriesEnabled() {
976
+        // in a global scale setup we should always query the lookup server
977
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
978
+            return true;
979
+        }
980
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
981
+        return ($result === 'yes');
982
+    }
983
+
984
+
985
+    /**
986
+     * Check if it is allowed to publish user specific data to the lookup server
987
+     *
988
+     * @return bool
989
+     */
990
+    public function isLookupServerUploadEnabled() {
991
+        // in a global scale setup the admin is responsible to keep the lookup server up-to-date
992
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
993
+            return false;
994
+        }
995
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
996
+        return ($result === 'yes');
997
+    }
998
+
999
+    /**
1000
+     * @inheritdoc
1001
+     */
1002
+    public function getAccessList($nodes, $currentAccess) {
1003
+        $ids = [];
1004
+        foreach ($nodes as $node) {
1005
+            $ids[] = $node->getId();
1006
+        }
1007
+
1008
+        $qb = $this->dbConnection->getQueryBuilder();
1009
+        $qb->select('share_with', 'token', 'file_source')
1010
+            ->from('share')
1011
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1012
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1013
+            ->andWhere($qb->expr()->orX(
1014
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1015
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1016
+            ));
1017
+        $cursor = $qb->execute();
1018
+
1019
+        if ($currentAccess === false) {
1020
+            $remote = $cursor->fetch() !== false;
1021
+            $cursor->closeCursor();
1022
+
1023
+            return ['remote' => $remote];
1024
+        }
1025
+
1026
+        $remote = [];
1027
+        while ($row = $cursor->fetch()) {
1028
+            $remote[$row['share_with']] = [
1029
+                'node_id' => $row['file_source'],
1030
+                'token' => $row['token'],
1031
+            ];
1032
+        }
1033
+        $cursor->closeCursor();
1034
+
1035
+        return ['remote' => $remote];
1036
+    }
1037 1037
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/templates/settings-admin.php 1 patch
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -4,12 +4,12 @@  discard block
 block discarded – undo
4 4
 script('federatedfilesharing', 'settings-admin');
5 5
 ?>
6 6
 
7
-<?php if($_['internalOnly'] === false): ?>
7
+<?php if ($_['internalOnly'] === false): ?>
8 8
 
9 9
 <div id="fileSharingSettings" class="followupsection">
10
-	<h3><?php p($l->t('Federated Cloud Sharing'));?></h3>
10
+	<h3><?php p($l->t('Federated Cloud Sharing')); ?></h3>
11 11
 	<a target="_blank" rel="noreferrer" class="icon-info svg"
12
-		title="<?php p($l->t('Open documentation'));?>"
12
+		title="<?php p($l->t('Open documentation')); ?>"
13 13
 		href="<?php p(link_to_docs('admin-sharing-federated')); ?>"></a>
14 14
 	<p class="settings-hint"><?php p($l->t('Adjust how people can share between servers.')); ?></p>
15 15
 
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 		<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled" class="checkbox"
18 18
 			   value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
19 19
 		<label for="outgoingServer2serverShareEnabled">
20
-			<?php p($l->t('Allow users on this server to send shares to other servers'));?>
20
+			<?php p($l->t('Allow users on this server to send shares to other servers')); ?>
21 21
 		</label>
22 22
 	</p>
23 23
 
@@ -25,21 +25,21 @@  discard block
 block discarded – undo
25 25
 		<input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled" class="checkbox"
26 26
 			   value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
27 27
 		<label for="incomingServer2serverShareEnabled">
28
-			<?php p($l->t('Allow users on this server to receive shares from other servers'));?>
28
+			<?php p($l->t('Allow users on this server to receive shares from other servers')); ?>
29 29
 		</label><br/>
30 30
 	</p>
31 31
 	<p>
32 32
 		<input type="checkbox" name="lookupServerEnabled" id="lookupServerEnabled" class="checkbox"
33 33
 			   value="1" <?php if ($_['lookupServerEnabled']) print_unescaped('checked="checked"'); ?> />
34 34
 		<label for="lookupServerEnabled">
35
-			<?php p($l->t('Search global and public address book for users and let local users publish their data'));?>
35
+			<?php p($l->t('Search global and public address book for users and let local users publish their data')); ?>
36 36
 		</label><br/>
37 37
 	</p>
38 38
 	<p>
39 39
 		<input type="checkbox" name="lookupServerUploadEnabled" id="lookupServerUploadEnabled" class="checkbox"
40 40
 			   value="1" <?php if ($_['lookupServerUploadEnabled']) print_unescaped('checked="checked"'); ?> />
41 41
 		<label for="lookupServerUploadEnabled">
42
-			<?php p($l->t('Allow users to publish their data to a global and public address book'));?>
42
+			<?php p($l->t('Allow users to publish their data to a global and public address book')); ?>
43 43
 		</label><br/>
44 44
 	</p>
45 45
 
Please login to merge, or discard this patch.
settings/personal.php 1 patch
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -41,9 +41,9 @@  discard block
 block discarded – undo
41 41
 $defaults = \OC::$server->getThemingDefaults();
42 42
 $certificateManager = \OC::$server->getCertificateManager();
43 43
 $accountManager = new \OC\Accounts\AccountManager(
44
-	\OC::$server->getDatabaseConnection(),
45
-	\OC::$server->getEventDispatcher(),
46
-	\OC::$server->getJobList()
44
+    \OC::$server->getDatabaseConnection(),
45
+    \OC::$server->getEventDispatcher(),
46
+    \OC::$server->getJobList()
47 47
 );
48 48
 $config = \OC::$server->getConfig();
49 49
 $urlGenerator = \OC::$server->getURLGenerator();
@@ -78,72 +78,72 @@  discard block
 block discarded – undo
78 78
 
79 79
 // array of common languages
80 80
 $commonLangCodes = array(
81
-	'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
81
+    'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
82 82
 );
83 83
 
84 84
 $languages=array();
85 85
 $commonLanguages = array();
86 86
 foreach($languageCodes as $lang) {
87
-	$l = \OC::$server->getL10N('settings', $lang);
88
-	// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
89
-	$potentialName = (string) $l->t('__language_name__');
90
-	if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
91
-		$ln = array('code' => $lang, 'name' => $potentialName);
92
-	} elseif ($lang === 'en') {
93
-		$ln = ['code' => $lang, 'name' => 'English (US)'];
94
-	}else{//fallback to language code
95
-		$ln=array('code'=>$lang, 'name'=>$lang);
96
-	}
97
-
98
-	// put appropriate languages into appropriate arrays, to print them sorted
99
-	// used language -> common languages -> divider -> other languages
100
-	if ($lang === $userLang) {
101
-		$userLang = $ln;
102
-	} elseif (in_array($lang, $commonLangCodes)) {
103
-		$commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
104
-	} else {
105
-		$languages[]=$ln;
106
-	}
87
+    $l = \OC::$server->getL10N('settings', $lang);
88
+    // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
89
+    $potentialName = (string) $l->t('__language_name__');
90
+    if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
91
+        $ln = array('code' => $lang, 'name' => $potentialName);
92
+    } elseif ($lang === 'en') {
93
+        $ln = ['code' => $lang, 'name' => 'English (US)'];
94
+    }else{//fallback to language code
95
+        $ln=array('code'=>$lang, 'name'=>$lang);
96
+    }
97
+
98
+    // put appropriate languages into appropriate arrays, to print them sorted
99
+    // used language -> common languages -> divider -> other languages
100
+    if ($lang === $userLang) {
101
+        $userLang = $ln;
102
+    } elseif (in_array($lang, $commonLangCodes)) {
103
+        $commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
104
+    } else {
105
+        $languages[]=$ln;
106
+    }
107 107
 }
108 108
 
109 109
 // if user language is not available but set somehow: show the actual code as name
110 110
 if (!is_array($userLang)) {
111
-	$userLang = [
112
-		'code' => $userLang,
113
-		'name' => $userLang,
114
-	];
111
+    $userLang = [
112
+        'code' => $userLang,
113
+        'name' => $userLang,
114
+    ];
115 115
 }
116 116
 
117 117
 ksort($commonLanguages);
118 118
 
119 119
 // sort now by displayed language not the iso-code
120 120
 usort( $languages, function ($a, $b) {
121
-	if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
122
-		// If a doesn't have a name, but b does, list b before a
123
-		return 1;
124
-	}
125
-	if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
126
-		// If a does have a name, but b doesn't, list a before b
127
-		return -1;
128
-	}
129
-	// Otherwise compare the names
130
-	return strcmp($a['name'], $b['name']);
121
+    if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
122
+        // If a doesn't have a name, but b does, list b before a
123
+        return 1;
124
+    }
125
+    if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
126
+        // If a does have a name, but b doesn't, list a before b
127
+        return -1;
128
+    }
129
+    // Otherwise compare the names
130
+    return strcmp($a['name'], $b['name']);
131 131
 });
132 132
 
133 133
 //links to clients
134 134
 $clients = array(
135
-	'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
136
-	'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
137
-	'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
135
+    'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
136
+    'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
137
+    'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
138 138
 );
139 139
 
140 140
 // only show root certificate import if external storages are enabled
141 141
 $enableCertImport = false;
142 142
 $externalStorageEnabled = \OC::$server->getAppManager()->isEnabledForUser('files_external');
143 143
 if ($externalStorageEnabled) {
144
-	/** @var \OCA\Files_External\Service\BackendService $backendService */
145
-	$backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
146
-	$enableCertImport = $backendService->isUserMountingAllowed();
144
+    /** @var \OCA\Files_External\Service\BackendService $backendService */
145
+    $backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
146
+    $enableCertImport = $backendService->isUserMountingAllowed();
147 147
 }
148 148
 
149 149
 
@@ -152,9 +152,9 @@  discard block
 block discarded – undo
152 152
 $tmpl = new OC_Template( 'settings', 'personal', 'user');
153 153
 $tmpl->assign('usage', OC_Helper::humanFileSize($storageInfo['used']));
154 154
 if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
155
-	$totalSpace = $l->t('Unlimited');
155
+    $totalSpace = $l->t('Unlimited');
156 156
 } else {
157
-	$totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
157
+    $totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
158 158
 }
159 159
 
160 160
 $uid = $user->getUID();
@@ -193,18 +193,18 @@  discard block
 block discarded – undo
193 193
 
194 194
 foreach ($needVerifyMessage as $property) {
195 195
 
196
-	switch ($userData[$property]['verified']) {
197
-		case \OC\Accounts\AccountManager::VERIFIED:
198
-			$message = $l->t('Verifying');
199
-			break;
200
-		case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
201
-			$message = $l->t('Verifying …');
202
-			break;
203
-		default:
204
-			$message = $l->t('Verify');
205
-	}
206
-
207
-	$tmpl->assign($property . 'Message', $message);
196
+    switch ($userData[$property]['verified']) {
197
+        case \OC\Accounts\AccountManager::VERIFIED:
198
+            $message = $l->t('Verifying');
199
+            break;
200
+        case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
201
+            $message = $l->t('Verifying …');
202
+            break;
203
+        default:
204
+            $message = $l->t('Verify');
205
+    }
206
+
207
+    $tmpl->assign($property . 'Message', $message);
208 208
 }
209 209
 
210 210
 $tmpl->assign('avatarChangeSupported', OC_User::canUserChangeAvatar(OC_User::getUser()));
@@ -215,9 +215,9 @@  discard block
 block discarded – undo
215 215
 $federatedFileSharingEnabled = \OC::$server->getAppManager()->isEnabledForUser('federatedfilesharing');
216 216
 $lookupServerUploadEnabled = false;
217 217
 if ($federatedFileSharingEnabled) {
218
-	$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
219
-	$shareProvider = $federatedFileSharing->getFederatedShareProvider();
220
-	$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
218
+    $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
219
+    $shareProvider = $federatedFileSharing->getFederatedShareProvider();
220
+    $lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
221 221
 }
222 222
 
223 223
 $tmpl->assign('lookupServerUploadEnabled', $lookupServerUploadEnabled);
@@ -240,35 +240,35 @@  discard block
 block discarded – undo
240 240
 
241 241
 // add bottom hardcoded forms from the template
242 242
 if ($enableCertImport) {
243
-	$certificatesTemplate = new OC_Template('settings', 'certificates');
244
-	$certificatesTemplate->assign('type', 'personal');
245
-	$certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
246
-	$certificatesTemplate->assign('certs', $certificateManager->listCertificates());
247
-	$certificatesTemplate->assign('urlGenerator', $urlGenerator);
248
-	$forms[] = $certificatesTemplate->fetchPage();
243
+    $certificatesTemplate = new OC_Template('settings', 'certificates');
244
+    $certificatesTemplate->assign('type', 'personal');
245
+    $certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
246
+    $certificatesTemplate->assign('certs', $certificateManager->listCertificates());
247
+    $certificatesTemplate->assign('urlGenerator', $urlGenerator);
248
+    $forms[] = $certificatesTemplate->fetchPage();
249 249
 }
250 250
 
251 251
 $formsMap = array_map(function($form){
252
-	if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
253
-		$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
254
-		$sectionName = str_replace('</h2>', '', $sectionName);
255
-		if (strpos($regs['class'], 'data-anchor-name') !== false) {
256
-			preg_match('%.*data-anchor-name="(?P<anchor>[^"]*)"%i', $regs['class'], $matches);
257
-			$anchor = $matches['anchor'];
258
-		} else {
259
-			$anchor = strtolower($sectionName);
260
-			$anchor = str_replace(' ', '-', $anchor);
261
-		}
262
-
263
-		return array(
264
-			'anchor' => $anchor,
265
-			'section-name' => $sectionName,
266
-			'form' => $form
267
-		);
268
-	}
269
-	return array(
270
-		'form' => $form
271
-	);
252
+    if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
253
+        $sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
254
+        $sectionName = str_replace('</h2>', '', $sectionName);
255
+        if (strpos($regs['class'], 'data-anchor-name') !== false) {
256
+            preg_match('%.*data-anchor-name="(?P<anchor>[^"]*)"%i', $regs['class'], $matches);
257
+            $anchor = $matches['anchor'];
258
+        } else {
259
+            $anchor = strtolower($sectionName);
260
+            $anchor = str_replace(' ', '-', $anchor);
261
+        }
262
+
263
+        return array(
264
+            'anchor' => $anchor,
265
+            'section-name' => $sectionName,
266
+            'form' => $form
267
+        );
268
+    }
269
+    return array(
270
+        'form' => $form
271
+    );
272 272
 }, $forms);
273 273
 
274 274
 $formsAndMore = array_merge($formsAndMore, $formsMap);
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Settings/Admin.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -30,55 +30,55 @@
 block discarded – undo
30 30
 
31 31
 class Admin implements ISettings {
32 32
 
33
-	/** @var FederatedShareProvider */
34
-	private $fedShareProvider;
33
+    /** @var FederatedShareProvider */
34
+    private $fedShareProvider;
35 35
 
36
-	/** @var IConfig */
37
-	private $gsConfig;
36
+    /** @var IConfig */
37
+    private $gsConfig;
38 38
 
39
-	/**
40
-	 * Admin constructor.
41
-	 *
42
-	 * @param FederatedShareProvider $fedShareProvider
43
-	 * @param IConfig $globalScaleConfig
44
-	 */
45
-	public function __construct(FederatedShareProvider $fedShareProvider, IConfig $globalScaleConfig) {
46
-		$this->fedShareProvider = $fedShareProvider;
47
-		$this->gsConfig = $globalScaleConfig;
48
-	}
39
+    /**
40
+     * Admin constructor.
41
+     *
42
+     * @param FederatedShareProvider $fedShareProvider
43
+     * @param IConfig $globalScaleConfig
44
+     */
45
+    public function __construct(FederatedShareProvider $fedShareProvider, IConfig $globalScaleConfig) {
46
+        $this->fedShareProvider = $fedShareProvider;
47
+        $this->gsConfig = $globalScaleConfig;
48
+    }
49 49
 
50
-	/**
51
-	 * @return TemplateResponse
52
-	 */
53
-	public function getForm() {
50
+    /**
51
+     * @return TemplateResponse
52
+     */
53
+    public function getForm() {
54 54
 
55
-		$parameters = [
56
-			'internalOnly' => $this->gsConfig->onlyInternalFederation(),
57
-			'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(),
58
-			'incomingServer2serverShareEnabled' => $this->fedShareProvider->isIncomingServer2serverShareEnabled(),
59
-			'lookupServerEnabled' => $this->fedShareProvider->isLookupServerQueriesEnabled(),
60
-			'lookupServerUploadEnabled' => $this->fedShareProvider->isLookupServerUploadEnabled(),
61
-		];
55
+        $parameters = [
56
+            'internalOnly' => $this->gsConfig->onlyInternalFederation(),
57
+            'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(),
58
+            'incomingServer2serverShareEnabled' => $this->fedShareProvider->isIncomingServer2serverShareEnabled(),
59
+            'lookupServerEnabled' => $this->fedShareProvider->isLookupServerQueriesEnabled(),
60
+            'lookupServerUploadEnabled' => $this->fedShareProvider->isLookupServerUploadEnabled(),
61
+        ];
62 62
 
63
-		return new TemplateResponse('federatedfilesharing', 'settings-admin', $parameters, '');
64
-	}
63
+        return new TemplateResponse('federatedfilesharing', 'settings-admin', $parameters, '');
64
+    }
65 65
 
66
-	/**
67
-	 * @return string the section ID, e.g. 'sharing'
68
-	 */
69
-	public function getSection() {
70
-		return 'sharing';
71
-	}
66
+    /**
67
+     * @return string the section ID, e.g. 'sharing'
68
+     */
69
+    public function getSection() {
70
+        return 'sharing';
71
+    }
72 72
 
73
-	/**
74
-	 * @return int whether the form should be rather on the top or bottom of
75
-	 * the admin section. The forms are arranged in ascending order of the
76
-	 * priority values. It is required to return a value between 0 and 100.
77
-	 *
78
-	 * E.g.: 70
79
-	 */
80
-	public function getPriority() {
81
-		return 20;
82
-	}
73
+    /**
74
+     * @return int whether the form should be rather on the top or bottom of
75
+     * the admin section. The forms are arranged in ascending order of the
76
+     * priority values. It is required to return a value between 0 and 100.
77
+     *
78
+     * E.g.: 70
79
+     */
80
+    public function getPriority() {
81
+        return 20;
82
+    }
83 83
 
84 84
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +376 added lines, -376 removed lines patch added patch discarded remove patch
@@ -63,380 +63,380 @@
 block discarded – undo
63 63
 
64 64
 class DIContainer extends SimpleContainer implements IAppContainer {
65 65
 
66
-	/**
67
-	 * @var array
68
-	 */
69
-	private $middleWares = array();
70
-
71
-	/** @var ServerContainer */
72
-	private $server;
73
-
74
-	/**
75
-	 * Put your class dependencies in here
76
-	 * @param string $appName the name of the app
77
-	 * @param array $urlParams
78
-	 * @param ServerContainer $server
79
-	 */
80
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
81
-		parent::__construct();
82
-		$this['AppName'] = $appName;
83
-		$this['urlParams'] = $urlParams;
84
-
85
-		/** @var \OC\ServerContainer $server */
86
-		if ($server === null) {
87
-			$server = \OC::$server;
88
-		}
89
-		$this->server = $server;
90
-		$this->server->registerAppContainer($appName, $this);
91
-
92
-		// aliases
93
-		$this->registerAlias('appName', 'AppName');
94
-		$this->registerAlias('webRoot', 'WebRoot');
95
-		$this->registerAlias('userId', 'UserId');
96
-
97
-		/**
98
-		 * Core services
99
-		 */
100
-		$this->registerService(IOutput::class, function($c){
101
-			return new Output($this->getServer()->getWebRoot());
102
-		});
103
-
104
-		$this->registerService(Folder::class, function() {
105
-			return $this->getServer()->getUserFolder();
106
-		});
107
-
108
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
109
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
110
-		});
111
-
112
-		$this->registerService(IL10N::class, function($c) {
113
-			return $this->getServer()->getL10N($c->query('AppName'));
114
-		});
115
-
116
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
117
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
118
-
119
-		$this->registerService(IRequest::class, function() {
120
-			return $this->getServer()->query(IRequest::class);
121
-		});
122
-		$this->registerAlias('Request', IRequest::class);
123
-
124
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
125
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
126
-
127
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
128
-
129
-		$this->registerService(IServerContainer::class, function ($c) {
130
-			return $this->getServer();
131
-		});
132
-		$this->registerAlias('ServerContainer', IServerContainer::class);
133
-
134
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
135
-			return $c->query('OCA\WorkflowEngine\Manager');
136
-		});
137
-
138
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
139
-			return $c;
140
-		});
141
-
142
-		// commonly used attributes
143
-		$this->registerService('UserId', function ($c) {
144
-			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
145
-		});
146
-
147
-		$this->registerService('WebRoot', function ($c) {
148
-			return $c->query('ServerContainer')->getWebRoot();
149
-		});
150
-
151
-		$this->registerService('fromMailAddress', function() {
152
-			return Util::getDefaultEmailAddress('no-reply');
153
-		});
154
-
155
-		$this->registerService('OC_Defaults', function ($c) {
156
-			return $c->getServer()->getThemingDefaults();
157
-		});
158
-
159
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
160
-			return $this->getServer()->getEncryptionManager();
161
-		});
162
-
163
-		$this->registerService(IConfig::class, function ($c) {
164
-			return $c->query(OC\GlobalScale\Config::class);
165
-		});
166
-
167
-		$this->registerService(IValidator::class, function($c) {
168
-			return $c->query(Validator::class);
169
-		});
170
-
171
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
-			return new \OC\Security\IdentityProof\Manager(
173
-				$this->getServer()->query(\OC\Files\AppData\Factory::class),
174
-				$this->getServer()->getCrypto()
175
-			);
176
-		});
177
-
178
-		/**
179
-		 * App Framework APIs
180
-		 */
181
-		$this->registerService('API', function($c){
182
-			$c->query('OCP\\ILogger')->debug(
183
-				'Accessing the API class is deprecated! Use the appropriate ' .
184
-				'services instead!'
185
-			);
186
-			return new API($c['AppName']);
187
-		});
188
-
189
-		$this->registerService('Protocol', function($c){
190
-			/** @var \OC\Server $server */
191
-			$server = $c->query('ServerContainer');
192
-			$protocol = $server->getRequest()->getHttpProtocol();
193
-			return new Http($_SERVER, $protocol);
194
-		});
195
-
196
-		$this->registerService('Dispatcher', function($c) {
197
-			return new Dispatcher(
198
-				$c['Protocol'],
199
-				$c['MiddlewareDispatcher'],
200
-				$c['ControllerMethodReflector'],
201
-				$c['Request']
202
-			);
203
-		});
204
-
205
-		/**
206
-		 * App Framework default arguments
207
-		 */
208
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
209
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
210
-		$this->registerParameter('corsMaxAge', 1728000);
211
-
212
-		/**
213
-		 * Middleware
214
-		 */
215
-		$app = $this;
216
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
217
-			/** @var \OC\Server $server */
218
-			$server = $app->getServer();
219
-
220
-			return new SecurityMiddleware(
221
-				$c['Request'],
222
-				$c['ControllerMethodReflector'],
223
-				$server->getNavigationManager(),
224
-				$server->getURLGenerator(),
225
-				$server->getLogger(),
226
-				$server->getSession(),
227
-				$c['AppName'],
228
-				$app->isLoggedIn(),
229
-				$app->isAdminUser(),
230
-				$server->getContentSecurityPolicyManager(),
231
-				$server->getCsrfTokenManager(),
232
-				$server->getContentSecurityPolicyNonceManager()
233
-			);
234
-
235
-		});
236
-
237
-		$this->registerService('BruteForceMiddleware', function($c) use ($app) {
238
-			/** @var \OC\Server $server */
239
-			$server = $app->getServer();
240
-
241
-			return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
242
-				$c['ControllerMethodReflector'],
243
-				$server->getBruteForceThrottler(),
244
-				$server->getRequest()
245
-			);
246
-		});
247
-
248
-		$this->registerService('RateLimitingMiddleware', function($c) use ($app) {
249
-			/** @var \OC\Server $server */
250
-			$server = $app->getServer();
251
-
252
-			return new RateLimitingMiddleware(
253
-				$server->getRequest(),
254
-				$server->getUserSession(),
255
-				$c['ControllerMethodReflector'],
256
-				$c->query(OC\Security\RateLimiting\Limiter::class)
257
-			);
258
-		});
259
-
260
-		$this->registerService('CORSMiddleware', function($c) {
261
-			return new CORSMiddleware(
262
-				$c['Request'],
263
-				$c['ControllerMethodReflector'],
264
-				$c->query(IUserSession::class),
265
-				$c->getServer()->getBruteForceThrottler()
266
-			);
267
-		});
268
-
269
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
270
-			return new SessionMiddleware(
271
-				$c['Request'],
272
-				$c['ControllerMethodReflector'],
273
-				$app->getServer()->getSession()
274
-			);
275
-		});
276
-
277
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
278
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
279
-			$userSession = $app->getServer()->getUserSession();
280
-			$session = $app->getServer()->getSession();
281
-			$urlGenerator = $app->getServer()->getURLGenerator();
282
-			$reflector = $c['ControllerMethodReflector'];
283
-			$request = $app->getServer()->getRequest();
284
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
285
-		});
286
-
287
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
288
-			return new OCSMiddleware(
289
-				$c['Request']
290
-			);
291
-		});
292
-
293
-		$middleWares = &$this->middleWares;
294
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
295
-			$dispatcher = new MiddlewareDispatcher();
296
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
297
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
298
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
299
-			$dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
300
-			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
301
-			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
302
-
303
-			foreach($middleWares as $middleWare) {
304
-				$dispatcher->registerMiddleware($c[$middleWare]);
305
-			}
306
-
307
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
308
-			return $dispatcher;
309
-		});
310
-
311
-	}
312
-
313
-
314
-	/**
315
-	 * @deprecated implements only deprecated methods
316
-	 * @return IApi
317
-	 */
318
-	function getCoreApi()
319
-	{
320
-		return $this->query('API');
321
-	}
322
-
323
-	/**
324
-	 * @return \OCP\IServerContainer
325
-	 */
326
-	function getServer()
327
-	{
328
-		return $this->server;
329
-	}
330
-
331
-	/**
332
-	 * @param string $middleWare
333
-	 * @return boolean|null
334
-	 */
335
-	function registerMiddleWare($middleWare) {
336
-		array_push($this->middleWares, $middleWare);
337
-	}
338
-
339
-	/**
340
-	 * used to return the appname of the set application
341
-	 * @return string the name of your application
342
-	 */
343
-	function getAppName() {
344
-		return $this->query('AppName');
345
-	}
346
-
347
-	/**
348
-	 * @deprecated use IUserSession->isLoggedIn()
349
-	 * @return boolean
350
-	 */
351
-	function isLoggedIn() {
352
-		return \OC::$server->getUserSession()->isLoggedIn();
353
-	}
354
-
355
-	/**
356
-	 * @deprecated use IGroupManager->isAdmin($userId)
357
-	 * @return boolean
358
-	 */
359
-	function isAdminUser() {
360
-		$uid = $this->getUserId();
361
-		return \OC_User::isAdminUser($uid);
362
-	}
363
-
364
-	private function getUserId() {
365
-		return $this->getServer()->getSession()->get('user_id');
366
-	}
367
-
368
-	/**
369
-	 * @deprecated use the ILogger instead
370
-	 * @param string $message
371
-	 * @param string $level
372
-	 * @return mixed
373
-	 */
374
-	function log($message, $level) {
375
-		switch($level){
376
-			case 'debug':
377
-				$level = \OCP\Util::DEBUG;
378
-				break;
379
-			case 'info':
380
-				$level = \OCP\Util::INFO;
381
-				break;
382
-			case 'warn':
383
-				$level = \OCP\Util::WARN;
384
-				break;
385
-			case 'fatal':
386
-				$level = \OCP\Util::FATAL;
387
-				break;
388
-			default:
389
-				$level = \OCP\Util::ERROR;
390
-				break;
391
-		}
392
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
393
-	}
394
-
395
-	/**
396
-	 * Register a capability
397
-	 *
398
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
399
-	 */
400
-	public function registerCapability($serviceName) {
401
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
402
-			return $this->query($serviceName);
403
-		});
404
-	}
405
-
406
-	/**
407
-	 * @param string $name
408
-	 * @return mixed
409
-	 * @throws QueryException if the query could not be resolved
410
-	 */
411
-	public function query($name) {
412
-		try {
413
-			return $this->queryNoFallback($name);
414
-		} catch (QueryException $e) {
415
-			return $this->getServer()->query($name);
416
-		}
417
-	}
418
-
419
-	/**
420
-	 * @param string $name
421
-	 * @return mixed
422
-	 * @throws QueryException if the query could not be resolved
423
-	 */
424
-	public function queryNoFallback($name) {
425
-		$name = $this->sanitizeName($name);
426
-
427
-		if ($this->offsetExists($name)) {
428
-			return parent::query($name);
429
-		} else {
430
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
431
-				return parent::query($name);
432
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
433
-				return parent::query($name);
434
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
435
-				return parent::query($name);
436
-			}
437
-		}
438
-
439
-		throw new QueryException('Could not resolve ' . $name . '!' .
440
-			' Class can not be instantiated');
441
-	}
66
+    /**
67
+     * @var array
68
+     */
69
+    private $middleWares = array();
70
+
71
+    /** @var ServerContainer */
72
+    private $server;
73
+
74
+    /**
75
+     * Put your class dependencies in here
76
+     * @param string $appName the name of the app
77
+     * @param array $urlParams
78
+     * @param ServerContainer $server
79
+     */
80
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
81
+        parent::__construct();
82
+        $this['AppName'] = $appName;
83
+        $this['urlParams'] = $urlParams;
84
+
85
+        /** @var \OC\ServerContainer $server */
86
+        if ($server === null) {
87
+            $server = \OC::$server;
88
+        }
89
+        $this->server = $server;
90
+        $this->server->registerAppContainer($appName, $this);
91
+
92
+        // aliases
93
+        $this->registerAlias('appName', 'AppName');
94
+        $this->registerAlias('webRoot', 'WebRoot');
95
+        $this->registerAlias('userId', 'UserId');
96
+
97
+        /**
98
+         * Core services
99
+         */
100
+        $this->registerService(IOutput::class, function($c){
101
+            return new Output($this->getServer()->getWebRoot());
102
+        });
103
+
104
+        $this->registerService(Folder::class, function() {
105
+            return $this->getServer()->getUserFolder();
106
+        });
107
+
108
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
109
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
110
+        });
111
+
112
+        $this->registerService(IL10N::class, function($c) {
113
+            return $this->getServer()->getL10N($c->query('AppName'));
114
+        });
115
+
116
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
117
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
118
+
119
+        $this->registerService(IRequest::class, function() {
120
+            return $this->getServer()->query(IRequest::class);
121
+        });
122
+        $this->registerAlias('Request', IRequest::class);
123
+
124
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
125
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
126
+
127
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
128
+
129
+        $this->registerService(IServerContainer::class, function ($c) {
130
+            return $this->getServer();
131
+        });
132
+        $this->registerAlias('ServerContainer', IServerContainer::class);
133
+
134
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
135
+            return $c->query('OCA\WorkflowEngine\Manager');
136
+        });
137
+
138
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
139
+            return $c;
140
+        });
141
+
142
+        // commonly used attributes
143
+        $this->registerService('UserId', function ($c) {
144
+            return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
145
+        });
146
+
147
+        $this->registerService('WebRoot', function ($c) {
148
+            return $c->query('ServerContainer')->getWebRoot();
149
+        });
150
+
151
+        $this->registerService('fromMailAddress', function() {
152
+            return Util::getDefaultEmailAddress('no-reply');
153
+        });
154
+
155
+        $this->registerService('OC_Defaults', function ($c) {
156
+            return $c->getServer()->getThemingDefaults();
157
+        });
158
+
159
+        $this->registerService('OCP\Encryption\IManager', function ($c) {
160
+            return $this->getServer()->getEncryptionManager();
161
+        });
162
+
163
+        $this->registerService(IConfig::class, function ($c) {
164
+            return $c->query(OC\GlobalScale\Config::class);
165
+        });
166
+
167
+        $this->registerService(IValidator::class, function($c) {
168
+            return $c->query(Validator::class);
169
+        });
170
+
171
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
172
+            return new \OC\Security\IdentityProof\Manager(
173
+                $this->getServer()->query(\OC\Files\AppData\Factory::class),
174
+                $this->getServer()->getCrypto()
175
+            );
176
+        });
177
+
178
+        /**
179
+         * App Framework APIs
180
+         */
181
+        $this->registerService('API', function($c){
182
+            $c->query('OCP\\ILogger')->debug(
183
+                'Accessing the API class is deprecated! Use the appropriate ' .
184
+                'services instead!'
185
+            );
186
+            return new API($c['AppName']);
187
+        });
188
+
189
+        $this->registerService('Protocol', function($c){
190
+            /** @var \OC\Server $server */
191
+            $server = $c->query('ServerContainer');
192
+            $protocol = $server->getRequest()->getHttpProtocol();
193
+            return new Http($_SERVER, $protocol);
194
+        });
195
+
196
+        $this->registerService('Dispatcher', function($c) {
197
+            return new Dispatcher(
198
+                $c['Protocol'],
199
+                $c['MiddlewareDispatcher'],
200
+                $c['ControllerMethodReflector'],
201
+                $c['Request']
202
+            );
203
+        });
204
+
205
+        /**
206
+         * App Framework default arguments
207
+         */
208
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
209
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
210
+        $this->registerParameter('corsMaxAge', 1728000);
211
+
212
+        /**
213
+         * Middleware
214
+         */
215
+        $app = $this;
216
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
217
+            /** @var \OC\Server $server */
218
+            $server = $app->getServer();
219
+
220
+            return new SecurityMiddleware(
221
+                $c['Request'],
222
+                $c['ControllerMethodReflector'],
223
+                $server->getNavigationManager(),
224
+                $server->getURLGenerator(),
225
+                $server->getLogger(),
226
+                $server->getSession(),
227
+                $c['AppName'],
228
+                $app->isLoggedIn(),
229
+                $app->isAdminUser(),
230
+                $server->getContentSecurityPolicyManager(),
231
+                $server->getCsrfTokenManager(),
232
+                $server->getContentSecurityPolicyNonceManager()
233
+            );
234
+
235
+        });
236
+
237
+        $this->registerService('BruteForceMiddleware', function($c) use ($app) {
238
+            /** @var \OC\Server $server */
239
+            $server = $app->getServer();
240
+
241
+            return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
242
+                $c['ControllerMethodReflector'],
243
+                $server->getBruteForceThrottler(),
244
+                $server->getRequest()
245
+            );
246
+        });
247
+
248
+        $this->registerService('RateLimitingMiddleware', function($c) use ($app) {
249
+            /** @var \OC\Server $server */
250
+            $server = $app->getServer();
251
+
252
+            return new RateLimitingMiddleware(
253
+                $server->getRequest(),
254
+                $server->getUserSession(),
255
+                $c['ControllerMethodReflector'],
256
+                $c->query(OC\Security\RateLimiting\Limiter::class)
257
+            );
258
+        });
259
+
260
+        $this->registerService('CORSMiddleware', function($c) {
261
+            return new CORSMiddleware(
262
+                $c['Request'],
263
+                $c['ControllerMethodReflector'],
264
+                $c->query(IUserSession::class),
265
+                $c->getServer()->getBruteForceThrottler()
266
+            );
267
+        });
268
+
269
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
270
+            return new SessionMiddleware(
271
+                $c['Request'],
272
+                $c['ControllerMethodReflector'],
273
+                $app->getServer()->getSession()
274
+            );
275
+        });
276
+
277
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
278
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
279
+            $userSession = $app->getServer()->getUserSession();
280
+            $session = $app->getServer()->getSession();
281
+            $urlGenerator = $app->getServer()->getURLGenerator();
282
+            $reflector = $c['ControllerMethodReflector'];
283
+            $request = $app->getServer()->getRequest();
284
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
285
+        });
286
+
287
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
288
+            return new OCSMiddleware(
289
+                $c['Request']
290
+            );
291
+        });
292
+
293
+        $middleWares = &$this->middleWares;
294
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
295
+            $dispatcher = new MiddlewareDispatcher();
296
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
297
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
298
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
299
+            $dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
300
+            $dispatcher->registerMiddleware($c['BruteForceMiddleware']);
301
+            $dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
302
+
303
+            foreach($middleWares as $middleWare) {
304
+                $dispatcher->registerMiddleware($c[$middleWare]);
305
+            }
306
+
307
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
308
+            return $dispatcher;
309
+        });
310
+
311
+    }
312
+
313
+
314
+    /**
315
+     * @deprecated implements only deprecated methods
316
+     * @return IApi
317
+     */
318
+    function getCoreApi()
319
+    {
320
+        return $this->query('API');
321
+    }
322
+
323
+    /**
324
+     * @return \OCP\IServerContainer
325
+     */
326
+    function getServer()
327
+    {
328
+        return $this->server;
329
+    }
330
+
331
+    /**
332
+     * @param string $middleWare
333
+     * @return boolean|null
334
+     */
335
+    function registerMiddleWare($middleWare) {
336
+        array_push($this->middleWares, $middleWare);
337
+    }
338
+
339
+    /**
340
+     * used to return the appname of the set application
341
+     * @return string the name of your application
342
+     */
343
+    function getAppName() {
344
+        return $this->query('AppName');
345
+    }
346
+
347
+    /**
348
+     * @deprecated use IUserSession->isLoggedIn()
349
+     * @return boolean
350
+     */
351
+    function isLoggedIn() {
352
+        return \OC::$server->getUserSession()->isLoggedIn();
353
+    }
354
+
355
+    /**
356
+     * @deprecated use IGroupManager->isAdmin($userId)
357
+     * @return boolean
358
+     */
359
+    function isAdminUser() {
360
+        $uid = $this->getUserId();
361
+        return \OC_User::isAdminUser($uid);
362
+    }
363
+
364
+    private function getUserId() {
365
+        return $this->getServer()->getSession()->get('user_id');
366
+    }
367
+
368
+    /**
369
+     * @deprecated use the ILogger instead
370
+     * @param string $message
371
+     * @param string $level
372
+     * @return mixed
373
+     */
374
+    function log($message, $level) {
375
+        switch($level){
376
+            case 'debug':
377
+                $level = \OCP\Util::DEBUG;
378
+                break;
379
+            case 'info':
380
+                $level = \OCP\Util::INFO;
381
+                break;
382
+            case 'warn':
383
+                $level = \OCP\Util::WARN;
384
+                break;
385
+            case 'fatal':
386
+                $level = \OCP\Util::FATAL;
387
+                break;
388
+            default:
389
+                $level = \OCP\Util::ERROR;
390
+                break;
391
+        }
392
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
393
+    }
394
+
395
+    /**
396
+     * Register a capability
397
+     *
398
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
399
+     */
400
+    public function registerCapability($serviceName) {
401
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
402
+            return $this->query($serviceName);
403
+        });
404
+    }
405
+
406
+    /**
407
+     * @param string $name
408
+     * @return mixed
409
+     * @throws QueryException if the query could not be resolved
410
+     */
411
+    public function query($name) {
412
+        try {
413
+            return $this->queryNoFallback($name);
414
+        } catch (QueryException $e) {
415
+            return $this->getServer()->query($name);
416
+        }
417
+    }
418
+
419
+    /**
420
+     * @param string $name
421
+     * @return mixed
422
+     * @throws QueryException if the query could not be resolved
423
+     */
424
+    public function queryNoFallback($name) {
425
+        $name = $this->sanitizeName($name);
426
+
427
+        if ($this->offsetExists($name)) {
428
+            return parent::query($name);
429
+        } else {
430
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
431
+                return parent::query($name);
432
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
433
+                return parent::query($name);
434
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
435
+                return parent::query($name);
436
+            }
437
+        }
438
+
439
+        throw new QueryException('Could not resolve ' . $name . '!' .
440
+            ' Class can not be instantiated');
441
+    }
442 442
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	 * @param array $urlParams
78 78
 	 * @param ServerContainer $server
79 79
 	 */
80
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
80
+	public function __construct($appName, $urlParams = array(), ServerContainer $server = null) {
81 81
 		parent::__construct();
82 82
 		$this['AppName'] = $appName;
83 83
 		$this['urlParams'] = $urlParams;
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 		/**
98 98
 		 * Core services
99 99
 		 */
100
-		$this->registerService(IOutput::class, function($c){
100
+		$this->registerService(IOutput::class, function($c) {
101 101
 			return new Output($this->getServer()->getWebRoot());
102 102
 		});
103 103
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			return $this->getServer()->getUserFolder();
106 106
 		});
107 107
 
108
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
108
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
109 109
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
110 110
 		});
111 111
 
@@ -126,25 +126,25 @@  discard block
 block discarded – undo
126 126
 
127 127
 		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
128 128
 
129
-		$this->registerService(IServerContainer::class, function ($c) {
129
+		$this->registerService(IServerContainer::class, function($c) {
130 130
 			return $this->getServer();
131 131
 		});
132 132
 		$this->registerAlias('ServerContainer', IServerContainer::class);
133 133
 
134
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
135 135
 			return $c->query('OCA\WorkflowEngine\Manager');
136 136
 		});
137 137
 
138
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
139 139
 			return $c;
140 140
 		});
141 141
 
142 142
 		// commonly used attributes
143
-		$this->registerService('UserId', function ($c) {
143
+		$this->registerService('UserId', function($c) {
144 144
 			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
145 145
 		});
146 146
 
147
-		$this->registerService('WebRoot', function ($c) {
147
+		$this->registerService('WebRoot', function($c) {
148 148
 			return $c->query('ServerContainer')->getWebRoot();
149 149
 		});
150 150
 
@@ -152,15 +152,15 @@  discard block
 block discarded – undo
152 152
 			return Util::getDefaultEmailAddress('no-reply');
153 153
 		});
154 154
 
155
-		$this->registerService('OC_Defaults', function ($c) {
155
+		$this->registerService('OC_Defaults', function($c) {
156 156
 			return $c->getServer()->getThemingDefaults();
157 157
 		});
158 158
 
159
-		$this->registerService('OCP\Encryption\IManager', function ($c) {
159
+		$this->registerService('OCP\Encryption\IManager', function($c) {
160 160
 			return $this->getServer()->getEncryptionManager();
161 161
 		});
162 162
 
163
-		$this->registerService(IConfig::class, function ($c) {
163
+		$this->registerService(IConfig::class, function($c) {
164 164
 			return $c->query(OC\GlobalScale\Config::class);
165 165
 		});
166 166
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			return $c->query(Validator::class);
169 169
 		});
170 170
 
171
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
171
+		$this->registerService(\OC\Security\IdentityProof\Manager::class, function($c) {
172 172
 			return new \OC\Security\IdentityProof\Manager(
173 173
 				$this->getServer()->query(\OC\Files\AppData\Factory::class),
174 174
 				$this->getServer()->getCrypto()
@@ -178,15 +178,15 @@  discard block
 block discarded – undo
178 178
 		/**
179 179
 		 * App Framework APIs
180 180
 		 */
181
-		$this->registerService('API', function($c){
181
+		$this->registerService('API', function($c) {
182 182
 			$c->query('OCP\\ILogger')->debug(
183
-				'Accessing the API class is deprecated! Use the appropriate ' .
183
+				'Accessing the API class is deprecated! Use the appropriate '.
184 184
 				'services instead!'
185 185
 			);
186 186
 			return new API($c['AppName']);
187 187
 		});
188 188
 
189
-		$this->registerService('Protocol', function($c){
189
+		$this->registerService('Protocol', function($c) {
190 190
 			/** @var \OC\Server $server */
191 191
 			$server = $c->query('ServerContainer');
192 192
 			$protocol = $server->getRequest()->getHttpProtocol();
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 			);
275 275
 		});
276 276
 
277
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
277
+		$this->registerService('TwoFactorMiddleware', function(SimpleContainer $c) use ($app) {
278 278
 			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
279 279
 			$userSession = $app->getServer()->getUserSession();
280 280
 			$session = $app->getServer()->getSession();
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
285 285
 		});
286 286
 
287
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
287
+		$this->registerService('OCSMiddleware', function(SimpleContainer $c) {
288 288
 			return new OCSMiddleware(
289 289
 				$c['Request']
290 290
 			);
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
301 301
 			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
302 302
 
303
-			foreach($middleWares as $middleWare) {
303
+			foreach ($middleWares as $middleWare) {
304 304
 				$dispatcher->registerMiddleware($c[$middleWare]);
305 305
 			}
306 306
 
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
 	 * @return mixed
373 373
 	 */
374 374
 	function log($message, $level) {
375
-		switch($level){
375
+		switch ($level) {
376 376
 			case 'debug':
377 377
 				$level = \OCP\Util::DEBUG;
378 378
 				break;
@@ -431,12 +431,12 @@  discard block
 block discarded – undo
431 431
 				return parent::query($name);
432 432
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
433 433
 				return parent::query($name);
434
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
434
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
435 435
 				return parent::query($name);
436 436
 			}
437 437
 		}
438 438
 
439
-		throw new QueryException('Could not resolve ' . $name . '!' .
439
+		throw new QueryException('Could not resolve '.$name.'!'.
440 440
 			' Class can not be instantiated');
441 441
 	}
442 442
 }
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -43,225 +43,225 @@
 block discarded – undo
43 43
  */
44 44
 class ProviderFactory implements IProviderFactory {
45 45
 
46
-	/** @var IServerContainer */
47
-	private $serverContainer;
48
-	/** @var DefaultShareProvider */
49
-	private $defaultProvider = null;
50
-	/** @var FederatedShareProvider */
51
-	private $federatedProvider = null;
52
-	/** @var  ShareByMailProvider */
53
-	private $shareByMailProvider;
54
-	/** @var  \OCA\Circles\ShareByCircleProvider;
55
-	 * ShareByCircleProvider */
56
-	private $shareByCircleProvider;
57
-
58
-	/**
59
-	 * IProviderFactory constructor.
60
-	 *
61
-	 * @param IServerContainer $serverContainer
62
-	 */
63
-	public function __construct(IServerContainer $serverContainer) {
64
-		$this->serverContainer = $serverContainer;
65
-	}
66
-
67
-	/**
68
-	 * Create the default share provider.
69
-	 *
70
-	 * @return DefaultShareProvider
71
-	 */
72
-	protected function defaultShareProvider() {
73
-		if ($this->defaultProvider === null) {
74
-			$this->defaultProvider = new DefaultShareProvider(
75
-				$this->serverContainer->getDatabaseConnection(),
76
-				$this->serverContainer->getUserManager(),
77
-				$this->serverContainer->getGroupManager(),
78
-				$this->serverContainer->getLazyRootFolder()
79
-			);
80
-		}
81
-
82
-		return $this->defaultProvider;
83
-	}
84
-
85
-	/**
86
-	 * Create the federated share provider
87
-	 *
88
-	 * @return FederatedShareProvider
89
-	 */
90
-	protected function federatedShareProvider() {
91
-		if ($this->federatedProvider === null) {
92
-			/*
46
+    /** @var IServerContainer */
47
+    private $serverContainer;
48
+    /** @var DefaultShareProvider */
49
+    private $defaultProvider = null;
50
+    /** @var FederatedShareProvider */
51
+    private $federatedProvider = null;
52
+    /** @var  ShareByMailProvider */
53
+    private $shareByMailProvider;
54
+    /** @var  \OCA\Circles\ShareByCircleProvider;
55
+     * ShareByCircleProvider */
56
+    private $shareByCircleProvider;
57
+
58
+    /**
59
+     * IProviderFactory constructor.
60
+     *
61
+     * @param IServerContainer $serverContainer
62
+     */
63
+    public function __construct(IServerContainer $serverContainer) {
64
+        $this->serverContainer = $serverContainer;
65
+    }
66
+
67
+    /**
68
+     * Create the default share provider.
69
+     *
70
+     * @return DefaultShareProvider
71
+     */
72
+    protected function defaultShareProvider() {
73
+        if ($this->defaultProvider === null) {
74
+            $this->defaultProvider = new DefaultShareProvider(
75
+                $this->serverContainer->getDatabaseConnection(),
76
+                $this->serverContainer->getUserManager(),
77
+                $this->serverContainer->getGroupManager(),
78
+                $this->serverContainer->getLazyRootFolder()
79
+            );
80
+        }
81
+
82
+        return $this->defaultProvider;
83
+    }
84
+
85
+    /**
86
+     * Create the federated share provider
87
+     *
88
+     * @return FederatedShareProvider
89
+     */
90
+    protected function federatedShareProvider() {
91
+        if ($this->federatedProvider === null) {
92
+            /*
93 93
 			 * Check if the app is enabled
94 94
 			 */
95
-			$appManager = $this->serverContainer->getAppManager();
96
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
97
-				return null;
98
-			}
95
+            $appManager = $this->serverContainer->getAppManager();
96
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
97
+                return null;
98
+            }
99 99
 
100
-			/*
100
+            /*
101 101
 			 * TODO: add factory to federated sharing app
102 102
 			 */
103
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
104
-			$addressHandler = new AddressHandler(
105
-				$this->serverContainer->getURLGenerator(),
106
-				$l,
107
-				$this->serverContainer->getCloudIdManager()
108
-			);
109
-			$notifications = new Notifications(
110
-				$addressHandler,
111
-				$this->serverContainer->getHTTPClientService(),
112
-				$this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
113
-				$this->serverContainer->getJobList()
114
-			);
115
-			$tokenHandler = new TokenHandler(
116
-				$this->serverContainer->getSecureRandom()
117
-			);
118
-
119
-			$this->federatedProvider = new FederatedShareProvider(
120
-				$this->serverContainer->getDatabaseConnection(),
121
-				$addressHandler,
122
-				$notifications,
123
-				$tokenHandler,
124
-				$l,
125
-				$this->serverContainer->getLogger(),
126
-				$this->serverContainer->getLazyRootFolder(),
127
-				$this->serverContainer->getConfig(),
128
-				$this->serverContainer->getUserManager(),
129
-				$this->serverContainer->getCloudIdManager(),
130
-				$this->serverContainer->query(Config::class)
131
-			);
132
-		}
133
-
134
-		return $this->federatedProvider;
135
-	}
136
-
137
-	/**
138
-	 * Create the federated share provider
139
-	 *
140
-	 * @return ShareByMailProvider
141
-	 */
142
-	protected function getShareByMailProvider() {
143
-		if ($this->shareByMailProvider === null) {
144
-			/*
103
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
104
+            $addressHandler = new AddressHandler(
105
+                $this->serverContainer->getURLGenerator(),
106
+                $l,
107
+                $this->serverContainer->getCloudIdManager()
108
+            );
109
+            $notifications = new Notifications(
110
+                $addressHandler,
111
+                $this->serverContainer->getHTTPClientService(),
112
+                $this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
113
+                $this->serverContainer->getJobList()
114
+            );
115
+            $tokenHandler = new TokenHandler(
116
+                $this->serverContainer->getSecureRandom()
117
+            );
118
+
119
+            $this->federatedProvider = new FederatedShareProvider(
120
+                $this->serverContainer->getDatabaseConnection(),
121
+                $addressHandler,
122
+                $notifications,
123
+                $tokenHandler,
124
+                $l,
125
+                $this->serverContainer->getLogger(),
126
+                $this->serverContainer->getLazyRootFolder(),
127
+                $this->serverContainer->getConfig(),
128
+                $this->serverContainer->getUserManager(),
129
+                $this->serverContainer->getCloudIdManager(),
130
+                $this->serverContainer->query(Config::class)
131
+            );
132
+        }
133
+
134
+        return $this->federatedProvider;
135
+    }
136
+
137
+    /**
138
+     * Create the federated share provider
139
+     *
140
+     * @return ShareByMailProvider
141
+     */
142
+    protected function getShareByMailProvider() {
143
+        if ($this->shareByMailProvider === null) {
144
+            /*
145 145
 			 * Check if the app is enabled
146 146
 			 */
147
-			$appManager = $this->serverContainer->getAppManager();
148
-			if (!$appManager->isEnabledForUser('sharebymail')) {
149
-				return null;
150
-			}
151
-
152
-			$settingsManager = new SettingsManager($this->serverContainer->getConfig());
153
-
154
-			$this->shareByMailProvider = new ShareByMailProvider(
155
-				$this->serverContainer->getDatabaseConnection(),
156
-				$this->serverContainer->getSecureRandom(),
157
-				$this->serverContainer->getUserManager(),
158
-				$this->serverContainer->getLazyRootFolder(),
159
-				$this->serverContainer->getL10N('sharebymail'),
160
-				$this->serverContainer->getLogger(),
161
-				$this->serverContainer->getMailer(),
162
-				$this->serverContainer->getURLGenerator(),
163
-				$this->serverContainer->getActivityManager(),
164
-				$settingsManager,
165
-				$this->serverContainer->query(Defaults::class),
166
-				$this->serverContainer->getHasher(),
167
-				$this->serverContainer->query(CapabilitiesManager::class)
168
-			);
169
-		}
170
-
171
-		return $this->shareByMailProvider;
172
-	}
173
-
174
-
175
-	/**
176
-	 * Create the circle share provider
177
-	 *
178
-	 * @return FederatedShareProvider
179
-	 */
180
-	protected function getShareByCircleProvider() {
181
-
182
-		$appManager = $this->serverContainer->getAppManager();
183
-		if (!$appManager->isEnabledForUser('circles')) {
184
-			return null;
185
-		}
186
-
187
-
188
-		if ($this->shareByCircleProvider === null) {
189
-
190
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
191
-				$this->serverContainer->getDatabaseConnection(),
192
-				$this->serverContainer->getSecureRandom(),
193
-				$this->serverContainer->getUserManager(),
194
-				$this->serverContainer->getLazyRootFolder(),
195
-				$this->serverContainer->getL10N('circles'),
196
-				$this->serverContainer->getLogger(),
197
-				$this->serverContainer->getURLGenerator()
198
-			);
199
-		}
200
-
201
-		return $this->shareByCircleProvider;
202
-	}
203
-
204
-
205
-	/**
206
-	 * @inheritdoc
207
-	 */
208
-	public function getProvider($id) {
209
-		$provider = null;
210
-		if ($id === 'ocinternal') {
211
-			$provider = $this->defaultShareProvider();
212
-		} else if ($id === 'ocFederatedSharing') {
213
-			$provider = $this->federatedShareProvider();
214
-		} else if ($id === 'ocMailShare') {
215
-			$provider = $this->getShareByMailProvider();
216
-		} else if ($id === 'ocCircleShare') {
217
-			$provider = $this->getShareByCircleProvider();
218
-		}
219
-
220
-		if ($provider === null) {
221
-			throw new ProviderException('No provider with id .' . $id . ' found.');
222
-		}
223
-
224
-		return $provider;
225
-	}
226
-
227
-	/**
228
-	 * @inheritdoc
229
-	 */
230
-	public function getProviderForType($shareType) {
231
-		$provider = null;
232
-
233
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
234
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
235
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
236
-		) {
237
-			$provider = $this->defaultShareProvider();
238
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
239
-			$provider = $this->federatedShareProvider();
240
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
241
-			$provider = $this->getShareByMailProvider();
242
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
243
-			$provider = $this->getShareByCircleProvider();
244
-		}
245
-
246
-
247
-		if ($provider === null) {
248
-			throw new ProviderException('No share provider for share type ' . $shareType);
249
-		}
250
-
251
-		return $provider;
252
-	}
253
-
254
-	public function getAllProviders() {
255
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
256
-		$shareByMail = $this->getShareByMailProvider();
257
-		if ($shareByMail !== null) {
258
-			$shares[] = $shareByMail;
259
-		}
260
-		$shareByCircle = $this->getShareByCircleProvider();
261
-		if ($shareByCircle !== null) {
262
-			$shares[] = $shareByCircle;
263
-		}
264
-
265
-		return $shares;
266
-	}
147
+            $appManager = $this->serverContainer->getAppManager();
148
+            if (!$appManager->isEnabledForUser('sharebymail')) {
149
+                return null;
150
+            }
151
+
152
+            $settingsManager = new SettingsManager($this->serverContainer->getConfig());
153
+
154
+            $this->shareByMailProvider = new ShareByMailProvider(
155
+                $this->serverContainer->getDatabaseConnection(),
156
+                $this->serverContainer->getSecureRandom(),
157
+                $this->serverContainer->getUserManager(),
158
+                $this->serverContainer->getLazyRootFolder(),
159
+                $this->serverContainer->getL10N('sharebymail'),
160
+                $this->serverContainer->getLogger(),
161
+                $this->serverContainer->getMailer(),
162
+                $this->serverContainer->getURLGenerator(),
163
+                $this->serverContainer->getActivityManager(),
164
+                $settingsManager,
165
+                $this->serverContainer->query(Defaults::class),
166
+                $this->serverContainer->getHasher(),
167
+                $this->serverContainer->query(CapabilitiesManager::class)
168
+            );
169
+        }
170
+
171
+        return $this->shareByMailProvider;
172
+    }
173
+
174
+
175
+    /**
176
+     * Create the circle share provider
177
+     *
178
+     * @return FederatedShareProvider
179
+     */
180
+    protected function getShareByCircleProvider() {
181
+
182
+        $appManager = $this->serverContainer->getAppManager();
183
+        if (!$appManager->isEnabledForUser('circles')) {
184
+            return null;
185
+        }
186
+
187
+
188
+        if ($this->shareByCircleProvider === null) {
189
+
190
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
191
+                $this->serverContainer->getDatabaseConnection(),
192
+                $this->serverContainer->getSecureRandom(),
193
+                $this->serverContainer->getUserManager(),
194
+                $this->serverContainer->getLazyRootFolder(),
195
+                $this->serverContainer->getL10N('circles'),
196
+                $this->serverContainer->getLogger(),
197
+                $this->serverContainer->getURLGenerator()
198
+            );
199
+        }
200
+
201
+        return $this->shareByCircleProvider;
202
+    }
203
+
204
+
205
+    /**
206
+     * @inheritdoc
207
+     */
208
+    public function getProvider($id) {
209
+        $provider = null;
210
+        if ($id === 'ocinternal') {
211
+            $provider = $this->defaultShareProvider();
212
+        } else if ($id === 'ocFederatedSharing') {
213
+            $provider = $this->federatedShareProvider();
214
+        } else if ($id === 'ocMailShare') {
215
+            $provider = $this->getShareByMailProvider();
216
+        } else if ($id === 'ocCircleShare') {
217
+            $provider = $this->getShareByCircleProvider();
218
+        }
219
+
220
+        if ($provider === null) {
221
+            throw new ProviderException('No provider with id .' . $id . ' found.');
222
+        }
223
+
224
+        return $provider;
225
+    }
226
+
227
+    /**
228
+     * @inheritdoc
229
+     */
230
+    public function getProviderForType($shareType) {
231
+        $provider = null;
232
+
233
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
234
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
235
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
236
+        ) {
237
+            $provider = $this->defaultShareProvider();
238
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
239
+            $provider = $this->federatedShareProvider();
240
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
241
+            $provider = $this->getShareByMailProvider();
242
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
243
+            $provider = $this->getShareByCircleProvider();
244
+        }
245
+
246
+
247
+        if ($provider === null) {
248
+            throw new ProviderException('No share provider for share type ' . $shareType);
249
+        }
250
+
251
+        return $provider;
252
+    }
253
+
254
+    public function getAllProviders() {
255
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
256
+        $shareByMail = $this->getShareByMailProvider();
257
+        if ($shareByMail !== null) {
258
+            $shares[] = $shareByMail;
259
+        }
260
+        $shareByCircle = $this->getShareByCircleProvider();
261
+        if ($shareByCircle !== null) {
262
+            $shares[] = $shareByCircle;
263
+        }
264
+
265
+        return $shares;
266
+    }
267 267
 }
Please login to merge, or discard this patch.