Completed
Push — stable10 ( d1b390...0bd063 )
by Lukas
27:03 queued 26:40
created
apps/files_external/ajax/oauth1.php 2 patches
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -33,42 +33,42 @@
 block discarded – undo
33 33
 
34 34
 // FIXME: currently hard-coded to Dropbox OAuth
35 35
 if (isset($_POST['app_key']) && isset($_POST['app_secret'])) {
36
-	$oauth = new Dropbox_OAuth_Curl((string)$_POST['app_key'], (string)$_POST['app_secret']);
37
-	if (isset($_POST['step'])) {
38
-		switch ($_POST['step']) {
39
-			case 1:
40
-				try {
41
-					if (isset($_POST['callback'])) {
42
-						$callback = (string)$_POST['callback'];
43
-					} else {
44
-						$callback = null;
45
-					}
46
-					$token = $oauth->getRequestToken();
47
-					OCP\JSON::success(array('data' => array('url' => $oauth->getAuthorizeUrl($callback),
48
-															'request_token' => $token['token'],
49
-															'request_token_secret' => $token['token_secret'])));
50
-				} catch (Exception $exception) {
51
-					OCP\JSON::error(array('data' => array('message' =>
52
-						$l->t('Fetching request tokens failed. Verify that your app key and secret are correct.'))
53
-						));
54
-				}
55
-				break;
56
-			case 2:
57
-				if (isset($_POST['request_token']) && isset($_POST['request_token_secret'])) {
58
-					try {
59
-						$oauth->setToken((string)$_POST['request_token'], (string)$_POST['request_token_secret']);
60
-						$token = $oauth->getAccessToken();
61
-						OCP\JSON::success(array('access_token' => $token['token'],
62
-												'access_token_secret' => $token['token_secret']));
63
-					} catch (Exception $exception) {
64
-						OCP\JSON::error(array('data' => array('message' =>
65
-							$l->t('Fetching access tokens failed. Verify that your app key and secret are correct.'))
66
-							));
67
-					}
68
-				}
69
-				break;
70
-		}
71
-	}
36
+    $oauth = new Dropbox_OAuth_Curl((string)$_POST['app_key'], (string)$_POST['app_secret']);
37
+    if (isset($_POST['step'])) {
38
+        switch ($_POST['step']) {
39
+            case 1:
40
+                try {
41
+                    if (isset($_POST['callback'])) {
42
+                        $callback = (string)$_POST['callback'];
43
+                    } else {
44
+                        $callback = null;
45
+                    }
46
+                    $token = $oauth->getRequestToken();
47
+                    OCP\JSON::success(array('data' => array('url' => $oauth->getAuthorizeUrl($callback),
48
+                                                            'request_token' => $token['token'],
49
+                                                            'request_token_secret' => $token['token_secret'])));
50
+                } catch (Exception $exception) {
51
+                    OCP\JSON::error(array('data' => array('message' =>
52
+                        $l->t('Fetching request tokens failed. Verify that your app key and secret are correct.'))
53
+                        ));
54
+                }
55
+                break;
56
+            case 2:
57
+                if (isset($_POST['request_token']) && isset($_POST['request_token_secret'])) {
58
+                    try {
59
+                        $oauth->setToken((string)$_POST['request_token'], (string)$_POST['request_token_secret']);
60
+                        $token = $oauth->getAccessToken();
61
+                        OCP\JSON::success(array('access_token' => $token['token'],
62
+                                                'access_token_secret' => $token['token_secret']));
63
+                    } catch (Exception $exception) {
64
+                        OCP\JSON::error(array('data' => array('message' =>
65
+                            $l->t('Fetching access tokens failed. Verify that your app key and secret are correct.'))
66
+                            ));
67
+                    }
68
+                }
69
+                break;
70
+        }
71
+    }
72 72
 } else {
73
-	OCP\JSON::error(array('data' => array('message' => $l->t('Please provide a valid app key and secret.'))));
73
+    OCP\JSON::error(array('data' => array('message' => $l->t('Please provide a valid app key and secret.'))));
74 74
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  * along with this program.  If not, see <http://www.gnu.org/licenses/>
25 25
  *
26 26
  */
27
-require_once __DIR__ . '/../3rdparty/Dropbox/autoload.php';
27
+require_once __DIR__.'/../3rdparty/Dropbox/autoload.php';
28 28
 
29 29
 OCP\JSON::checkAppEnabled('files_external');
30 30
 OCP\JSON::checkLoggedIn();
@@ -33,13 +33,13 @@  discard block
 block discarded – undo
33 33
 
34 34
 // FIXME: currently hard-coded to Dropbox OAuth
35 35
 if (isset($_POST['app_key']) && isset($_POST['app_secret'])) {
36
-	$oauth = new Dropbox_OAuth_Curl((string)$_POST['app_key'], (string)$_POST['app_secret']);
36
+	$oauth = new Dropbox_OAuth_Curl((string) $_POST['app_key'], (string) $_POST['app_secret']);
37 37
 	if (isset($_POST['step'])) {
38 38
 		switch ($_POST['step']) {
39 39
 			case 1:
40 40
 				try {
41 41
 					if (isset($_POST['callback'])) {
42
-						$callback = (string)$_POST['callback'];
42
+						$callback = (string) $_POST['callback'];
43 43
 					} else {
44 44
 						$callback = null;
45 45
 					}
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 			case 2:
57 57
 				if (isset($_POST['request_token']) && isset($_POST['request_token_secret'])) {
58 58
 					try {
59
-						$oauth->setToken((string)$_POST['request_token'], (string)$_POST['request_token_secret']);
59
+						$oauth->setToken((string) $_POST['request_token'], (string) $_POST['request_token_secret']);
60 60
 						$token = $oauth->getAccessToken();
61 61
 						OCP\JSON::success(array('access_token' => $token['token'],
62 62
 												'access_token_secret' => $token['token_secret']));
Please login to merge, or discard this patch.
apps/files_external/ajax/oauth2.php 2 patches
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
  *
29 29
  */
30 30
 set_include_path(get_include_path().PATH_SEPARATOR.
31
-	\OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
31
+    \OC_App::getAppPath('files_external').'/3rdparty/google-api-php-client/src');
32 32
 require_once 'Google/autoload.php';
33 33
 
34 34
 OCP\JSON::checkAppEnabled('files_external');
@@ -38,37 +38,37 @@  discard block
 block discarded – undo
38 38
 
39 39
 // FIXME: currently hard-coded to Google Drive
40 40
 if (isset($_POST['client_id']) && isset($_POST['client_secret']) && isset($_POST['redirect'])) {
41
-	$client = new Google_Client();
42
-	$client->setClientId((string)$_POST['client_id']);
43
-	$client->setClientSecret((string)$_POST['client_secret']);
44
-	$client->setRedirectUri((string)$_POST['redirect']);
45
-	$client->setScopes(array('https://www.googleapis.com/auth/drive'));
46
-	$client->setApprovalPrompt('force');
47
-	$client->setAccessType('offline');
48
-	if (isset($_POST['step'])) {
49
-		$step = $_POST['step'];
50
-		if ($step == 1) {
51
-			try {
52
-				$authUrl = $client->createAuthUrl();
53
-				OCP\JSON::success(array('data' => array(
54
-					'url' => $authUrl
55
-				)));
56
-			} catch (Exception $exception) {
57
-				OCP\JSON::error(array('data' => array(
58
-					'message' => $l->t('Step 1 failed. Exception: %s', array($exception->getMessage()))
59
-				)));
60
-			}
61
-		} else if ($step == 2 && isset($_POST['code'])) {
62
-			try {
63
-				$token = $client->authenticate((string)$_POST['code']);
64
-				OCP\JSON::success(array('data' => array(
65
-					'token' => $token
66
-				)));
67
-			} catch (Exception $exception) {
68
-				OCP\JSON::error(array('data' => array(
69
-					'message' => $l->t('Step 2 failed. Exception: %s', array($exception->getMessage()))
70
-				)));
71
-			}
72
-		}
73
-	}
41
+    $client = new Google_Client();
42
+    $client->setClientId((string)$_POST['client_id']);
43
+    $client->setClientSecret((string)$_POST['client_secret']);
44
+    $client->setRedirectUri((string)$_POST['redirect']);
45
+    $client->setScopes(array('https://www.googleapis.com/auth/drive'));
46
+    $client->setApprovalPrompt('force');
47
+    $client->setAccessType('offline');
48
+    if (isset($_POST['step'])) {
49
+        $step = $_POST['step'];
50
+        if ($step == 1) {
51
+            try {
52
+                $authUrl = $client->createAuthUrl();
53
+                OCP\JSON::success(array('data' => array(
54
+                    'url' => $authUrl
55
+                )));
56
+            } catch (Exception $exception) {
57
+                OCP\JSON::error(array('data' => array(
58
+                    'message' => $l->t('Step 1 failed. Exception: %s', array($exception->getMessage()))
59
+                )));
60
+            }
61
+        } else if ($step == 2 && isset($_POST['code'])) {
62
+            try {
63
+                $token = $client->authenticate((string)$_POST['code']);
64
+                OCP\JSON::success(array('data' => array(
65
+                    'token' => $token
66
+                )));
67
+            } catch (Exception $exception) {
68
+                OCP\JSON::error(array('data' => array(
69
+                    'message' => $l->t('Step 2 failed. Exception: %s', array($exception->getMessage()))
70
+                )));
71
+            }
72
+        }
73
+    }
74 74
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -39,9 +39,9 @@  discard block
 block discarded – undo
39 39
 // FIXME: currently hard-coded to Google Drive
40 40
 if (isset($_POST['client_id']) && isset($_POST['client_secret']) && isset($_POST['redirect'])) {
41 41
 	$client = new Google_Client();
42
-	$client->setClientId((string)$_POST['client_id']);
43
-	$client->setClientSecret((string)$_POST['client_secret']);
44
-	$client->setRedirectUri((string)$_POST['redirect']);
42
+	$client->setClientId((string) $_POST['client_id']);
43
+	$client->setClientSecret((string) $_POST['client_secret']);
44
+	$client->setRedirectUri((string) $_POST['redirect']);
45 45
 	$client->setScopes(array('https://www.googleapis.com/auth/drive'));
46 46
 	$client->setApprovalPrompt('force');
47 47
 	$client->setAccessType('offline');
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 			}
61 61
 		} else if ($step == 2 && isset($_POST['code'])) {
62 62
 			try {
63
-				$token = $client->authenticate((string)$_POST['code']);
63
+				$token = $client->authenticate((string) $_POST['code']);
64 64
 				OCP\JSON::success(array('data' => array(
65 65
 					'token' => $token
66 66
 				)));
Please login to merge, or discard this patch.
apps/files_external/ajax/applicable.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -30,23 +30,23 @@
 block discarded – undo
30 30
 $limit = null;
31 31
 $offset = null;
32 32
 if (isset($_GET['pattern'])) {
33
-	$pattern = (string)$_GET['pattern'];
33
+    $pattern = (string)$_GET['pattern'];
34 34
 }
35 35
 if (isset($_GET['limit'])) {
36
-	$limit = (int)$_GET['limit'];
36
+    $limit = (int)$_GET['limit'];
37 37
 }
38 38
 if (isset($_GET['offset'])) {
39
-	$offset = (int)$_GET['offset'];
39
+    $offset = (int)$_GET['offset'];
40 40
 }
41 41
 
42 42
 $groups = [];
43 43
 foreach (\OC::$server->getGroupManager()->search($pattern, $limit, $offset) as $group) {
44
-	$groups[$group->getGID()] = $group->getGID();
44
+    $groups[$group->getGID()] = $group->getGID();
45 45
 }
46 46
 
47 47
 $users = [];
48 48
 foreach (\OC::$server->getUserManager()->searchDisplayName($pattern, $limit, $offset) as $user) {
49
-	$users[$user->getUID()] = $user->getDisplayName();
49
+    $users[$user->getUID()] = $user->getDisplayName();
50 50
 }
51 51
 
52 52
 $results = array('groups' => $groups, 'users' => $users);
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -30,13 +30,13 @@
 block discarded – undo
30 30
 $limit = null;
31 31
 $offset = null;
32 32
 if (isset($_GET['pattern'])) {
33
-	$pattern = (string)$_GET['pattern'];
33
+	$pattern = (string) $_GET['pattern'];
34 34
 }
35 35
 if (isset($_GET['limit'])) {
36
-	$limit = (int)$_GET['limit'];
36
+	$limit = (int) $_GET['limit'];
37 37
 }
38 38
 if (isset($_GET['offset'])) {
39
-	$offset = (int)$_GET['offset'];
39
+	$offset = (int) $_GET['offset'];
40 40
 }
41 41
 
42 42
 $groups = [];
Please login to merge, or discard this patch.
apps/files_external/lib/Service/ImportLegacyStoragesService.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -24,25 +24,25 @@
 block discarded – undo
24 24
 namespace OCA\Files_External\Service;
25 25
 
26 26
 class ImportLegacyStoragesService extends LegacyStoragesService {
27
-	private $data;
27
+    private $data;
28 28
 
29
-	/**
30
-	 * @param BackendService $backendService
31
-	 */
32
-	public function __construct(BackendService $backendService) {
33
-		$this->backendService = $backendService;
34
-	}
29
+    /**
30
+     * @param BackendService $backendService
31
+     */
32
+    public function __construct(BackendService $backendService) {
33
+        $this->backendService = $backendService;
34
+    }
35 35
 
36
-	public function setData($data) {
37
-		$this->data = $data;
38
-	}
36
+    public function setData($data) {
37
+        $this->data = $data;
38
+    }
39 39
 
40
-	/**
41
-	 * Read legacy config data
42
-	 *
43
-	 * @return array list of mount configs
44
-	 */
45
-	protected function readLegacyConfig() {
46
-		return $this->data;
47
-	}
40
+    /**
41
+     * Read legacy config data
42
+     *
43
+     * @return array list of mount configs
44
+     */
45
+    protected function readLegacyConfig() {
46
+        return $this->data;
47
+    }
48 48
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Service/BackendService.php 1 patch
Indentation   +245 added lines, -245 removed lines patch added patch discarded remove patch
@@ -35,249 +35,249 @@
 block discarded – undo
35 35
  */
36 36
 class BackendService {
37 37
 
38
-	/** Visibility constants for VisibilityTrait */
39
-	const VISIBILITY_NONE = 0;
40
-	const VISIBILITY_PERSONAL = 1;
41
-	const VISIBILITY_ADMIN = 2;
42
-	//const VISIBILITY_ALIENS = 4;
43
-
44
-	const VISIBILITY_DEFAULT = 3; // PERSONAL | ADMIN
45
-
46
-	/** Priority constants for PriorityTrait */
47
-	const PRIORITY_DEFAULT = 100;
48
-
49
-	/** @var IConfig */
50
-	protected $config;
51
-
52
-	/** @var bool */
53
-	private $userMountingAllowed = true;
54
-
55
-	/** @var string[] */
56
-	private $userMountingBackends = [];
57
-
58
-	/** @var Backend[] */
59
-	private $backends = [];
60
-
61
-	/** @var IBackendProvider[] */
62
-	private $backendProviders = [];
63
-
64
-	/** @var AuthMechanism[] */
65
-	private $authMechanisms = [];
66
-
67
-	/** @var IAuthMechanismProvider[] */
68
-	private $authMechanismProviders = [];
69
-
70
-	/**
71
-	 * @param IConfig $config
72
-	 */
73
-	public function __construct(
74
-		IConfig $config
75
-	) {
76
-		$this->config = $config;
77
-
78
-		// Load config values
79
-		if ($this->config->getAppValue('files_external', 'allow_user_mounting', 'yes') !== 'yes') {
80
-			$this->userMountingAllowed = false;
81
-		}
82
-		$this->userMountingBackends = explode(',',
83
-			$this->config->getAppValue('files_external', 'user_mounting_backends', '')
84
-		);
85
-
86
-		// if no backend is in the list an empty string is in the array and user mounting is disabled
87
-		if ($this->userMountingBackends === ['']) {
88
-			$this->userMountingAllowed = false;
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * Register a backend provider
94
-	 *
95
-	 * @since 9.1.0
96
-	 * @param IBackendProvider $provider
97
-	 */
98
-	public function registerBackendProvider(IBackendProvider $provider) {
99
-		$this->backendProviders[] = $provider;
100
-	}
101
-
102
-	private function loadBackendProviders() {
103
-		foreach ($this->backendProviders as $provider) {
104
-			$this->registerBackends($provider->getBackends());
105
-		}
106
-		$this->backendProviders = [];
107
-	}
108
-
109
-	/**
110
-	 * Register an auth mechanism provider
111
-	 *
112
-	 * @since 9.1.0
113
-	 * @param IAuthMechanismProvider $provider
114
-	 */
115
-	public function registerAuthMechanismProvider(IAuthMechanismProvider $provider) {
116
-		$this->authMechanismProviders[] = $provider;
117
-	}
118
-
119
-	private function loadAuthMechanismProviders() {
120
-		foreach ($this->authMechanismProviders as $provider) {
121
-			$this->registerAuthMechanisms($provider->getAuthMechanisms());
122
-		}
123
-		$this->authMechanismProviders = [];
124
-	}
125
-
126
-	/**
127
-	 * Register a backend
128
-	 *
129
-	 * @deprecated 9.1.0 use registerBackendProvider()
130
-	 * @param Backend $backend
131
-	 */
132
-	public function registerBackend(Backend $backend) {
133
-		if (!$this->isAllowedUserBackend($backend)) {
134
-			$backend->removeVisibility(BackendService::VISIBILITY_PERSONAL);
135
-		}
136
-		foreach ($backend->getIdentifierAliases() as $alias) {
137
-			$this->backends[$alias] = $backend;
138
-		}
139
-	}
140
-
141
-	/**
142
-	 * @deprecated 9.1.0 use registerBackendProvider()
143
-	 * @param Backend[] $backends
144
-	 */
145
-	public function registerBackends(array $backends) {
146
-		foreach ($backends as $backend) {
147
-			$this->registerBackend($backend);
148
-		}
149
-	}
150
-	/**
151
-	 * Register an authentication mechanism
152
-	 *
153
-	 * @deprecated 9.1.0 use registerAuthMechanismProvider()
154
-	 * @param AuthMechanism $authMech
155
-	 */
156
-	public function registerAuthMechanism(AuthMechanism $authMech) {
157
-		if (!$this->isAllowedAuthMechanism($authMech)) {
158
-			$authMech->removeVisibility(BackendService::VISIBILITY_PERSONAL);
159
-		}
160
-		foreach ($authMech->getIdentifierAliases() as $alias) {
161
-			$this->authMechanisms[$alias] = $authMech;
162
-		}
163
-	}
164
-
165
-	/**
166
-	 * @deprecated 9.1.0 use registerAuthMechanismProvider()
167
-	 * @param AuthMechanism[] $mechanisms
168
-	 */
169
-	public function registerAuthMechanisms(array $mechanisms) {
170
-		foreach ($mechanisms as $mechanism) {
171
-			$this->registerAuthMechanism($mechanism);
172
-		}
173
-	}
174
-
175
-	/**
176
-	 * Get all backends
177
-	 *
178
-	 * @return Backend[]
179
-	 */
180
-	public function getBackends() {
181
-		$this->loadBackendProviders();
182
-		// only return real identifiers, no aliases
183
-		$backends = [];
184
-		foreach ($this->backends as $backend) {
185
-			$backends[$backend->getIdentifier()] = $backend;
186
-		}
187
-		return $backends;
188
-	}
189
-
190
-	/**
191
-	 * Get all available backends
192
-	 *
193
-	 * @return Backend[]
194
-	 */
195
-	public function getAvailableBackends() {
196
-		return array_filter($this->getBackends(), function($backend) {
197
-			return !($backend->checkDependencies());
198
-		});
199
-	}
200
-
201
-	/**
202
-	 * @param string $identifier
203
-	 * @return Backend|null
204
-	 */
205
-	public function getBackend($identifier) {
206
-		$this->loadBackendProviders();
207
-		if (isset($this->backends[$identifier])) {
208
-			return $this->backends[$identifier];
209
-		}
210
-		return null;
211
-	}
212
-
213
-	/**
214
-	 * Get all authentication mechanisms
215
-	 *
216
-	 * @return AuthMechanism[]
217
-	 */
218
-	public function getAuthMechanisms() {
219
-		$this->loadAuthMechanismProviders();
220
-		// only return real identifiers, no aliases
221
-		$mechanisms = [];
222
-		foreach ($this->authMechanisms as $mechanism) {
223
-			$mechanisms[$mechanism->getIdentifier()] = $mechanism;
224
-		}
225
-		return $mechanisms;
226
-	}
227
-
228
-	/**
229
-	 * Get all authentication mechanisms for schemes
230
-	 *
231
-	 * @param string[] $schemes
232
-	 * @return AuthMechanism[]
233
-	 */
234
-	public function getAuthMechanismsByScheme(array $schemes) {
235
-		return array_filter($this->getAuthMechanisms(), function($authMech) use ($schemes) {
236
-			return in_array($authMech->getScheme(), $schemes, true);
237
-		});
238
-	}
239
-
240
-	/**
241
-	 * @param string $identifier
242
-	 * @return AuthMechanism|null
243
-	 */
244
-	public function getAuthMechanism($identifier) {
245
-		$this->loadAuthMechanismProviders();
246
-		if (isset($this->authMechanisms[$identifier])) {
247
-			return $this->authMechanisms[$identifier];
248
-		}
249
-		return null;
250
-	}
251
-
252
-	/**
253
-	 * @return bool
254
-	 */
255
-	public function isUserMountingAllowed() {
256
-		return $this->userMountingAllowed;
257
-	}
258
-
259
-	/**
260
-	 * Check a backend if a user is allowed to mount it
261
-	 *
262
-	 * @param Backend $backend
263
-	 * @return bool
264
-	 */
265
-	protected function isAllowedUserBackend(Backend $backend) {
266
-		if ($this->userMountingAllowed &&
267
-			array_intersect($backend->getIdentifierAliases(), $this->userMountingBackends)
268
-		) {
269
-			return true;
270
-		}
271
-		return false;
272
-	}
273
-
274
-	/**
275
-	 * Check an authentication mechanism if a user is allowed to use it
276
-	 *
277
-	 * @param AuthMechanism $authMechanism
278
-	 * @return bool
279
-	 */
280
-	protected function isAllowedAuthMechanism(AuthMechanism $authMechanism) {
281
-		return true; // not implemented
282
-	}
38
+    /** Visibility constants for VisibilityTrait */
39
+    const VISIBILITY_NONE = 0;
40
+    const VISIBILITY_PERSONAL = 1;
41
+    const VISIBILITY_ADMIN = 2;
42
+    //const VISIBILITY_ALIENS = 4;
43
+
44
+    const VISIBILITY_DEFAULT = 3; // PERSONAL | ADMIN
45
+
46
+    /** Priority constants for PriorityTrait */
47
+    const PRIORITY_DEFAULT = 100;
48
+
49
+    /** @var IConfig */
50
+    protected $config;
51
+
52
+    /** @var bool */
53
+    private $userMountingAllowed = true;
54
+
55
+    /** @var string[] */
56
+    private $userMountingBackends = [];
57
+
58
+    /** @var Backend[] */
59
+    private $backends = [];
60
+
61
+    /** @var IBackendProvider[] */
62
+    private $backendProviders = [];
63
+
64
+    /** @var AuthMechanism[] */
65
+    private $authMechanisms = [];
66
+
67
+    /** @var IAuthMechanismProvider[] */
68
+    private $authMechanismProviders = [];
69
+
70
+    /**
71
+     * @param IConfig $config
72
+     */
73
+    public function __construct(
74
+        IConfig $config
75
+    ) {
76
+        $this->config = $config;
77
+
78
+        // Load config values
79
+        if ($this->config->getAppValue('files_external', 'allow_user_mounting', 'yes') !== 'yes') {
80
+            $this->userMountingAllowed = false;
81
+        }
82
+        $this->userMountingBackends = explode(',',
83
+            $this->config->getAppValue('files_external', 'user_mounting_backends', '')
84
+        );
85
+
86
+        // if no backend is in the list an empty string is in the array and user mounting is disabled
87
+        if ($this->userMountingBackends === ['']) {
88
+            $this->userMountingAllowed = false;
89
+        }
90
+    }
91
+
92
+    /**
93
+     * Register a backend provider
94
+     *
95
+     * @since 9.1.0
96
+     * @param IBackendProvider $provider
97
+     */
98
+    public function registerBackendProvider(IBackendProvider $provider) {
99
+        $this->backendProviders[] = $provider;
100
+    }
101
+
102
+    private function loadBackendProviders() {
103
+        foreach ($this->backendProviders as $provider) {
104
+            $this->registerBackends($provider->getBackends());
105
+        }
106
+        $this->backendProviders = [];
107
+    }
108
+
109
+    /**
110
+     * Register an auth mechanism provider
111
+     *
112
+     * @since 9.1.0
113
+     * @param IAuthMechanismProvider $provider
114
+     */
115
+    public function registerAuthMechanismProvider(IAuthMechanismProvider $provider) {
116
+        $this->authMechanismProviders[] = $provider;
117
+    }
118
+
119
+    private function loadAuthMechanismProviders() {
120
+        foreach ($this->authMechanismProviders as $provider) {
121
+            $this->registerAuthMechanisms($provider->getAuthMechanisms());
122
+        }
123
+        $this->authMechanismProviders = [];
124
+    }
125
+
126
+    /**
127
+     * Register a backend
128
+     *
129
+     * @deprecated 9.1.0 use registerBackendProvider()
130
+     * @param Backend $backend
131
+     */
132
+    public function registerBackend(Backend $backend) {
133
+        if (!$this->isAllowedUserBackend($backend)) {
134
+            $backend->removeVisibility(BackendService::VISIBILITY_PERSONAL);
135
+        }
136
+        foreach ($backend->getIdentifierAliases() as $alias) {
137
+            $this->backends[$alias] = $backend;
138
+        }
139
+    }
140
+
141
+    /**
142
+     * @deprecated 9.1.0 use registerBackendProvider()
143
+     * @param Backend[] $backends
144
+     */
145
+    public function registerBackends(array $backends) {
146
+        foreach ($backends as $backend) {
147
+            $this->registerBackend($backend);
148
+        }
149
+    }
150
+    /**
151
+     * Register an authentication mechanism
152
+     *
153
+     * @deprecated 9.1.0 use registerAuthMechanismProvider()
154
+     * @param AuthMechanism $authMech
155
+     */
156
+    public function registerAuthMechanism(AuthMechanism $authMech) {
157
+        if (!$this->isAllowedAuthMechanism($authMech)) {
158
+            $authMech->removeVisibility(BackendService::VISIBILITY_PERSONAL);
159
+        }
160
+        foreach ($authMech->getIdentifierAliases() as $alias) {
161
+            $this->authMechanisms[$alias] = $authMech;
162
+        }
163
+    }
164
+
165
+    /**
166
+     * @deprecated 9.1.0 use registerAuthMechanismProvider()
167
+     * @param AuthMechanism[] $mechanisms
168
+     */
169
+    public function registerAuthMechanisms(array $mechanisms) {
170
+        foreach ($mechanisms as $mechanism) {
171
+            $this->registerAuthMechanism($mechanism);
172
+        }
173
+    }
174
+
175
+    /**
176
+     * Get all backends
177
+     *
178
+     * @return Backend[]
179
+     */
180
+    public function getBackends() {
181
+        $this->loadBackendProviders();
182
+        // only return real identifiers, no aliases
183
+        $backends = [];
184
+        foreach ($this->backends as $backend) {
185
+            $backends[$backend->getIdentifier()] = $backend;
186
+        }
187
+        return $backends;
188
+    }
189
+
190
+    /**
191
+     * Get all available backends
192
+     *
193
+     * @return Backend[]
194
+     */
195
+    public function getAvailableBackends() {
196
+        return array_filter($this->getBackends(), function($backend) {
197
+            return !($backend->checkDependencies());
198
+        });
199
+    }
200
+
201
+    /**
202
+     * @param string $identifier
203
+     * @return Backend|null
204
+     */
205
+    public function getBackend($identifier) {
206
+        $this->loadBackendProviders();
207
+        if (isset($this->backends[$identifier])) {
208
+            return $this->backends[$identifier];
209
+        }
210
+        return null;
211
+    }
212
+
213
+    /**
214
+     * Get all authentication mechanisms
215
+     *
216
+     * @return AuthMechanism[]
217
+     */
218
+    public function getAuthMechanisms() {
219
+        $this->loadAuthMechanismProviders();
220
+        // only return real identifiers, no aliases
221
+        $mechanisms = [];
222
+        foreach ($this->authMechanisms as $mechanism) {
223
+            $mechanisms[$mechanism->getIdentifier()] = $mechanism;
224
+        }
225
+        return $mechanisms;
226
+    }
227
+
228
+    /**
229
+     * Get all authentication mechanisms for schemes
230
+     *
231
+     * @param string[] $schemes
232
+     * @return AuthMechanism[]
233
+     */
234
+    public function getAuthMechanismsByScheme(array $schemes) {
235
+        return array_filter($this->getAuthMechanisms(), function($authMech) use ($schemes) {
236
+            return in_array($authMech->getScheme(), $schemes, true);
237
+        });
238
+    }
239
+
240
+    /**
241
+     * @param string $identifier
242
+     * @return AuthMechanism|null
243
+     */
244
+    public function getAuthMechanism($identifier) {
245
+        $this->loadAuthMechanismProviders();
246
+        if (isset($this->authMechanisms[$identifier])) {
247
+            return $this->authMechanisms[$identifier];
248
+        }
249
+        return null;
250
+    }
251
+
252
+    /**
253
+     * @return bool
254
+     */
255
+    public function isUserMountingAllowed() {
256
+        return $this->userMountingAllowed;
257
+    }
258
+
259
+    /**
260
+     * Check a backend if a user is allowed to mount it
261
+     *
262
+     * @param Backend $backend
263
+     * @return bool
264
+     */
265
+    protected function isAllowedUserBackend(Backend $backend) {
266
+        if ($this->userMountingAllowed &&
267
+            array_intersect($backend->getIdentifierAliases(), $this->userMountingBackends)
268
+        ) {
269
+            return true;
270
+        }
271
+        return false;
272
+    }
273
+
274
+    /**
275
+     * Check an authentication mechanism if a user is allowed to use it
276
+     *
277
+     * @param AuthMechanism $authMechanism
278
+     * @return bool
279
+     */
280
+    protected function isAllowedAuthMechanism(AuthMechanism $authMechanism) {
281
+        return true; // not implemented
282
+    }
283 283
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Service/GlobalStoragesService.php 2 patches
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -35,151 +35,151 @@
 block discarded – undo
35 35
  * Service class to manage global external storages
36 36
  */
37 37
 class GlobalStoragesService extends StoragesService {
38
-	/**
39
-	 * Triggers $signal for all applicable users of the given
40
-	 * storage
41
-	 *
42
-	 * @param StorageConfig $storage storage data
43
-	 * @param string $signal signal to trigger
44
-	 */
45
-	protected function triggerHooks(StorageConfig $storage, $signal) {
46
-		// FIXME: Use as expression in empty once PHP 5.4 support is dropped
47
-		$applicableUsers = $storage->getApplicableUsers();
48
-		$applicableGroups = $storage->getApplicableGroups();
49
-		if (empty($applicableUsers) && empty($applicableGroups)) {
50
-			// raise for user "all"
51
-			$this->triggerApplicableHooks(
52
-				$signal,
53
-				$storage->getMountPoint(),
54
-				\OC_Mount_Config::MOUNT_TYPE_USER,
55
-				['all']
56
-			);
57
-			return;
58
-		}
59
-
60
-		$this->triggerApplicableHooks(
61
-			$signal,
62
-			$storage->getMountPoint(),
63
-			\OC_Mount_Config::MOUNT_TYPE_USER,
64
-			$applicableUsers
65
-		);
66
-		$this->triggerApplicableHooks(
67
-			$signal,
68
-			$storage->getMountPoint(),
69
-			\OC_Mount_Config::MOUNT_TYPE_GROUP,
70
-			$applicableGroups
71
-		);
72
-	}
73
-
74
-	/**
75
-	 * Triggers signal_create_mount or signal_delete_mount to
76
-	 * accommodate for additions/deletions in applicableUsers
77
-	 * and applicableGroups fields.
78
-	 *
79
-	 * @param StorageConfig $oldStorage old storage config
80
-	 * @param StorageConfig $newStorage new storage config
81
-	 */
82
-	protected function triggerChangeHooks(StorageConfig $oldStorage, StorageConfig $newStorage) {
83
-		// if mount point changed, it's like a deletion + creation
84
-		if ($oldStorage->getMountPoint() !== $newStorage->getMountPoint()) {
85
-			$this->triggerHooks($oldStorage, Filesystem::signal_delete_mount);
86
-			$this->triggerHooks($newStorage, Filesystem::signal_create_mount);
87
-			return;
88
-		}
89
-
90
-		$userAdditions = array_diff($newStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());
91
-		$userDeletions = array_diff($oldStorage->getApplicableUsers(), $newStorage->getApplicableUsers());
92
-		$groupAdditions = array_diff($newStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());
93
-		$groupDeletions = array_diff($oldStorage->getApplicableGroups(), $newStorage->getApplicableGroups());
94
-
95
-		// FIXME: Use as expression in empty once PHP 5.4 support is dropped
96
-		// if no applicable were set, raise a signal for "all"
97
-		$oldApplicableUsers = $oldStorage->getApplicableUsers();
98
-		$oldApplicableGroups = $oldStorage->getApplicableGroups();
99
-		if (empty($oldApplicableUsers) && empty($oldApplicableGroups)) {
100
-			$this->triggerApplicableHooks(
101
-				Filesystem::signal_delete_mount,
102
-				$oldStorage->getMountPoint(),
103
-				\OC_Mount_Config::MOUNT_TYPE_USER,
104
-				['all']
105
-			);
106
-		}
107
-
108
-		// trigger delete for removed users
109
-		$this->triggerApplicableHooks(
110
-			Filesystem::signal_delete_mount,
111
-			$oldStorage->getMountPoint(),
112
-			\OC_Mount_Config::MOUNT_TYPE_USER,
113
-			$userDeletions
114
-		);
115
-
116
-		// trigger delete for removed groups
117
-		$this->triggerApplicableHooks(
118
-			Filesystem::signal_delete_mount,
119
-			$oldStorage->getMountPoint(),
120
-			\OC_Mount_Config::MOUNT_TYPE_GROUP,
121
-			$groupDeletions
122
-		);
123
-
124
-		// and now add the new users
125
-		$this->triggerApplicableHooks(
126
-			Filesystem::signal_create_mount,
127
-			$newStorage->getMountPoint(),
128
-			\OC_Mount_Config::MOUNT_TYPE_USER,
129
-			$userAdditions
130
-		);
131
-
132
-		// and now add the new groups
133
-		$this->triggerApplicableHooks(
134
-			Filesystem::signal_create_mount,
135
-			$newStorage->getMountPoint(),
136
-			\OC_Mount_Config::MOUNT_TYPE_GROUP,
137
-			$groupAdditions
138
-		);
139
-
140
-		// FIXME: Use as expression in empty once PHP 5.4 support is dropped
141
-		// if no applicable, raise a signal for "all"
142
-		$newApplicableUsers = $newStorage->getApplicableUsers();
143
-		$newApplicableGroups = $newStorage->getApplicableGroups();
144
-		if (empty($newApplicableUsers) && empty($newApplicableGroups)) {
145
-			$this->triggerApplicableHooks(
146
-				Filesystem::signal_create_mount,
147
-				$newStorage->getMountPoint(),
148
-				\OC_Mount_Config::MOUNT_TYPE_USER,
149
-				['all']
150
-			);
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * Get the visibility type for this controller, used in validation
156
-	 *
157
-	 * @return string BackendService::VISIBILITY_* constants
158
-	 */
159
-	public function getVisibilityType() {
160
-		return BackendService::VISIBILITY_ADMIN;
161
-	}
162
-
163
-	protected function isApplicable(StorageConfig $config) {
164
-		return true;
165
-	}
166
-
167
-	/**
168
-	 * Get all configured admin and personal mounts
169
-	 *
170
-	 * @return array map of storage id to storage config
171
-	 */
172
-	public function getStorageForAllUsers() {
173
-		$mounts = $this->dbConfig->getAllMounts();
174
-		$configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
175
-		$configs = array_filter($configs, function ($config) {
176
-			return $config instanceof StorageConfig;
177
-		});
178
-
179
-		$keys = array_map(function (StorageConfig $config) {
180
-			return $config->getId();
181
-		}, $configs);
182
-
183
-		return array_combine($keys, $configs);
184
-	}
38
+    /**
39
+     * Triggers $signal for all applicable users of the given
40
+     * storage
41
+     *
42
+     * @param StorageConfig $storage storage data
43
+     * @param string $signal signal to trigger
44
+     */
45
+    protected function triggerHooks(StorageConfig $storage, $signal) {
46
+        // FIXME: Use as expression in empty once PHP 5.4 support is dropped
47
+        $applicableUsers = $storage->getApplicableUsers();
48
+        $applicableGroups = $storage->getApplicableGroups();
49
+        if (empty($applicableUsers) && empty($applicableGroups)) {
50
+            // raise for user "all"
51
+            $this->triggerApplicableHooks(
52
+                $signal,
53
+                $storage->getMountPoint(),
54
+                \OC_Mount_Config::MOUNT_TYPE_USER,
55
+                ['all']
56
+            );
57
+            return;
58
+        }
59
+
60
+        $this->triggerApplicableHooks(
61
+            $signal,
62
+            $storage->getMountPoint(),
63
+            \OC_Mount_Config::MOUNT_TYPE_USER,
64
+            $applicableUsers
65
+        );
66
+        $this->triggerApplicableHooks(
67
+            $signal,
68
+            $storage->getMountPoint(),
69
+            \OC_Mount_Config::MOUNT_TYPE_GROUP,
70
+            $applicableGroups
71
+        );
72
+    }
73
+
74
+    /**
75
+     * Triggers signal_create_mount or signal_delete_mount to
76
+     * accommodate for additions/deletions in applicableUsers
77
+     * and applicableGroups fields.
78
+     *
79
+     * @param StorageConfig $oldStorage old storage config
80
+     * @param StorageConfig $newStorage new storage config
81
+     */
82
+    protected function triggerChangeHooks(StorageConfig $oldStorage, StorageConfig $newStorage) {
83
+        // if mount point changed, it's like a deletion + creation
84
+        if ($oldStorage->getMountPoint() !== $newStorage->getMountPoint()) {
85
+            $this->triggerHooks($oldStorage, Filesystem::signal_delete_mount);
86
+            $this->triggerHooks($newStorage, Filesystem::signal_create_mount);
87
+            return;
88
+        }
89
+
90
+        $userAdditions = array_diff($newStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());
91
+        $userDeletions = array_diff($oldStorage->getApplicableUsers(), $newStorage->getApplicableUsers());
92
+        $groupAdditions = array_diff($newStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());
93
+        $groupDeletions = array_diff($oldStorage->getApplicableGroups(), $newStorage->getApplicableGroups());
94
+
95
+        // FIXME: Use as expression in empty once PHP 5.4 support is dropped
96
+        // if no applicable were set, raise a signal for "all"
97
+        $oldApplicableUsers = $oldStorage->getApplicableUsers();
98
+        $oldApplicableGroups = $oldStorage->getApplicableGroups();
99
+        if (empty($oldApplicableUsers) && empty($oldApplicableGroups)) {
100
+            $this->triggerApplicableHooks(
101
+                Filesystem::signal_delete_mount,
102
+                $oldStorage->getMountPoint(),
103
+                \OC_Mount_Config::MOUNT_TYPE_USER,
104
+                ['all']
105
+            );
106
+        }
107
+
108
+        // trigger delete for removed users
109
+        $this->triggerApplicableHooks(
110
+            Filesystem::signal_delete_mount,
111
+            $oldStorage->getMountPoint(),
112
+            \OC_Mount_Config::MOUNT_TYPE_USER,
113
+            $userDeletions
114
+        );
115
+
116
+        // trigger delete for removed groups
117
+        $this->triggerApplicableHooks(
118
+            Filesystem::signal_delete_mount,
119
+            $oldStorage->getMountPoint(),
120
+            \OC_Mount_Config::MOUNT_TYPE_GROUP,
121
+            $groupDeletions
122
+        );
123
+
124
+        // and now add the new users
125
+        $this->triggerApplicableHooks(
126
+            Filesystem::signal_create_mount,
127
+            $newStorage->getMountPoint(),
128
+            \OC_Mount_Config::MOUNT_TYPE_USER,
129
+            $userAdditions
130
+        );
131
+
132
+        // and now add the new groups
133
+        $this->triggerApplicableHooks(
134
+            Filesystem::signal_create_mount,
135
+            $newStorage->getMountPoint(),
136
+            \OC_Mount_Config::MOUNT_TYPE_GROUP,
137
+            $groupAdditions
138
+        );
139
+
140
+        // FIXME: Use as expression in empty once PHP 5.4 support is dropped
141
+        // if no applicable, raise a signal for "all"
142
+        $newApplicableUsers = $newStorage->getApplicableUsers();
143
+        $newApplicableGroups = $newStorage->getApplicableGroups();
144
+        if (empty($newApplicableUsers) && empty($newApplicableGroups)) {
145
+            $this->triggerApplicableHooks(
146
+                Filesystem::signal_create_mount,
147
+                $newStorage->getMountPoint(),
148
+                \OC_Mount_Config::MOUNT_TYPE_USER,
149
+                ['all']
150
+            );
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Get the visibility type for this controller, used in validation
156
+     *
157
+     * @return string BackendService::VISIBILITY_* constants
158
+     */
159
+    public function getVisibilityType() {
160
+        return BackendService::VISIBILITY_ADMIN;
161
+    }
162
+
163
+    protected function isApplicable(StorageConfig $config) {
164
+        return true;
165
+    }
166
+
167
+    /**
168
+     * Get all configured admin and personal mounts
169
+     *
170
+     * @return array map of storage id to storage config
171
+     */
172
+    public function getStorageForAllUsers() {
173
+        $mounts = $this->dbConfig->getAllMounts();
174
+        $configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
175
+        $configs = array_filter($configs, function ($config) {
176
+            return $config instanceof StorageConfig;
177
+        });
178
+
179
+        $keys = array_map(function (StorageConfig $config) {
180
+            return $config->getId();
181
+        }, $configs);
182
+
183
+        return array_combine($keys, $configs);
184
+    }
185 185
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -172,11 +172,11 @@
 block discarded – undo
172 172
 	public function getStorageForAllUsers() {
173 173
 		$mounts = $this->dbConfig->getAllMounts();
174 174
 		$configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
175
-		$configs = array_filter($configs, function ($config) {
175
+		$configs = array_filter($configs, function($config) {
176 176
 			return $config instanceof StorageConfig;
177 177
 		});
178 178
 
179
-		$keys = array_map(function (StorageConfig $config) {
179
+		$keys = array_map(function(StorageConfig $config) {
180 180
 			return $config->getId();
181 181
 		}, $configs);
182 182
 
Please login to merge, or discard this patch.
apps/files_external/lib/Service/UserLegacyStoragesService.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -29,28 +29,28 @@
 block discarded – undo
29 29
  * Read user defined mounts from the legacy mount.json
30 30
  */
31 31
 class UserLegacyStoragesService extends LegacyStoragesService {
32
-	/**
33
-	 * @var IUserSession
34
-	 */
35
-	private $userSession;
32
+    /**
33
+     * @var IUserSession
34
+     */
35
+    private $userSession;
36 36
 
37
-	/**
38
-	 * @param BackendService $backendService
39
-	 * @param IUserSession $userSession
40
-	 */
41
-	public function __construct(BackendService $backendService, IUserSession $userSession) {
42
-		$this->backendService = $backendService;
43
-		$this->userSession = $userSession;
44
-	}
37
+    /**
38
+     * @param BackendService $backendService
39
+     * @param IUserSession $userSession
40
+     */
41
+    public function __construct(BackendService $backendService, IUserSession $userSession) {
42
+        $this->backendService = $backendService;
43
+        $this->userSession = $userSession;
44
+    }
45 45
 
46
-	/**
47
-	 * Read legacy config data
48
-	 *
49
-	 * @return array list of storage configs
50
-	 */
51
-	protected function readLegacyConfig() {
52
-		// read user config
53
-		$user = $this->userSession->getUser()->getUID();
54
-		return \OC_Mount_Config::readData($user);
55
-	}
46
+    /**
47
+     * Read legacy config data
48
+     *
49
+     * @return array list of storage configs
50
+     */
51
+    protected function readLegacyConfig() {
52
+        // read user config
53
+        $user = $this->userSession->getUser()->getUID();
54
+        return \OC_Mount_Config::readData($user);
55
+    }
56 56
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Service/DBConfigService.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function getAdminMountsForMultiple($type, array $values) {
180 180
 		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
181
+		$params = array_map(function($value) use ($builder) {
182 182
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183 183
 		}, $values);
184 184
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232 232
 			]);
233 233
 		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
234
+		return (int) $this->connection->lastInsertId('*PREFIX*external_mounts');
235 235
 	}
236 236
 
237 237
 	/**
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		$uniqueMounts = array_values($uniqueMounts);
369 369
 
370
-		$mountIds = array_map(function ($mount) {
370
+		$mountIds = array_map(function($mount) {
371 371
 			return $mount['mount_id'];
372 372
 		}, $uniqueMounts);
373 373
 		$mountIds = array_values(array_unique($mountIds));
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		$config = $this->getConfigForMounts($mountIds);
377 377
 		$options = $this->getOptionsForMounts($mountIds);
378 378
 
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
379
+		return array_map(function($mount, $applicable, $config, $options) {
380
+			$mount['type'] = (int) $mount['type'];
381
+			$mount['priority'] = (int) $mount['priority'];
382 382
 			$mount['applicable'] = $applicable;
383 383
 			$mount['config'] = $config;
384 384
 			$mount['options'] = $options;
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		}
401 401
 		$builder = $this->connection->getQueryBuilder();
402 402
 		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
403
+		$placeHolders = array_map(function($id) use ($builder) {
404 404
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405 405
 		}, $mountIds);
406 406
 		$query = $builder->select($fields)
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		foreach ($rows as $row) {
416 416
 			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
417
+				$row['type'] = (int) $row['type'];
418 418
 			}
419 419
 			$result[$row['mount_id']][] = $row;
420 420
 		}
@@ -445,8 +445,8 @@  discard block
 block discarded – undo
445 445
 	public function getOptionsForMounts($mountIds) {
446 446
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447 447
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
448
+		return array_map(function(array $options) {
449
+			return array_map(function($option) {
450 450
 				return json_decode($option);
451 451
 			}, $options);
452 452
 		}, $optionsMap);
@@ -457,16 +457,16 @@  discard block
 block discarded – undo
457 457
 	 * @return array ['key1' => $value1, ...]
458 458
 	 */
459 459
 	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
460
+		$decryptedPairts = array_map(function($pair) {
461 461
 			if ($pair['key'] === 'password') {
462 462
 				$pair['value'] = $this->decryptValue($pair['value']);
463 463
 			}
464 464
 			return $pair;
465 465
 		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
466
+		$keys = array_map(function($pair) {
467 467
 			return $pair['key'];
468 468
 		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
469
+		$values = array_map(function($pair) {
470 470
 			return $pair['value'];
471 471
 		}, $decryptedPairts);
472 472
 
Please login to merge, or discard this patch.
Indentation   +429 added lines, -429 removed lines patch added patch discarded remove patch
@@ -32,433 +32,433 @@
 block discarded – undo
32 32
  * Stores the mount config in the database
33 33
  */
34 34
 class DBConfigService {
35
-	const MOUNT_TYPE_ADMIN = 1;
36
-	const MOUNT_TYPE_PERSONAl = 2;
37
-
38
-	const APPLICABLE_TYPE_GLOBAL = 1;
39
-	const APPLICABLE_TYPE_GROUP = 2;
40
-	const APPLICABLE_TYPE_USER = 3;
41
-
42
-	/**
43
-	 * @var IDBConnection
44
-	 */
45
-	private $connection;
46
-
47
-	/**
48
-	 * @var ICrypto
49
-	 */
50
-	private $crypto;
51
-
52
-	/**
53
-	 * DBConfigService constructor.
54
-	 *
55
-	 * @param IDBConnection $connection
56
-	 * @param ICrypto $crypto
57
-	 */
58
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
-		$this->connection = $connection;
60
-		$this->crypto = $crypto;
61
-	}
62
-
63
-	/**
64
-	 * @param int $mountId
65
-	 * @return array
66
-	 */
67
-	public function getMountById($mountId) {
68
-		$builder = $this->connection->getQueryBuilder();
69
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
-			->from('external_mounts', 'm')
71
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
-		$mounts = $this->getMountsFromQuery($query);
73
-		if (count($mounts) > 0) {
74
-			return $mounts[0];
75
-		} else {
76
-			return null;
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Get all configured mounts
82
-	 *
83
-	 * @return array
84
-	 */
85
-	public function getAllMounts() {
86
-		$builder = $this->connection->getQueryBuilder();
87
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
-			->from('external_mounts');
89
-		return $this->getMountsFromQuery($query);
90
-	}
91
-
92
-	/**
93
-	 * Get admin defined mounts
94
-	 *
95
-	 * @return array
96
-	 */
97
-	public function getAdminMounts() {
98
-		$builder = $this->connection->getQueryBuilder();
99
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
100
-			->from('external_mounts')
101
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
102
-		return $this->getMountsFromQuery($query);
103
-	}
104
-
105
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
106
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
107
-			->from('external_mounts', 'm')
108
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
109
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
110
-
111
-		if (is_null($value)) {
112
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
113
-		} else {
114
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
115
-		}
116
-
117
-		return $query;
118
-	}
119
-
120
-	/**
121
-	 * Get mounts by applicable
122
-	 *
123
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
124
-	 * @param string|null $value user_id, group_id or null for global mounts
125
-	 * @return array
126
-	 */
127
-	public function getMountsFor($type, $value) {
128
-		$builder = $this->connection->getQueryBuilder();
129
-		$query = $this->getForQuery($builder, $type, $value);
130
-
131
-		return $this->getMountsFromQuery($query);
132
-	}
133
-
134
-	/**
135
-	 * Get admin defined mounts by applicable
136
-	 *
137
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
138
-	 * @param string|null $value user_id, group_id or null for global mounts
139
-	 * @return array
140
-	 */
141
-	public function getAdminMountsFor($type, $value) {
142
-		$builder = $this->connection->getQueryBuilder();
143
-		$query = $this->getForQuery($builder, $type, $value);
144
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
145
-
146
-		return $this->getMountsFromQuery($query);
147
-	}
148
-
149
-	/**
150
-	 * Get admin defined mounts for multiple applicable
151
-	 *
152
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
153
-	 * @param string[] $values user_ids or group_ids
154
-	 * @return array
155
-	 */
156
-	public function getAdminMountsForMultiple($type, array $values) {
157
-		$builder = $this->connection->getQueryBuilder();
158
-		$params = array_map(function ($value) use ($builder) {
159
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
160
-		}, $values);
161
-
162
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
163
-			->from('external_mounts', 'm')
164
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
165
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
166
-			->andWhere($builder->expr()->in('a.value', $params));
167
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
-
169
-		return $this->getMountsFromQuery($query);
170
-	}
171
-
172
-	/**
173
-	 * Get user defined mounts by applicable
174
-	 *
175
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
-	 * @param string|null $value user_id, group_id or null for global mounts
177
-	 * @return array
178
-	 */
179
-	public function getUserMountsFor($type, $value) {
180
-		$builder = $this->connection->getQueryBuilder();
181
-		$query = $this->getForQuery($builder, $type, $value);
182
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
183
-
184
-		return $this->getMountsFromQuery($query);
185
-	}
186
-
187
-	/**
188
-	 * Add a mount to the database
189
-	 *
190
-	 * @param string $mountPoint
191
-	 * @param string $storageBackend
192
-	 * @param string $authBackend
193
-	 * @param int $priority
194
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
195
-	 * @return int the id of the new mount
196
-	 */
197
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
198
-		if (!$priority) {
199
-			$priority = 100;
200
-		}
201
-		$builder = $this->connection->getQueryBuilder();
202
-		$query = $builder->insert('external_mounts')
203
-			->values([
204
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
205
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
206
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
207
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
208
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
209
-			]);
210
-		$query->execute();
211
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
212
-	}
213
-
214
-	/**
215
-	 * Remove a mount from the database
216
-	 *
217
-	 * @param int $mountId
218
-	 */
219
-	public function removeMount($mountId) {
220
-		$builder = $this->connection->getQueryBuilder();
221
-		$query = $builder->delete('external_mounts')
222
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
223
-		$query->execute();
224
-
225
-		$query = $builder->delete('external_applicable')
226
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
227
-		$query->execute();
228
-
229
-		$query = $builder->delete('external_config')
230
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
231
-		$query->execute();
232
-
233
-		$query = $builder->delete('external_options')
234
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
235
-		$query->execute();
236
-	}
237
-
238
-	/**
239
-	 * @param int $mountId
240
-	 * @param string $newMountPoint
241
-	 */
242
-	public function setMountPoint($mountId, $newMountPoint) {
243
-		$builder = $this->connection->getQueryBuilder();
244
-
245
-		$query = $builder->update('external_mounts')
246
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
247
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
248
-
249
-		$query->execute();
250
-	}
251
-
252
-	/**
253
-	 * @param int $mountId
254
-	 * @param string $newAuthBackend
255
-	 */
256
-	public function setAuthBackend($mountId, $newAuthBackend) {
257
-		$builder = $this->connection->getQueryBuilder();
258
-
259
-		$query = $builder->update('external_mounts')
260
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
261
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
-
263
-		$query->execute();
264
-	}
265
-
266
-	/**
267
-	 * @param int $mountId
268
-	 * @param string $key
269
-	 * @param string $value
270
-	 */
271
-	public function setConfig($mountId, $key, $value) {
272
-		if ($key === 'password') {
273
-			$value = $this->encryptValue($value);
274
-		}
275
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
276
-			'mount_id' => $mountId,
277
-			'key' => $key,
278
-			'value' => $value
279
-		], ['mount_id', 'key']);
280
-		if ($count === 0) {
281
-			$builder = $this->connection->getQueryBuilder();
282
-			$query = $builder->update('external_config')
283
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
284
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
285
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
286
-			$query->execute();
287
-		}
288
-	}
289
-
290
-	/**
291
-	 * @param int $mountId
292
-	 * @param string $key
293
-	 * @param string $value
294
-	 */
295
-	public function setOption($mountId, $key, $value) {
296
-
297
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
298
-			'mount_id' => $mountId,
299
-			'key' => $key,
300
-			'value' => json_encode($value)
301
-		], ['mount_id', 'key']);
302
-		if ($count === 0) {
303
-			$builder = $this->connection->getQueryBuilder();
304
-			$query = $builder->update('external_options')
305
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
306
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
307
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
308
-			$query->execute();
309
-		}
310
-	}
311
-
312
-	public function addApplicable($mountId, $type, $value) {
313
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
314
-			'mount_id' => $mountId,
315
-			'type' => $type,
316
-			'value' => $value
317
-		], ['mount_id', 'type', 'value']);
318
-	}
319
-
320
-	public function removeApplicable($mountId, $type, $value) {
321
-		$builder = $this->connection->getQueryBuilder();
322
-		$query = $builder->delete('external_applicable')
323
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
324
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
325
-
326
-		if (is_null($value)) {
327
-			$query = $query->andWhere($builder->expr()->isNull('value'));
328
-		} else {
329
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
330
-		}
331
-
332
-		$query->execute();
333
-	}
334
-
335
-	private function getMountsFromQuery(IQueryBuilder $query) {
336
-		$result = $query->execute();
337
-		$mounts = $result->fetchAll();
338
-		$uniqueMounts = [];
339
-		foreach ($mounts as $mount) {
340
-			$id = $mount['mount_id'];
341
-			if (!isset($uniqueMounts[$id])) {
342
-				$uniqueMounts[$id] = $mount;
343
-			}
344
-		}
345
-		$uniqueMounts = array_values($uniqueMounts);
346
-
347
-		$mountIds = array_map(function ($mount) {
348
-			return $mount['mount_id'];
349
-		}, $uniqueMounts);
350
-		$mountIds = array_values(array_unique($mountIds));
351
-
352
-		$applicable = $this->getApplicableForMounts($mountIds);
353
-		$config = $this->getConfigForMounts($mountIds);
354
-		$options = $this->getOptionsForMounts($mountIds);
355
-
356
-		return array_map(function ($mount, $applicable, $config, $options) {
357
-			$mount['type'] = (int)$mount['type'];
358
-			$mount['priority'] = (int)$mount['priority'];
359
-			$mount['applicable'] = $applicable;
360
-			$mount['config'] = $config;
361
-			$mount['options'] = $options;
362
-			return $mount;
363
-		}, $uniqueMounts, $applicable, $config, $options);
364
-	}
365
-
366
-	/**
367
-	 * Get mount options from a table grouped by mount id
368
-	 *
369
-	 * @param string $table
370
-	 * @param string[] $fields
371
-	 * @param int[] $mountIds
372
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
373
-	 */
374
-	private function selectForMounts($table, array $fields, array $mountIds) {
375
-		if (count($mountIds) === 0) {
376
-			return [];
377
-		}
378
-		$builder = $this->connection->getQueryBuilder();
379
-		$fields[] = 'mount_id';
380
-		$placeHolders = array_map(function ($id) use ($builder) {
381
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
382
-		}, $mountIds);
383
-		$query = $builder->select($fields)
384
-			->from($table)
385
-			->where($builder->expr()->in('mount_id', $placeHolders));
386
-		$rows = $query->execute()->fetchAll();
387
-
388
-		$result = [];
389
-		foreach ($mountIds as $mountId) {
390
-			$result[$mountId] = [];
391
-		}
392
-		foreach ($rows as $row) {
393
-			if (isset($row['type'])) {
394
-				$row['type'] = (int)$row['type'];
395
-			}
396
-			$result[$row['mount_id']][] = $row;
397
-		}
398
-		return $result;
399
-	}
400
-
401
-	/**
402
-	 * @param int[] $mountIds
403
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
404
-	 */
405
-	public function getApplicableForMounts($mountIds) {
406
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
407
-	}
408
-
409
-	/**
410
-	 * @param int[] $mountIds
411
-	 * @return array [$id => ['key1' => $value1, ...], ...]
412
-	 */
413
-	public function getConfigForMounts($mountIds) {
414
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
415
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
416
-	}
417
-
418
-	/**
419
-	 * @param int[] $mountIds
420
-	 * @return array [$id => ['key1' => $value1, ...], ...]
421
-	 */
422
-	public function getOptionsForMounts($mountIds) {
423
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
424
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
425
-		return array_map(function (array $options) {
426
-			return array_map(function ($option) {
427
-				return json_decode($option);
428
-			}, $options);
429
-		}, $optionsMap);
430
-	}
431
-
432
-	/**
433
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
434
-	 * @return array ['key1' => $value1, ...]
435
-	 */
436
-	private function createKeyValueMap(array $keyValuePairs) {
437
-		$decryptedPairts = array_map(function ($pair) {
438
-			if ($pair['key'] === 'password') {
439
-				$pair['value'] = $this->decryptValue($pair['value']);
440
-			}
441
-			return $pair;
442
-		}, $keyValuePairs);
443
-		$keys = array_map(function ($pair) {
444
-			return $pair['key'];
445
-		}, $decryptedPairts);
446
-		$values = array_map(function ($pair) {
447
-			return $pair['value'];
448
-		}, $decryptedPairts);
449
-
450
-		return array_combine($keys, $values);
451
-	}
452
-
453
-	private function encryptValue($value) {
454
-		return $this->crypto->encrypt($value);
455
-	}
456
-
457
-	private function decryptValue($value) {
458
-		try {
459
-			return $this->crypto->decrypt($value);
460
-		} catch (\Exception $e) {
461
-			return $value;
462
-		}
463
-	}
35
+    const MOUNT_TYPE_ADMIN = 1;
36
+    const MOUNT_TYPE_PERSONAl = 2;
37
+
38
+    const APPLICABLE_TYPE_GLOBAL = 1;
39
+    const APPLICABLE_TYPE_GROUP = 2;
40
+    const APPLICABLE_TYPE_USER = 3;
41
+
42
+    /**
43
+     * @var IDBConnection
44
+     */
45
+    private $connection;
46
+
47
+    /**
48
+     * @var ICrypto
49
+     */
50
+    private $crypto;
51
+
52
+    /**
53
+     * DBConfigService constructor.
54
+     *
55
+     * @param IDBConnection $connection
56
+     * @param ICrypto $crypto
57
+     */
58
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
+        $this->connection = $connection;
60
+        $this->crypto = $crypto;
61
+    }
62
+
63
+    /**
64
+     * @param int $mountId
65
+     * @return array
66
+     */
67
+    public function getMountById($mountId) {
68
+        $builder = $this->connection->getQueryBuilder();
69
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
+            ->from('external_mounts', 'm')
71
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
+        $mounts = $this->getMountsFromQuery($query);
73
+        if (count($mounts) > 0) {
74
+            return $mounts[0];
75
+        } else {
76
+            return null;
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Get all configured mounts
82
+     *
83
+     * @return array
84
+     */
85
+    public function getAllMounts() {
86
+        $builder = $this->connection->getQueryBuilder();
87
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
+            ->from('external_mounts');
89
+        return $this->getMountsFromQuery($query);
90
+    }
91
+
92
+    /**
93
+     * Get admin defined mounts
94
+     *
95
+     * @return array
96
+     */
97
+    public function getAdminMounts() {
98
+        $builder = $this->connection->getQueryBuilder();
99
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
100
+            ->from('external_mounts')
101
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
102
+        return $this->getMountsFromQuery($query);
103
+    }
104
+
105
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
106
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
107
+            ->from('external_mounts', 'm')
108
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
109
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
110
+
111
+        if (is_null($value)) {
112
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
113
+        } else {
114
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
115
+        }
116
+
117
+        return $query;
118
+    }
119
+
120
+    /**
121
+     * Get mounts by applicable
122
+     *
123
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
124
+     * @param string|null $value user_id, group_id or null for global mounts
125
+     * @return array
126
+     */
127
+    public function getMountsFor($type, $value) {
128
+        $builder = $this->connection->getQueryBuilder();
129
+        $query = $this->getForQuery($builder, $type, $value);
130
+
131
+        return $this->getMountsFromQuery($query);
132
+    }
133
+
134
+    /**
135
+     * Get admin defined mounts by applicable
136
+     *
137
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
138
+     * @param string|null $value user_id, group_id or null for global mounts
139
+     * @return array
140
+     */
141
+    public function getAdminMountsFor($type, $value) {
142
+        $builder = $this->connection->getQueryBuilder();
143
+        $query = $this->getForQuery($builder, $type, $value);
144
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
145
+
146
+        return $this->getMountsFromQuery($query);
147
+    }
148
+
149
+    /**
150
+     * Get admin defined mounts for multiple applicable
151
+     *
152
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
153
+     * @param string[] $values user_ids or group_ids
154
+     * @return array
155
+     */
156
+    public function getAdminMountsForMultiple($type, array $values) {
157
+        $builder = $this->connection->getQueryBuilder();
158
+        $params = array_map(function ($value) use ($builder) {
159
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
160
+        }, $values);
161
+
162
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
163
+            ->from('external_mounts', 'm')
164
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
165
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
166
+            ->andWhere($builder->expr()->in('a.value', $params));
167
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
+
169
+        return $this->getMountsFromQuery($query);
170
+    }
171
+
172
+    /**
173
+     * Get user defined mounts by applicable
174
+     *
175
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
+     * @param string|null $value user_id, group_id or null for global mounts
177
+     * @return array
178
+     */
179
+    public function getUserMountsFor($type, $value) {
180
+        $builder = $this->connection->getQueryBuilder();
181
+        $query = $this->getForQuery($builder, $type, $value);
182
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
183
+
184
+        return $this->getMountsFromQuery($query);
185
+    }
186
+
187
+    /**
188
+     * Add a mount to the database
189
+     *
190
+     * @param string $mountPoint
191
+     * @param string $storageBackend
192
+     * @param string $authBackend
193
+     * @param int $priority
194
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
195
+     * @return int the id of the new mount
196
+     */
197
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
198
+        if (!$priority) {
199
+            $priority = 100;
200
+        }
201
+        $builder = $this->connection->getQueryBuilder();
202
+        $query = $builder->insert('external_mounts')
203
+            ->values([
204
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
205
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
206
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
207
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
208
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
209
+            ]);
210
+        $query->execute();
211
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
212
+    }
213
+
214
+    /**
215
+     * Remove a mount from the database
216
+     *
217
+     * @param int $mountId
218
+     */
219
+    public function removeMount($mountId) {
220
+        $builder = $this->connection->getQueryBuilder();
221
+        $query = $builder->delete('external_mounts')
222
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
223
+        $query->execute();
224
+
225
+        $query = $builder->delete('external_applicable')
226
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
227
+        $query->execute();
228
+
229
+        $query = $builder->delete('external_config')
230
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
231
+        $query->execute();
232
+
233
+        $query = $builder->delete('external_options')
234
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
235
+        $query->execute();
236
+    }
237
+
238
+    /**
239
+     * @param int $mountId
240
+     * @param string $newMountPoint
241
+     */
242
+    public function setMountPoint($mountId, $newMountPoint) {
243
+        $builder = $this->connection->getQueryBuilder();
244
+
245
+        $query = $builder->update('external_mounts')
246
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
247
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
248
+
249
+        $query->execute();
250
+    }
251
+
252
+    /**
253
+     * @param int $mountId
254
+     * @param string $newAuthBackend
255
+     */
256
+    public function setAuthBackend($mountId, $newAuthBackend) {
257
+        $builder = $this->connection->getQueryBuilder();
258
+
259
+        $query = $builder->update('external_mounts')
260
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
261
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
+
263
+        $query->execute();
264
+    }
265
+
266
+    /**
267
+     * @param int $mountId
268
+     * @param string $key
269
+     * @param string $value
270
+     */
271
+    public function setConfig($mountId, $key, $value) {
272
+        if ($key === 'password') {
273
+            $value = $this->encryptValue($value);
274
+        }
275
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
276
+            'mount_id' => $mountId,
277
+            'key' => $key,
278
+            'value' => $value
279
+        ], ['mount_id', 'key']);
280
+        if ($count === 0) {
281
+            $builder = $this->connection->getQueryBuilder();
282
+            $query = $builder->update('external_config')
283
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
284
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
285
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
286
+            $query->execute();
287
+        }
288
+    }
289
+
290
+    /**
291
+     * @param int $mountId
292
+     * @param string $key
293
+     * @param string $value
294
+     */
295
+    public function setOption($mountId, $key, $value) {
296
+
297
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
298
+            'mount_id' => $mountId,
299
+            'key' => $key,
300
+            'value' => json_encode($value)
301
+        ], ['mount_id', 'key']);
302
+        if ($count === 0) {
303
+            $builder = $this->connection->getQueryBuilder();
304
+            $query = $builder->update('external_options')
305
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
306
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
307
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
308
+            $query->execute();
309
+        }
310
+    }
311
+
312
+    public function addApplicable($mountId, $type, $value) {
313
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
314
+            'mount_id' => $mountId,
315
+            'type' => $type,
316
+            'value' => $value
317
+        ], ['mount_id', 'type', 'value']);
318
+    }
319
+
320
+    public function removeApplicable($mountId, $type, $value) {
321
+        $builder = $this->connection->getQueryBuilder();
322
+        $query = $builder->delete('external_applicable')
323
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
324
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
325
+
326
+        if (is_null($value)) {
327
+            $query = $query->andWhere($builder->expr()->isNull('value'));
328
+        } else {
329
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
330
+        }
331
+
332
+        $query->execute();
333
+    }
334
+
335
+    private function getMountsFromQuery(IQueryBuilder $query) {
336
+        $result = $query->execute();
337
+        $mounts = $result->fetchAll();
338
+        $uniqueMounts = [];
339
+        foreach ($mounts as $mount) {
340
+            $id = $mount['mount_id'];
341
+            if (!isset($uniqueMounts[$id])) {
342
+                $uniqueMounts[$id] = $mount;
343
+            }
344
+        }
345
+        $uniqueMounts = array_values($uniqueMounts);
346
+
347
+        $mountIds = array_map(function ($mount) {
348
+            return $mount['mount_id'];
349
+        }, $uniqueMounts);
350
+        $mountIds = array_values(array_unique($mountIds));
351
+
352
+        $applicable = $this->getApplicableForMounts($mountIds);
353
+        $config = $this->getConfigForMounts($mountIds);
354
+        $options = $this->getOptionsForMounts($mountIds);
355
+
356
+        return array_map(function ($mount, $applicable, $config, $options) {
357
+            $mount['type'] = (int)$mount['type'];
358
+            $mount['priority'] = (int)$mount['priority'];
359
+            $mount['applicable'] = $applicable;
360
+            $mount['config'] = $config;
361
+            $mount['options'] = $options;
362
+            return $mount;
363
+        }, $uniqueMounts, $applicable, $config, $options);
364
+    }
365
+
366
+    /**
367
+     * Get mount options from a table grouped by mount id
368
+     *
369
+     * @param string $table
370
+     * @param string[] $fields
371
+     * @param int[] $mountIds
372
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
373
+     */
374
+    private function selectForMounts($table, array $fields, array $mountIds) {
375
+        if (count($mountIds) === 0) {
376
+            return [];
377
+        }
378
+        $builder = $this->connection->getQueryBuilder();
379
+        $fields[] = 'mount_id';
380
+        $placeHolders = array_map(function ($id) use ($builder) {
381
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
382
+        }, $mountIds);
383
+        $query = $builder->select($fields)
384
+            ->from($table)
385
+            ->where($builder->expr()->in('mount_id', $placeHolders));
386
+        $rows = $query->execute()->fetchAll();
387
+
388
+        $result = [];
389
+        foreach ($mountIds as $mountId) {
390
+            $result[$mountId] = [];
391
+        }
392
+        foreach ($rows as $row) {
393
+            if (isset($row['type'])) {
394
+                $row['type'] = (int)$row['type'];
395
+            }
396
+            $result[$row['mount_id']][] = $row;
397
+        }
398
+        return $result;
399
+    }
400
+
401
+    /**
402
+     * @param int[] $mountIds
403
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
404
+     */
405
+    public function getApplicableForMounts($mountIds) {
406
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
407
+    }
408
+
409
+    /**
410
+     * @param int[] $mountIds
411
+     * @return array [$id => ['key1' => $value1, ...], ...]
412
+     */
413
+    public function getConfigForMounts($mountIds) {
414
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
415
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
416
+    }
417
+
418
+    /**
419
+     * @param int[] $mountIds
420
+     * @return array [$id => ['key1' => $value1, ...], ...]
421
+     */
422
+    public function getOptionsForMounts($mountIds) {
423
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
424
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
425
+        return array_map(function (array $options) {
426
+            return array_map(function ($option) {
427
+                return json_decode($option);
428
+            }, $options);
429
+        }, $optionsMap);
430
+    }
431
+
432
+    /**
433
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
434
+     * @return array ['key1' => $value1, ...]
435
+     */
436
+    private function createKeyValueMap(array $keyValuePairs) {
437
+        $decryptedPairts = array_map(function ($pair) {
438
+            if ($pair['key'] === 'password') {
439
+                $pair['value'] = $this->decryptValue($pair['value']);
440
+            }
441
+            return $pair;
442
+        }, $keyValuePairs);
443
+        $keys = array_map(function ($pair) {
444
+            return $pair['key'];
445
+        }, $decryptedPairts);
446
+        $values = array_map(function ($pair) {
447
+            return $pair['value'];
448
+        }, $decryptedPairts);
449
+
450
+        return array_combine($keys, $values);
451
+    }
452
+
453
+    private function encryptValue($value) {
454
+        return $this->crypto->encrypt($value);
455
+    }
456
+
457
+    private function decryptValue($value) {
458
+        try {
459
+            return $this->crypto->decrypt($value);
460
+        } catch (\Exception $e) {
461
+            return $value;
462
+        }
463
+    }
464 464
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Service/LegacyStoragesService.php 2 patches
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -30,183 +30,183 @@
 block discarded – undo
30 30
  * Read mount config from legacy mount.json
31 31
  */
32 32
 abstract class LegacyStoragesService {
33
-	/** @var BackendService */
34
-	protected $backendService;
33
+    /** @var BackendService */
34
+    protected $backendService;
35 35
 
36
-	/**
37
-	 * Read legacy config data
38
-	 *
39
-	 * @return array list of mount configs
40
-	 */
41
-	abstract protected function readLegacyConfig();
36
+    /**
37
+     * Read legacy config data
38
+     *
39
+     * @return array list of mount configs
40
+     */
41
+    abstract protected function readLegacyConfig();
42 42
 
43
-	/**
44
-	 * Copy legacy storage options into the given storage config object.
45
-	 *
46
-	 * @param StorageConfig $storageConfig storage config to populate
47
-	 * @param string $mountType mount type
48
-	 * @param string $applicable applicable user or group
49
-	 * @param array $storageOptions legacy storage options
50
-	 *
51
-	 * @return StorageConfig populated storage config
52
-	 */
53
-	protected function populateStorageConfigWithLegacyOptions(
54
-		&$storageConfig,
55
-		$mountType,
56
-		$applicable,
57
-		$storageOptions
58
-	) {
59
-		$backend = $this->backendService->getBackend($storageOptions['backend']);
60
-		if (!$backend) {
61
-			throw new \UnexpectedValueException('Invalid backend ' . $storageOptions['backend']);
62
-		}
63
-		$storageConfig->setBackend($backend);
64
-		if (isset($storageOptions['authMechanism']) && $storageOptions['authMechanism'] !== 'builtin::builtin') {
65
-			$authMechanism = $this->backendService->getAuthMechanism($storageOptions['authMechanism']);
66
-		} else {
67
-			$authMechanism = $backend->getLegacyAuthMechanism($storageOptions);
68
-			$storageOptions['authMechanism'] = 'null'; // to make error handling easier
69
-		}
70
-		if (!$authMechanism) {
71
-			throw new \UnexpectedValueException('Invalid authentication mechanism ' . $storageOptions['authMechanism']);
72
-		}
73
-		$storageConfig->setAuthMechanism($authMechanism);
74
-		$storageConfig->setBackendOptions($storageOptions['options']);
75
-		if (isset($storageOptions['mountOptions'])) {
76
-			$storageConfig->setMountOptions($storageOptions['mountOptions']);
77
-		}
78
-		if (!isset($storageOptions['priority'])) {
79
-			$storageOptions['priority'] = $backend->getPriority();
80
-		}
81
-		$storageConfig->setPriority($storageOptions['priority']);
82
-		if ($mountType === \OC_Mount_Config::MOUNT_TYPE_USER) {
83
-			$applicableUsers = $storageConfig->getApplicableUsers();
84
-			if ($applicable !== 'all') {
85
-				$applicableUsers[] = $applicable;
86
-				$storageConfig->setApplicableUsers($applicableUsers);
87
-			}
88
-		} else if ($mountType === \OC_Mount_Config::MOUNT_TYPE_GROUP) {
89
-			$applicableGroups = $storageConfig->getApplicableGroups();
90
-			$applicableGroups[] = $applicable;
91
-			$storageConfig->setApplicableGroups($applicableGroups);
92
-		}
93
-		return $storageConfig;
94
-	}
43
+    /**
44
+     * Copy legacy storage options into the given storage config object.
45
+     *
46
+     * @param StorageConfig $storageConfig storage config to populate
47
+     * @param string $mountType mount type
48
+     * @param string $applicable applicable user or group
49
+     * @param array $storageOptions legacy storage options
50
+     *
51
+     * @return StorageConfig populated storage config
52
+     */
53
+    protected function populateStorageConfigWithLegacyOptions(
54
+        &$storageConfig,
55
+        $mountType,
56
+        $applicable,
57
+        $storageOptions
58
+    ) {
59
+        $backend = $this->backendService->getBackend($storageOptions['backend']);
60
+        if (!$backend) {
61
+            throw new \UnexpectedValueException('Invalid backend ' . $storageOptions['backend']);
62
+        }
63
+        $storageConfig->setBackend($backend);
64
+        if (isset($storageOptions['authMechanism']) && $storageOptions['authMechanism'] !== 'builtin::builtin') {
65
+            $authMechanism = $this->backendService->getAuthMechanism($storageOptions['authMechanism']);
66
+        } else {
67
+            $authMechanism = $backend->getLegacyAuthMechanism($storageOptions);
68
+            $storageOptions['authMechanism'] = 'null'; // to make error handling easier
69
+        }
70
+        if (!$authMechanism) {
71
+            throw new \UnexpectedValueException('Invalid authentication mechanism ' . $storageOptions['authMechanism']);
72
+        }
73
+        $storageConfig->setAuthMechanism($authMechanism);
74
+        $storageConfig->setBackendOptions($storageOptions['options']);
75
+        if (isset($storageOptions['mountOptions'])) {
76
+            $storageConfig->setMountOptions($storageOptions['mountOptions']);
77
+        }
78
+        if (!isset($storageOptions['priority'])) {
79
+            $storageOptions['priority'] = $backend->getPriority();
80
+        }
81
+        $storageConfig->setPriority($storageOptions['priority']);
82
+        if ($mountType === \OC_Mount_Config::MOUNT_TYPE_USER) {
83
+            $applicableUsers = $storageConfig->getApplicableUsers();
84
+            if ($applicable !== 'all') {
85
+                $applicableUsers[] = $applicable;
86
+                $storageConfig->setApplicableUsers($applicableUsers);
87
+            }
88
+        } else if ($mountType === \OC_Mount_Config::MOUNT_TYPE_GROUP) {
89
+            $applicableGroups = $storageConfig->getApplicableGroups();
90
+            $applicableGroups[] = $applicable;
91
+            $storageConfig->setApplicableGroups($applicableGroups);
92
+        }
93
+        return $storageConfig;
94
+    }
95 95
 
96
-	/**
97
-	 * Read the external storages config
98
-	 *
99
-	 * @return StorageConfig[] map of storage id to storage config
100
-	 */
101
-	public function getAllStorages() {
102
-		$mountPoints = $this->readLegacyConfig();
103
-		/**
104
-		 * Here is the how the horribly messy mount point array looks like
105
-		 * from the mount.json file:
106
-		 *
107
-		 * $storageOptions = $mountPoints[$mountType][$applicable][$mountPath]
108
-		 *
109
-		 * - $mountType is either "user" or "group"
110
-		 * - $applicable is the name of a user or group (or the current user for personal mounts)
111
-		 * - $mountPath is the mount point path (where the storage must be mounted)
112
-		 * - $storageOptions is a map of storage options:
113
-		 *     - "priority": storage priority
114
-		 *     - "backend": backend identifier
115
-		 *     - "class": LEGACY backend class name
116
-		 *     - "options": backend-specific options
117
-		 *     - "authMechanism": authentication mechanism identifier
118
-		 *     - "mountOptions": mount-specific options (ex: disable previews, scanner, etc)
119
-		 */
120
-		// group by storage id
121
-		/** @var StorageConfig[] $storages */
122
-		$storages = [];
123
-		// for storages without id (legacy), group by config hash for
124
-		// later processing
125
-		$storagesWithConfigHash = [];
126
-		foreach ($mountPoints as $mountType => $applicables) {
127
-			foreach ($applicables as $applicable => $mountPaths) {
128
-				foreach ($mountPaths as $rootMountPath => $storageOptions) {
129
-					$currentStorage = null;
130
-					/**
131
-					 * Flag whether the config that was read already has an id.
132
-					 * If not, it will use a config hash instead and generate
133
-					 * a proper id later
134
-					 *
135
-					 * @var boolean
136
-					 */
137
-					$hasId = false;
138
-					// the root mount point is in the format "/$user/files/the/mount/point"
139
-					// we remove the "/$user/files" prefix
140
-					$parts = explode('/', ltrim($rootMountPath, '/'), 3);
141
-					if (count($parts) < 3) {
142
-						// something went wrong, skip
143
-						\OCP\Util::writeLog(
144
-							'files_external',
145
-							'Could not parse mount point "' . $rootMountPath . '"',
146
-							\OCP\Util::ERROR
147
-						);
148
-						continue;
149
-					}
150
-					$relativeMountPath = rtrim($parts[2], '/');
151
-					// note: we cannot do this after the loop because the decrypted config
152
-					// options might be needed for the config hash
153
-					$storageOptions['options'] = \OC_Mount_Config::decryptPasswords($storageOptions['options']);
154
-					if (!isset($storageOptions['backend'])) {
155
-						$storageOptions['backend'] = $storageOptions['class']; // legacy compat
156
-					}
157
-					if (!isset($storageOptions['authMechanism'])) {
158
-						$storageOptions['authMechanism'] = null; // ensure config hash works
159
-					}
160
-					if (isset($storageOptions['id'])) {
161
-						$configId = (int)$storageOptions['id'];
162
-						if (isset($storages[$configId])) {
163
-							$currentStorage = $storages[$configId];
164
-						}
165
-						$hasId = true;
166
-					} else {
167
-						// missing id in legacy config, need to generate
168
-						// but at this point we don't know the max-id, so use
169
-						// first group it by config hash
170
-						$storageOptions['mountpoint'] = $rootMountPath;
171
-						$configId = \OC_Mount_Config::makeConfigHash($storageOptions);
172
-						if (isset($storagesWithConfigHash[$configId])) {
173
-							$currentStorage = $storagesWithConfigHash[$configId];
174
-						}
175
-					}
176
-					if (is_null($currentStorage)) {
177
-						// create new
178
-						$currentStorage = new StorageConfig($configId);
179
-						$currentStorage->setMountPoint($relativeMountPath);
180
-					}
181
-					try {
182
-						$this->populateStorageConfigWithLegacyOptions(
183
-							$currentStorage,
184
-							$mountType,
185
-							$applicable,
186
-							$storageOptions
187
-						);
188
-						if ($hasId) {
189
-							$storages[$configId] = $currentStorage;
190
-						} else {
191
-							$storagesWithConfigHash[$configId] = $currentStorage;
192
-						}
193
-					} catch (\UnexpectedValueException $e) {
194
-						// don't die if a storage backend doesn't exist
195
-						\OCP\Util::writeLog(
196
-							'files_external',
197
-							'Could not load storage: "' . $e->getMessage() . '"',
198
-							\OCP\Util::ERROR
199
-						);
200
-					}
201
-				}
202
-			}
203
-		}
96
+    /**
97
+     * Read the external storages config
98
+     *
99
+     * @return StorageConfig[] map of storage id to storage config
100
+     */
101
+    public function getAllStorages() {
102
+        $mountPoints = $this->readLegacyConfig();
103
+        /**
104
+         * Here is the how the horribly messy mount point array looks like
105
+         * from the mount.json file:
106
+         *
107
+         * $storageOptions = $mountPoints[$mountType][$applicable][$mountPath]
108
+         *
109
+         * - $mountType is either "user" or "group"
110
+         * - $applicable is the name of a user or group (or the current user for personal mounts)
111
+         * - $mountPath is the mount point path (where the storage must be mounted)
112
+         * - $storageOptions is a map of storage options:
113
+         *     - "priority": storage priority
114
+         *     - "backend": backend identifier
115
+         *     - "class": LEGACY backend class name
116
+         *     - "options": backend-specific options
117
+         *     - "authMechanism": authentication mechanism identifier
118
+         *     - "mountOptions": mount-specific options (ex: disable previews, scanner, etc)
119
+         */
120
+        // group by storage id
121
+        /** @var StorageConfig[] $storages */
122
+        $storages = [];
123
+        // for storages without id (legacy), group by config hash for
124
+        // later processing
125
+        $storagesWithConfigHash = [];
126
+        foreach ($mountPoints as $mountType => $applicables) {
127
+            foreach ($applicables as $applicable => $mountPaths) {
128
+                foreach ($mountPaths as $rootMountPath => $storageOptions) {
129
+                    $currentStorage = null;
130
+                    /**
131
+                     * Flag whether the config that was read already has an id.
132
+                     * If not, it will use a config hash instead and generate
133
+                     * a proper id later
134
+                     *
135
+                     * @var boolean
136
+                     */
137
+                    $hasId = false;
138
+                    // the root mount point is in the format "/$user/files/the/mount/point"
139
+                    // we remove the "/$user/files" prefix
140
+                    $parts = explode('/', ltrim($rootMountPath, '/'), 3);
141
+                    if (count($parts) < 3) {
142
+                        // something went wrong, skip
143
+                        \OCP\Util::writeLog(
144
+                            'files_external',
145
+                            'Could not parse mount point "' . $rootMountPath . '"',
146
+                            \OCP\Util::ERROR
147
+                        );
148
+                        continue;
149
+                    }
150
+                    $relativeMountPath = rtrim($parts[2], '/');
151
+                    // note: we cannot do this after the loop because the decrypted config
152
+                    // options might be needed for the config hash
153
+                    $storageOptions['options'] = \OC_Mount_Config::decryptPasswords($storageOptions['options']);
154
+                    if (!isset($storageOptions['backend'])) {
155
+                        $storageOptions['backend'] = $storageOptions['class']; // legacy compat
156
+                    }
157
+                    if (!isset($storageOptions['authMechanism'])) {
158
+                        $storageOptions['authMechanism'] = null; // ensure config hash works
159
+                    }
160
+                    if (isset($storageOptions['id'])) {
161
+                        $configId = (int)$storageOptions['id'];
162
+                        if (isset($storages[$configId])) {
163
+                            $currentStorage = $storages[$configId];
164
+                        }
165
+                        $hasId = true;
166
+                    } else {
167
+                        // missing id in legacy config, need to generate
168
+                        // but at this point we don't know the max-id, so use
169
+                        // first group it by config hash
170
+                        $storageOptions['mountpoint'] = $rootMountPath;
171
+                        $configId = \OC_Mount_Config::makeConfigHash($storageOptions);
172
+                        if (isset($storagesWithConfigHash[$configId])) {
173
+                            $currentStorage = $storagesWithConfigHash[$configId];
174
+                        }
175
+                    }
176
+                    if (is_null($currentStorage)) {
177
+                        // create new
178
+                        $currentStorage = new StorageConfig($configId);
179
+                        $currentStorage->setMountPoint($relativeMountPath);
180
+                    }
181
+                    try {
182
+                        $this->populateStorageConfigWithLegacyOptions(
183
+                            $currentStorage,
184
+                            $mountType,
185
+                            $applicable,
186
+                            $storageOptions
187
+                        );
188
+                        if ($hasId) {
189
+                            $storages[$configId] = $currentStorage;
190
+                        } else {
191
+                            $storagesWithConfigHash[$configId] = $currentStorage;
192
+                        }
193
+                    } catch (\UnexpectedValueException $e) {
194
+                        // don't die if a storage backend doesn't exist
195
+                        \OCP\Util::writeLog(
196
+                            'files_external',
197
+                            'Could not load storage: "' . $e->getMessage() . '"',
198
+                            \OCP\Util::ERROR
199
+                        );
200
+                    }
201
+                }
202
+            }
203
+        }
204 204
 
205
-		// convert parameter values
206
-		foreach ($storages as $storage) {
207
-			$storage->getBackend()->validateStorageDefinition($storage);
208
-			$storage->getAuthMechanism()->validateStorageDefinition($storage);
209
-		}
210
-		return $storages;
211
-	}
205
+        // convert parameter values
206
+        foreach ($storages as $storage) {
207
+            $storage->getBackend()->validateStorageDefinition($storage);
208
+            $storage->getAuthMechanism()->validateStorageDefinition($storage);
209
+        }
210
+        return $storages;
211
+    }
212 212
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	) {
59 59
 		$backend = $this->backendService->getBackend($storageOptions['backend']);
60 60
 		if (!$backend) {
61
-			throw new \UnexpectedValueException('Invalid backend ' . $storageOptions['backend']);
61
+			throw new \UnexpectedValueException('Invalid backend '.$storageOptions['backend']);
62 62
 		}
63 63
 		$storageConfig->setBackend($backend);
64 64
 		if (isset($storageOptions['authMechanism']) && $storageOptions['authMechanism'] !== 'builtin::builtin') {
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 			$storageOptions['authMechanism'] = 'null'; // to make error handling easier
69 69
 		}
70 70
 		if (!$authMechanism) {
71
-			throw new \UnexpectedValueException('Invalid authentication mechanism ' . $storageOptions['authMechanism']);
71
+			throw new \UnexpectedValueException('Invalid authentication mechanism '.$storageOptions['authMechanism']);
72 72
 		}
73 73
 		$storageConfig->setAuthMechanism($authMechanism);
74 74
 		$storageConfig->setBackendOptions($storageOptions['options']);
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 						// something went wrong, skip
143 143
 						\OCP\Util::writeLog(
144 144
 							'files_external',
145
-							'Could not parse mount point "' . $rootMountPath . '"',
145
+							'Could not parse mount point "'.$rootMountPath.'"',
146 146
 							\OCP\Util::ERROR
147 147
 						);
148 148
 						continue;
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 						$storageOptions['authMechanism'] = null; // ensure config hash works
159 159
 					}
160 160
 					if (isset($storageOptions['id'])) {
161
-						$configId = (int)$storageOptions['id'];
161
+						$configId = (int) $storageOptions['id'];
162 162
 						if (isset($storages[$configId])) {
163 163
 							$currentStorage = $storages[$configId];
164 164
 						}
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 						// don't die if a storage backend doesn't exist
195 195
 						\OCP\Util::writeLog(
196 196
 							'files_external',
197
-							'Could not load storage: "' . $e->getMessage() . '"',
197
+							'Could not load storage: "'.$e->getMessage().'"',
198 198
 							\OCP\Util::ERROR
199 199
 						);
200 200
 					}
Please login to merge, or discard this patch.